Release 5.13h
[org-mode/org-tableheadings.git] / org.el
blob96c9e90beb618eac26725073d6520b77f0f50226
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 5.13h
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 ;;;; Require other packages
69 (eval-when-compile
70 (require 'cl)
71 (require 'gnus-sum)
72 (require 'calendar))
73 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
74 ;; the file noutline.el being loaded.
75 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
76 ;; We require noutline, which might be provided in outline.el
77 (require 'outline) (require 'noutline)
78 ;; Other stuff we need.
79 (require 'time-date)
80 (require 'easymenu)
82 ;;;; Customization variables
84 ;;; Version
86 (defconst org-version "5.13h"
87 "The version number of the file org.el.")
88 (defun org-version ()
89 (interactive)
90 (message "Org-mode version %s" org-version))
92 ;;; Compatibility constants
93 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
94 (defconst org-format-transports-properties-p
95 (let ((x "a"))
96 (add-text-properties 0 1 '(test t) x)
97 (get-text-property 0 'test (format "%s" x)))
98 "Does format transport text properties?")
100 (defmacro org-unmodified (&rest body)
101 "Execute body without changing buffer-modified-p."
102 `(set-buffer-modified-p
103 (prog1 (buffer-modified-p) ,@body)))
105 (defmacro org-re (s)
106 "Replace posix classes in regular expression."
107 (if (featurep 'xemacs)
108 (let ((ss s))
109 (save-match-data
110 (while (string-match "\\[:alnum:\\]" ss)
111 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
112 (while (string-match "\\[:alpha:\\]" ss)
113 (setq ss (replace-match "a-zA-Z" t t ss)))
114 ss))
117 (defmacro org-preserve-lc (&rest body)
118 `(let ((_line (org-current-line))
119 (_col (current-column)))
120 (unwind-protect
121 (progn ,@body)
122 (goto-line _line)
123 (move-to-column _col))))
125 (defmacro org-without-partial-completion (&rest body)
126 `(let ((pc-mode (and (boundp 'partial-completion-mode)
127 partial-completion-mode)))
128 (unwind-protect
129 (progn
130 (if pc-mode (partial-completion-mode -1))
131 ,@body)
132 (if pc-mode (partial-completion-mode 1)))))
134 ;;; The custom variables
136 (defgroup org nil
137 "Outline-based notes management and organizer."
138 :tag "Org"
139 :group 'outlines
140 :group 'hypermedia
141 :group 'calendar)
143 ;; FIXME: Needs a separate group...
144 (defcustom org-completion-fallback-command 'hippie-expand
145 "The expansion command called by \\[org-complete] in normal context.
146 Normal means, no org-mode-specific context."
147 :group 'org
148 :type 'function)
150 (defgroup org-startup nil
151 "Options concerning startup of Org-mode."
152 :tag "Org Startup"
153 :group 'org)
155 (defcustom org-startup-folded t
156 "Non-nil means, entering Org-mode will switch to OVERVIEW.
157 This can also be configured on a per-file basis by adding one of
158 the following lines anywhere in the buffer:
160 #+STARTUP: fold
161 #+STARTUP: nofold
162 #+STARTUP: content"
163 :group 'org-startup
164 :type '(choice
165 (const :tag "nofold: show all" nil)
166 (const :tag "fold: overview" t)
167 (const :tag "content: all headlines" content)))
169 (defcustom org-startup-truncated t
170 "Non-nil means, entering Org-mode will set `truncate-lines'.
171 This is useful since some lines containing links can be very long and
172 uninteresting. Also tables look terrible when wrapped."
173 :group 'org-startup
174 :type 'boolean)
176 (defcustom org-startup-align-all-tables nil
177 "Non-nil means, align all tables when visiting a file.
178 This is useful when the column width in tables is forced with <N> cookies
179 in table fields. Such tables will look correct only after the first re-align.
180 This can also be configured on a per-file basis by adding one of
181 the following lines anywhere in the buffer:
182 #+STARTUP: align
183 #+STARTUP: noalign"
184 :group 'org-startup
185 :type 'boolean)
187 (defcustom org-insert-mode-line-in-empty-file nil
188 "Non-nil means insert the first line setting Org-mode in empty files.
189 When the function `org-mode' is called interactively in an empty file, this
190 normally means that the file name does not automatically trigger Org-mode.
191 To ensure that the file will always be in Org-mode in the future, a
192 line enforcing Org-mode will be inserted into the buffer, if this option
193 has been set."
194 :group 'org-startup
195 :type 'boolean)
197 (defcustom org-replace-disputed-keys nil
198 "Non-nil means use alternative key bindings for some keys.
199 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
200 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
201 If you want to use Org-mode together with one of these other modes,
202 or more generally if you would like to move some Org-mode commands to
203 other keys, set this variable and configure the keys with the variable
204 `org-disputed-keys'.
206 This option is only relevant at load-time of Org-mode, and must be set
207 *before* org.el is loaded. Changing it requires a restart of Emacs to
208 become effective."
209 :group 'org-startup
210 :type 'boolean)
212 (if (fboundp 'defvaralias)
213 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
215 (defcustom org-disputed-keys
216 '(([(shift up)] . [(meta p)])
217 ([(shift down)] . [(meta n)])
218 ([(shift left)] . [(meta -)])
219 ([(shift right)] . [(meta +)])
220 ([(control shift right)] . [(meta shift +)])
221 ([(control shift left)] . [(meta shift -)]))
222 "Keys for which Org-mode and other modes compete.
223 This is an alist, cars are the default keys, second element specifies
224 the alternative to use when `org-replace-disputed-keys' is t.
226 Keys can be specified in any syntax supported by `define-key'.
227 The value of this option takes effect only at Org-mode's startup,
228 therefore you'll have to restart Emacs to apply it after changing."
229 :group 'org-startup
230 :type 'alist)
232 (defun org-key (key)
233 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
234 Or return the original if not disputed."
235 (if org-replace-disputed-keys
236 (let* ((nkey (key-description key))
237 (x (org-find-if (lambda (x)
238 (equal (key-description (car x)) nkey))
239 org-disputed-keys)))
240 (if x (cdr x) key))
241 key))
243 (defun org-find-if (predicate seq)
244 (catch 'exit
245 (while seq
246 (if (funcall predicate (car seq))
247 (throw 'exit (car seq))
248 (pop seq)))))
250 (defun org-defkey (keymap key def)
251 "Define a key, possibly translated, as returned by `org-key'."
252 (define-key keymap (org-key key) def))
254 (defcustom org-ellipsis 'org-ellipsis
255 "The ellipsis to use in the Org-mode outline.
256 When nil, just use the standard three dots. When a string, use that instead,
257 When a face, use the standart 3 dots, but with the specified face.
258 The change affects only Org-mode (which will then use its own display table).
259 Changing this requires executing `M-x org-mode' in a buffer to become
260 effective."
261 :group 'org-startup
262 :type '(choice (const :tag "Default" nil)
263 (face :tag "Face" :value org-warning)
264 (string :tag "String" :value "...#")))
266 (defvar org-display-table nil
267 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
269 (defgroup org-keywords nil
270 "Keywords in Org-mode."
271 :tag "Org Keywords"
272 :group 'org)
274 (defcustom org-deadline-string "DEADLINE:"
275 "String to mark deadline entries.
276 A deadline is this string, followed by a time stamp. Should be a word,
277 terminated by a colon. You can insert a schedule keyword and
278 a timestamp with \\[org-deadline].
279 Changes become only effective after restarting Emacs."
280 :group 'org-keywords
281 :type 'string)
283 (defcustom org-scheduled-string "SCHEDULED:"
284 "String to mark scheduled TODO entries.
285 A schedule is this string, followed by a time stamp. Should be a word,
286 terminated by a colon. You can insert a schedule keyword and
287 a timestamp with \\[org-schedule].
288 Changes become only effective after restarting Emacs."
289 :group 'org-keywords
290 :type 'string)
292 (defcustom org-closed-string "CLOSED:"
293 "String used as the prefix for timestamps logging closing a TODO entry."
294 :group 'org-keywords
295 :type 'string)
297 (defcustom org-clock-string "CLOCK:"
298 "String used as prefix for timestamps clocking work hours on an item."
299 :group 'org-keywords
300 :type 'string)
302 (defcustom org-comment-string "COMMENT"
303 "Entries starting with this keyword will never be exported.
304 An entry can be toggled between COMMENT and normal with
305 \\[org-toggle-comment].
306 Changes become only effective after restarting Emacs."
307 :group 'org-keywords
308 :type 'string)
310 (defcustom org-quote-string "QUOTE"
311 "Entries starting with this keyword will be exported in fixed-width font.
312 Quoting applies only to the text in the entry following the headline, and does
313 not extend beyond the next headline, even if that is lower level.
314 An entry can be toggled between QUOTE and normal with
315 \\[org-toggle-fixed-width-section]."
316 :group 'org-keywords
317 :type 'string)
319 (defconst org-repeat-re
320 (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
321 " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
322 "Regular expression for specifying repeated events.
323 After a match, group 1 contains the repeat expression.")
325 (defgroup org-structure nil
326 "Options concerning the general structure of Org-mode files."
327 :tag "Org Structure"
328 :group 'org)
330 (defgroup org-reveal-location nil
331 "Options about how to make context of a location visible."
332 :tag "Org Reveal Location"
333 :group 'org-structure)
335 (defcustom org-show-hierarchy-above '((default . t))
336 "Non-nil means, show full hierarchy when revealing a location.
337 Org-mode often shows locations in an org-mode file which might have
338 been invisible before. When this is set, the hierarchy of headings
339 above the exposed location is shown.
340 Turning this off for example for sparse trees makes them very compact.
341 Instead of t, this can also be an alist specifying this option for different
342 contexts. Valid contexts are
343 agenda when exposing an entry from the agenda
344 org-goto when using the command `org-goto' on key C-c C-j
345 occur-tree when using the command `org-occur' on key C-c /
346 tags-tree when constructing a sparse tree based on tags matches
347 link-search when exposing search matches associated with a link
348 mark-goto when exposing the jump goal of a mark
349 bookmark-jump when exposing a bookmark location
350 isearch when exiting from an incremental search
351 default default for all contexts not set explicitly"
352 :group 'org-reveal-location
353 :type '(choice
354 (const :tag "Always" t)
355 (const :tag "Never" nil)
356 (repeat :greedy t :tag "Individual contexts"
357 (cons
358 (choice :tag "Context"
359 (const agenda)
360 (const org-goto)
361 (const occur-tree)
362 (const tags-tree)
363 (const link-search)
364 (const mark-goto)
365 (const bookmark-jump)
366 (const isearch)
367 (const default))
368 (boolean)))))
370 (defcustom org-show-following-heading '((default . nil))
371 "Non-nil means, show following heading when revealing a location.
372 Org-mode often shows locations in an org-mode file which might have
373 been invisible before. When this is set, the heading following the
374 match is shown.
375 Turning this off for example for sparse trees makes them very compact,
376 but makes it harder to edit the location of the match. In such a case,
377 use the command \\[org-reveal] to show more context.
378 Instead of t, this can also be an alist specifying this option for different
379 contexts. See `org-show-hierarchy-above' for valid contexts."
380 :group 'org-reveal-location
381 :type '(choice
382 (const :tag "Always" t)
383 (const :tag "Never" nil)
384 (repeat :greedy t :tag "Individual contexts"
385 (cons
386 (choice :tag "Context"
387 (const agenda)
388 (const org-goto)
389 (const occur-tree)
390 (const tags-tree)
391 (const link-search)
392 (const mark-goto)
393 (const bookmark-jump)
394 (const isearch)
395 (const default))
396 (boolean)))))
398 (defcustom org-show-siblings '((default . nil) (isearch t))
399 "Non-nil means, show all sibling heading when revealing a location.
400 Org-mode often shows locations in an org-mode file which might have
401 been invisible before. When this is set, the sibling of the current entry
402 heading are all made visible. If `org-show-hierarchy-above' is t,
403 the same happens on each level of the hierarchy above the current entry.
405 By default this is on for the isearch context, off for all other contexts.
406 Turning this off for example for sparse trees makes them very compact,
407 but makes it harder to edit the location of the match. In such a case,
408 use the command \\[org-reveal] to show more context.
409 Instead of t, this can also be an alist specifying this option for different
410 contexts. See `org-show-hierarchy-above' for valid contexts."
411 :group 'org-reveal-location
412 :type '(choice
413 (const :tag "Always" t)
414 (const :tag "Never" nil)
415 (repeat :greedy t :tag "Individual contexts"
416 (cons
417 (choice :tag "Context"
418 (const agenda)
419 (const org-goto)
420 (const occur-tree)
421 (const tags-tree)
422 (const link-search)
423 (const mark-goto)
424 (const bookmark-jump)
425 (const isearch)
426 (const default))
427 (boolean)))))
429 (defgroup org-cycle nil
430 "Options concerning visibility cycling in Org-mode."
431 :tag "Org Cycle"
432 :group 'org-structure)
434 (defcustom org-drawers '("PROPERTIES" "CLOCK")
435 "Names of drawers. Drawers are not opened by cycling on the headline above.
436 Drawers only open with a TAB on the drawer line itself. A drawer looks like
437 this:
438 :DRAWERNAME:
439 .....
440 :END:
441 The drawer \"PROPERTIES\" is special for capturing properties through
442 the property API.
444 Drawers can be defined on the per-file basis with a line like:
446 #+DRAWERS: HIDDEN STATE PROPERTIES"
447 :group 'org-structure
448 :type '(repeat (string :tag "Drawer Name")))
450 (defcustom org-cycle-global-at-bob nil
451 "Cycle globally if cursor is at beginning of buffer and not at a headline.
452 This makes it possible to do global cycling without having to use S-TAB or
453 C-u TAB. For this special case to work, the first line of the buffer
454 must not be a headline - it may be empty ot some other text. When used in
455 this way, `org-cycle-hook' is disables temporarily, to make sure the
456 cursor stays at the beginning of the buffer.
457 When this option is nil, don't do anything special at the beginning
458 of the buffer."
459 :group 'org-cycle
460 :type 'boolean)
462 (defcustom org-cycle-emulate-tab t
463 "Where should `org-cycle' emulate TAB.
464 nil Never
465 white Only in completely white lines
466 whitestart Only at the beginning of lines, before the first non-white char.
467 t Everywhere except in headlines
468 exc-hl-bol Everywhere except at the start of a headline
469 If TAB is used in a place where it does not emulate TAB, the current subtree
470 visibility is cycled."
471 :group 'org-cycle
472 :type '(choice (const :tag "Never" nil)
473 (const :tag "Only in completely white lines" white)
474 (const :tag "Before first char in a line" whitestart)
475 (const :tag "Everywhere except in headlines" t)
476 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
479 (defcustom org-cycle-separator-lines 2
480 "Number of empty lines needed to keep an empty line between collapsed trees.
481 If you leave an empty line between the end of a subtree and the following
482 headline, this empty line is hidden when the subtree is folded.
483 Org-mode will leave (exactly) one empty line visible if the number of
484 empty lines is equal or larger to the number given in this variable.
485 So the default 2 means, at least 2 empty lines after the end of a subtree
486 are needed to produce free space between a collapsed subtree and the
487 following headline.
489 Special case: when 0, never leave empty lines in collapsed view."
490 :group 'org-cycle
491 :type 'integer)
493 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
494 org-cycle-hide-drawers
495 org-cycle-show-empty-lines
496 org-optimize-window-after-visibility-change)
497 "Hook that is run after `org-cycle' has changed the buffer visibility.
498 The function(s) in this hook must accept a single argument which indicates
499 the new state that was set by the most recent `org-cycle' command. The
500 argument is a symbol. After a global state change, it can have the values
501 `overview', `content', or `all'. After a local state change, it can have
502 the values `folded', `children', or `subtree'."
503 :group 'org-cycle
504 :type 'hook)
506 (defgroup org-edit-structure nil
507 "Options concerning structure editing in Org-mode."
508 :tag "Org Edit Structure"
509 :group 'org-structure)
511 (defcustom org-special-ctrl-a/e nil
512 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
513 When t, `C-a' will bring back the cursor to the beginning of the
514 headline text, i.e. after the stars and after a possible TODO keyword.
515 In an item, this will be the position after the bullet.
516 When the cursor is already at that position, another `C-a' will bring
517 it to the beginning of the line.
518 `C-e' will jump to the end of the headline, ignoring the presence of tags
519 in the headline. A second `C-e' will then jump to the true end of the
520 line, after any tags.
521 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
522 and only a directly following, identical keypress will bring the cursor
523 to the special positions."
524 :group 'org-edit-structure
525 :type '(choice
526 (const :tag "off" nil)
527 (const :tag "after bullet first" t)
528 (const :tag "border first" reversed)))
530 (if (fboundp 'defvaralias)
531 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
533 (defcustom org-odd-levels-only nil
534 "Non-nil means, skip even levels and only use odd levels for the outline.
535 This has the effect that two stars are being added/taken away in
536 promotion/demotion commands. It also influences how levels are
537 handled by the exporters.
538 Changing it requires restart of `font-lock-mode' to become effective
539 for fontification also in regions already fontified.
540 You may also set this on a per-file basis by adding one of the following
541 lines to the buffer:
543 #+STARTUP: odd
544 #+STARTUP: oddeven"
545 :group 'org-edit-structure
546 :group 'org-font-lock
547 :type 'boolean)
549 (defcustom org-adapt-indentation t
550 "Non-nil means, adapt indentation when promoting and demoting.
551 When this is set and the *entire* text in an entry is indented, the
552 indentation is increased by one space in a demotion command, and
553 decreased by one in a promotion command. If any line in the entry
554 body starts at column 0, indentation is not changed at all."
555 :group 'org-edit-structure
556 :type 'boolean)
558 (defcustom org-blank-before-new-entry '((heading . nil)
559 (plain-list-item . nil))
560 "Should `org-insert-heading' leave a blank line before new heading/item?
561 The value is an alist, with `heading' and `plain-list-item' as car,
562 and a boolean flag as cdr."
563 :group 'org-edit-structure
564 :type '(list
565 (cons (const heading) (boolean))
566 (cons (const plain-list-item) (boolean))))
568 (defcustom org-insert-heading-hook nil
569 "Hook being run after inserting a new heading."
570 :group 'org-edit-structure
571 :type 'boolean)
573 (defcustom org-enable-fixed-width-editor t
574 "Non-nil means, lines starting with \":\" are treated as fixed-width.
575 This currently only means, they are never auto-wrapped.
576 When nil, such lines will be treated like ordinary lines.
577 See also the QUOTE keyword."
578 :group 'org-edit-structure
579 :type 'boolean)
581 (defgroup org-sparse-trees nil
582 "Options concerning sparse trees in Org-mode."
583 :tag "Org Sparse Trees"
584 :group 'org-structure)
586 (defcustom org-highlight-sparse-tree-matches t
587 "Non-nil means, highlight all matches that define a sparse tree.
588 The highlights will automatically disappear the next time the buffer is
589 changed by an edit command."
590 :group 'org-sparse-trees
591 :type 'boolean)
593 (defcustom org-remove-highlights-with-change t
594 "Non-nil means, any change to the buffer will remove temporary highlights.
595 Such highlights are created by `org-occur' and `org-clock-display'.
596 When nil, `C-c C-c needs to be used to get rid of the highlights.
597 The highlights created by `org-preview-latex-fragment' always need
598 `C-c C-c' to be removed."
599 :group 'org-sparse-trees
600 :group 'org-time
601 :type 'boolean)
604 (defcustom org-occur-hook '(org-first-headline-recenter)
605 "Hook that is run after `org-occur' has constructed a sparse tree.
606 This can be used to recenter the window to show as much of the structure
607 as possible."
608 :group 'org-sparse-trees
609 :type 'hook)
611 (defgroup org-plain-lists nil
612 "Options concerning plain lists in Org-mode."
613 :tag "Org Plain lists"
614 :group 'org-structure)
616 (defcustom org-cycle-include-plain-lists nil
617 "Non-nil means, include plain lists into visibility cycling.
618 This means that during cycling, plain list items will *temporarily* be
619 interpreted as outline headlines with a level given by 1000+i where i is the
620 indentation of the bullet. In all other operations, plain list items are
621 not seen as headlines. For example, you cannot assign a TODO keyword to
622 such an item."
623 :group 'org-plain-lists
624 :type 'boolean)
626 (defcustom org-plain-list-ordered-item-terminator t
627 "The character that makes a line with leading number an ordered list item.
628 Valid values are ?. and ?\). To get both terminators, use t. While
629 ?. may look nicer, it creates the danger that a line with leading
630 number may be incorrectly interpreted as an item. ?\) therefore is
631 the safe choice."
632 :group 'org-plain-lists
633 :type '(choice (const :tag "dot like in \"2.\"" ?.)
634 (const :tag "paren like in \"2)\"" ?\))
635 (const :tab "both" t)))
637 (defcustom org-auto-renumber-ordered-lists t
638 "Non-nil means, automatically renumber ordered plain lists.
639 Renumbering happens when the sequence have been changed with
640 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
641 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
642 :group 'org-plain-lists
643 :type 'boolean)
645 (defcustom org-provide-checkbox-statistics t
646 "Non-nil means, update checkbox statistics after insert and toggle.
647 When this is set, checkbox statistics is updated each time you either insert
648 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
649 with \\[org-ctrl-c-ctrl-c\\]."
650 :group 'org-plain-lists
651 :type 'boolean)
653 (defgroup org-archive nil
654 "Options concerning archiving in Org-mode."
655 :tag "Org Archive"
656 :group 'org-structure)
658 (defcustom org-archive-tag "ARCHIVE"
659 "The tag that marks a subtree as archived.
660 An archived subtree does not open during visibility cycling, and does
661 not contribute to the agenda listings."
662 :group 'org-archive
663 :group 'org-keywords
664 :type 'string)
666 (defcustom org-agenda-skip-archived-trees t
667 "Non-nil means, the agenda will skip any items located in archived trees.
668 An archived tree is a tree marked with the tag ARCHIVE."
669 :group 'org-archive
670 :group 'org-agenda-skip
671 :type 'boolean)
673 (defcustom org-cycle-open-archived-trees nil
674 "Non-nil means, `org-cycle' will open archived trees.
675 An archived tree is a tree marked with the tag ARCHIVE.
676 When nil, archived trees will stay folded. You can still open them with
677 normal outline commands like `show-all', but not with the cycling commands."
678 :group 'org-archive
679 :group 'org-cycle
680 :type 'boolean)
682 (defcustom org-sparse-tree-open-archived-trees nil
683 "Non-nil means sparse tree construction shows matches in archived trees.
684 When nil, matches in these trees are highlighted, but the trees are kept in
685 collapsed state."
686 :group 'org-archive
687 :group 'org-sparse-trees
688 :type 'boolean)
690 (defcustom org-archive-location "%s_archive::"
691 "The location where subtrees should be archived.
692 This string consists of two parts, separated by a double-colon.
694 The first part is a file name - when omitted, archiving happens in the same
695 file. %s will be replaced by the current file name (without directory part).
696 Archiving to a different file is useful to keep archived entries from
697 contributing to the Org-mode Agenda.
699 The part after the double colon is a headline. The archived entries will be
700 filed under that headline. When omitted, the subtrees are simply filed away
701 at the end of the file, as top-level entries.
703 Here are a few examples:
704 \"%s_archive::\"
705 If the current file is Projects.org, archive in file
706 Projects.org_archive, as top-level trees. This is the default.
708 \"::* Archived Tasks\"
709 Archive in the current file, under the top-level headline
710 \"* Archived Tasks\".
712 \"~/org/archive.org::\"
713 Archive in file ~/org/archive.org (absolute path), as top-level trees.
715 \"basement::** Finished Tasks\"
716 Archive in file ./basement (relative path), as level 3 trees
717 below the level 2 heading \"** Finished Tasks\".
719 You may set this option on a per-file basis by adding to the buffer a
720 line like
722 #+ARCHIVE: basement::** Finished Tasks"
723 :group 'org-archive
724 :type 'string)
726 (defcustom org-archive-mark-done t
727 "Non-nil means, mark entries as DONE when they are moved to the archive file.
728 This can be a string to set the keyword to use. When t, Org-mode will
729 use the first keyword in its list that means done."
730 :group 'org-archive
731 :type '(choice
732 (const :tag "No" nil)
733 (const :tag "Yes" t)
734 (string :tag "Use this keyword")))
736 (defcustom org-archive-stamp-time t
737 "Non-nil means, add a time stamp to entries moved to an archive file.
738 This variable is obsolete and has no effect anymore, instead add ot remove
739 `time' from the variablle `org-archive-save-context-info'."
740 :group 'org-archive
741 :type 'boolean)
743 (defcustom org-archive-save-context-info '(time file category todo itags)
744 "Parts of context info that should be stored as properties when archiving.
745 When a subtree is moved to an archive file, it looses information given by
746 context, like inherited tags, the category, and possibly also the TODO
747 state (depending on the variable `org-archive-mark-done').
748 This variable can be a list of any of the following symbols:
750 time The time of archiving.
751 file The file where the entry originates.
752 itags The local tags, in the headline of the subtree.
753 ltags The tags the subtree inherits from further up the hierarchy.
754 todo The pre-archive TODO state.
755 category The category, taken from file name or #+CATEGORY lines.
757 For each symbol present in the list, a property will be created in
758 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
759 information."
760 :group 'org-archive
761 :type '(set :greedy t
762 (const :tag "Time" time)
763 (const :tag "File" file)
764 (const :tag "Category" category)
765 (const :tag "TODO state" todo)
766 (const :tag "TODO state" priority)
767 (const :tag "Inherited tags" itags)
768 (const :tag "Local tags" ltags)))
770 (defgroup org-table nil
771 "Options concerning tables in Org-mode."
772 :tag "Org Table"
773 :group 'org)
775 (defcustom org-enable-table-editor 'optimized
776 "Non-nil means, lines starting with \"|\" are handled by the table editor.
777 When nil, such lines will be treated like ordinary lines.
779 When equal to the symbol `optimized', the table editor will be optimized to
780 do the following:
781 - Automatic overwrite mode in front of whitespace in table fields.
782 This makes the structure of the table stay in tact as long as the edited
783 field does not exceed the column width.
784 - Minimize the number of realigns. Normally, the table is aligned each time
785 TAB or RET are pressed to move to another field. With optimization this
786 happens only if changes to a field might have changed the column width.
787 Optimization requires replacing the functions `self-insert-command',
788 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
789 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
790 very good at guessing when a re-align will be necessary, but you can always
791 force one with \\[org-ctrl-c-ctrl-c].
793 If you would like to use the optimized version in Org-mode, but the
794 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
796 This variable can be used to turn on and off the table editor during a session,
797 but in order to toggle optimization, a restart is required.
799 See also the variable `org-table-auto-blank-field'."
800 :group 'org-table
801 :type '(choice
802 (const :tag "off" nil)
803 (const :tag "on" t)
804 (const :tag "on, optimized" optimized)))
806 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
807 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
808 In the optimized version, the table editor takes over all simple keys that
809 normally just insert a character. In tables, the characters are inserted
810 in a way to minimize disturbing the table structure (i.e. in overwrite mode
811 for empty fields). Outside tables, the correct binding of the keys is
812 restored.
814 The default for this option is t if the optimized version is also used in
815 Org-mode. See the variable `org-enable-table-editor' for details. Changing
816 this variable requires a restart of Emacs to become effective."
817 :group 'org-table
818 :type 'boolean)
820 (defcustom orgtbl-radio-table-templates
821 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
822 % END RECEIVE ORGTBL %n
823 \\begin{comment}
824 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
825 | | |
826 \\end{comment}\n")
827 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
828 @c END RECEIVE ORGTBL %n
829 @ignore
830 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
831 | | |
832 @end ignore\n")
833 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
834 <!-- END RECEIVE ORGTBL %n -->
835 <!--
836 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
837 | | |
838 -->\n"))
839 "Templates for radio tables in different major modes.
840 All occurrences of %n in a template will be replaced with the name of the
841 table, obtained by prompting the user."
842 :group 'org-table
843 :type '(repeat
844 (list (symbol :tag "Major mode")
845 (string :tag "Format"))))
847 (defgroup org-table-settings nil
848 "Settings for tables in Org-mode."
849 :tag "Org Table Settings"
850 :group 'org-table)
852 (defcustom org-table-default-size "5x2"
853 "The default size for newly created tables, Columns x Rows."
854 :group 'org-table-settings
855 :type 'string)
857 (defcustom org-table-number-regexp
858 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
859 "Regular expression for recognizing numbers in table columns.
860 If a table column contains mostly numbers, it will be aligned to the
861 right. If not, it will be aligned to the left.
863 The default value of this option is a regular expression which allows
864 anything which looks remotely like a number as used in scientific
865 context. For example, all of the following will be considered a
866 number:
867 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
869 Other options offered by the customize interface are more restrictive."
870 :group 'org-table-settings
871 :type '(choice
872 (const :tag "Positive Integers"
873 "^[0-9]+$")
874 (const :tag "Integers"
875 "^[-+]?[0-9]+$")
876 (const :tag "Floating Point Numbers"
877 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
878 (const :tag "Floating Point Number or Integer"
879 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
880 (const :tag "Exponential, Floating point, Integer"
881 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
882 (const :tag "Very General Number-Like, including hex"
883 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
884 (string :tag "Regexp:")))
886 (defcustom org-table-number-fraction 0.5
887 "Fraction of numbers in a column required to make the column align right.
888 In a column all non-white fields are considered. If at least this
889 fraction of fields is matched by `org-table-number-fraction',
890 alignment to the right border applies."
891 :group 'org-table-settings
892 :type 'number)
894 (defgroup org-table-editing nil
895 "Bahavior of tables during editing in Org-mode."
896 :tag "Org Table Editing"
897 :group 'org-table)
899 (defcustom org-table-automatic-realign t
900 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
901 When nil, aligning is only done with \\[org-table-align], or after column
902 removal/insertion."
903 :group 'org-table-editing
904 :type 'boolean)
906 (defcustom org-table-auto-blank-field t
907 "Non-nil means, automatically blank table field when starting to type into it.
908 This only happens when typing immediately after a field motion
909 command (TAB, S-TAB or RET).
910 Only relevant when `org-enable-table-editor' is equal to `optimized'."
911 :group 'org-table-editing
912 :type 'boolean)
914 (defcustom org-table-tab-jumps-over-hlines t
915 "Non-nil means, tab in the last column of a table with jump over a hline.
916 If a horizontal separator line is following the current line,
917 `org-table-next-field' can either create a new row before that line, or jump
918 over the line. When this option is nil, a new line will be created before
919 this line."
920 :group 'org-table-editing
921 :type 'boolean)
923 (defcustom org-table-tab-recognizes-table.el t
924 "Non-nil means, TAB will automatically notice a table.el table.
925 When it sees such a table, it moves point into it and - if necessary -
926 calls `table-recognize-table'."
927 :group 'org-table-editing
928 :type 'boolean)
930 (defgroup org-table-calculation nil
931 "Options concerning tables in Org-mode."
932 :tag "Org Table Calculation"
933 :group 'org-table)
935 (defcustom org-table-use-standard-references t
936 "Should org-mode work with table refrences like B3 instead of @3$2?
937 Possible values are:
938 nil never use them
939 from accept as input, do not present for editing
940 t: accept as input and present for editing"
941 :group 'org-table-calculation
942 :type '(choice
943 (const :tag "Never, don't even check unser input for them" nil)
944 (const :tag "Always, both as user input, and when editing" t)
945 (const :tag "Convert user input, don't offer during editing" 'from)))
947 (defcustom org-table-copy-increment t
948 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
949 :group 'org-table-calculation
950 :type 'boolean)
952 (defcustom org-calc-default-modes
953 '(calc-internal-prec 12
954 calc-float-format (float 5)
955 calc-angle-mode deg
956 calc-prefer-frac nil
957 calc-symbolic-mode nil
958 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
959 calc-display-working-message t
961 "List with Calc mode settings for use in calc-eval for table formulas.
962 The list must contain alternating symbols (Calc modes variables and values).
963 Don't remove any of the default settings, just change the values. Org-mode
964 relies on the variables to be present in the list."
965 :group 'org-table-calculation
966 :type 'plist)
968 (defcustom org-table-formula-evaluate-inline t
969 "Non-nil means, TAB and RET evaluate a formula in current table field.
970 If the current field starts with an equal sign, it is assumed to be a formula
971 which should be evaluated as described in the manual and in the documentation
972 string of the command `org-table-eval-formula'. This feature requires the
973 Emacs calc package.
974 When this variable is nil, formula calculation is only available through
975 the command \\[org-table-eval-formula]."
976 :group 'org-table-calculation
977 :type 'boolean)
979 (defcustom org-table-formula-use-constants t
980 "Non-nil means, interpret constants in formulas in tables.
981 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
982 by the value given in `org-table-formula-constants', or by a value obtained
983 from the `constants.el' package."
984 :group 'org-table-calculation
985 :type 'boolean)
987 (defcustom org-table-formula-constants nil
988 "Alist with constant names and values, for use in table formulas.
989 The car of each element is a name of a constant, without the `$' before it.
990 The cdr is the value as a string. For example, if you'd like to use the
991 speed of light in a formula, you would configure
993 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
995 and then use it in an equation like `$1*$c'.
997 Constants can also be defined on a per-file basis using a line like
999 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1000 :group 'org-table-calculation
1001 :type '(repeat
1002 (cons (string :tag "name")
1003 (string :tag "value"))))
1005 (defvar org-table-formula-constants-local nil
1006 "Local version of `org-table-formula-constants'.")
1007 (make-variable-buffer-local 'org-table-formula-constants-local)
1009 (defcustom org-table-allow-automatic-line-recalculation t
1010 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1011 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1012 :group 'org-table-calculation
1013 :type 'boolean)
1015 (defgroup org-link nil
1016 "Options concerning links in Org-mode."
1017 :tag "Org Link"
1018 :group 'org)
1020 (defvar org-link-abbrev-alist-local nil
1021 "Buffer-local version of `org-link-abbrev-alist', which see.
1022 The value of this is taken from the #+LINK lines.")
1023 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1025 (defcustom org-link-abbrev-alist nil
1026 "Alist of link abbreviations.
1027 The car of each element is a string, to be replaced at the start of a link.
1028 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1029 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1031 [[linkkey:tag][description]]
1033 If REPLACE is a string, the tag will simply be appended to create the link.
1034 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1035 also be a function that will be called with the tag as the only argument to
1036 create the link. See the manual for examples."
1037 :group 'org-link
1038 :type 'alist)
1040 (defcustom org-descriptive-links t
1041 "Non-nil means, hide link part and only show description of bracket links.
1042 Bracket links are like [[link][descritpion]]. This variable sets the initial
1043 state in new org-mode buffers. The setting can then be toggled on a
1044 per-buffer basis from the Org->Hyperlinks menu."
1045 :group 'org-link
1046 :type 'boolean)
1048 (defcustom org-link-file-path-type 'adaptive
1049 "How the path name in file links should be stored.
1050 Valid values are:
1052 relative relative to the current directory, i.e. the directory of the file
1053 into which the link is being inserted.
1054 absolute absolute path, if possible with ~ for home directory.
1055 noabbrev absolute path, no abbreviation of home directory.
1056 adaptive Use relative path for files in the current directory and sub-
1057 directories of it. For other files, use an absolute path."
1058 :group 'org-link
1059 :type '(choice
1060 (const relative)
1061 (const absolute)
1062 (const noabbrev)
1063 (const adaptive)))
1065 (defcustom org-activate-links '(bracket angle plain radio tag date)
1066 "Types of links that should be activated in Org-mode files.
1067 This is a list of symbols, each leading to the activation of a certain link
1068 type. In principle, it does not hurt to turn on most link types - there may
1069 be a small gain when turning off unused link types. The types are:
1071 bracket The recommended [[link][description]] or [[link]] links with hiding.
1072 angular Links in angular brackes that may contain whitespace like
1073 <bbdb:Carsten Dominik>.
1074 plain Plain links in normal text, no whitespace, like http://google.com.
1075 radio Text that is matched by a radio target, see manual for details.
1076 tag Tag settings in a headline (link to tag search).
1077 date Time stamps (link to calendar).
1079 Changing this variable requires a restart of Emacs to become effective."
1080 :group 'org-link
1081 :type '(set (const :tag "Double bracket links (new style)" bracket)
1082 (const :tag "Angular bracket links (old style)" angular)
1083 (const :tag "plain text links" plain)
1084 (const :tag "Radio target matches" radio)
1085 (const :tag "Tags" tag)
1086 (const :tag "Tags" target)
1087 (const :tag "Timestamps" date)))
1089 (defgroup org-link-store nil
1090 "Options concerning storing links in Org-mode"
1091 :tag "Org Store Link"
1092 :group 'org-link)
1094 (defcustom org-email-link-description-format "Email %c: %.30s"
1095 "Format of the description part of a link to an email or usenet message.
1096 The following %-excapes will be replaced by corresponding information:
1098 %F full \"From\" field
1099 %f name, taken from \"From\" field, address if no name
1100 %T full \"To\" field
1101 %t first name in \"To\" field, address if no name
1102 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1103 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1104 %s subject
1105 %m message-id.
1107 You may use normal field width specification between the % and the letter.
1108 This is for example useful to limit the length of the subject.
1110 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1111 :group 'org-link-store
1112 :type 'string)
1114 (defcustom org-from-is-user-regexp
1115 (let (r1 r2)
1116 (when (and user-mail-address (not (string= user-mail-address "")))
1117 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1118 (when (and user-full-name (not (string= user-full-name "")))
1119 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1120 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1121 "Regexp mached against the \"From:\" header of an email or usenet message.
1122 It should match if the message is from the user him/herself."
1123 :group 'org-link-store
1124 :type 'regexp)
1126 (defcustom org-context-in-file-links t
1127 "Non-nil means, file links from `org-store-link' contain context.
1128 A search string will be added to the file name with :: as separator and
1129 used to find the context when the link is activated by the command
1130 `org-open-at-point'.
1131 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1132 negates this setting for the duration of the command."
1133 :group 'org-link-store
1134 :type 'boolean)
1136 (defcustom org-keep-stored-link-after-insertion nil
1137 "Non-nil means, keep link in list for entire session.
1139 The command `org-store-link' adds a link pointing to the current
1140 location to an internal list. These links accumulate during a session.
1141 The command `org-insert-link' can be used to insert links into any
1142 Org-mode file (offering completion for all stored links). When this
1143 option is nil, every link which has been inserted once using \\[org-insert-link]
1144 will be removed from the list, to make completing the unused links
1145 more efficient."
1146 :group 'org-link-store
1147 :type 'boolean)
1149 (defcustom org-usenet-links-prefer-google nil
1150 "Non-nil means, `org-store-link' will create web links to Google groups.
1151 When nil, Gnus will be used for such links.
1152 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1153 negates this setting for the duration of the command."
1154 :group 'org-link-store
1155 :type 'boolean)
1157 (defgroup org-link-follow nil
1158 "Options concerning following links in Org-mode"
1159 :tag "Org Follow Link"
1160 :group 'org-link)
1162 (defcustom org-tab-follows-link nil
1163 "Non-nil means, on links TAB will follow the link.
1164 Needs to be set before org.el is loaded."
1165 :group 'org-link-follow
1166 :type 'boolean)
1168 (defcustom org-return-follows-link nil
1169 "Non-nil means, on links RET will follow the link.
1170 Needs to be set before org.el is loaded."
1171 :group 'org-link-follow
1172 :type 'boolean)
1174 (defcustom org-mouse-1-follows-link t
1175 "Non-nil means, mouse-1 on a link will follow the link.
1176 A longer mouse click will still set point. Does not wortk on XEmacs.
1177 Needs to be set before org.el is loaded."
1178 :group 'org-link-follow
1179 :type 'boolean)
1181 (defcustom org-mark-ring-length 4
1182 "Number of different positions to be recorded in the ring
1183 Changing this requires a restart of Emacs to work correctly."
1184 :group 'org-link-follow
1185 :type 'interger)
1187 (defcustom org-link-frame-setup
1188 '((vm . vm-visit-folder-other-frame)
1189 (gnus . gnus-other-frame)
1190 (file . find-file-other-window))
1191 "Setup the frame configuration for following links.
1192 When following a link with Emacs, it may often be useful to display
1193 this link in another window or frame. This variable can be used to
1194 set this up for the different types of links.
1195 For VM, use any of
1196 `vm-visit-folder'
1197 `vm-visit-folder-other-frame'
1198 For Gnus, use any of
1199 `gnus'
1200 `gnus-other-frame'
1201 For FILE, use any of
1202 `find-file'
1203 `find-file-other-window'
1204 `find-file-other-frame'
1205 For the calendar, use the variable `calendar-setup'.
1206 For BBDB, it is currently only possible to display the matches in
1207 another window."
1208 :group 'org-link-follow
1209 :type '(list
1210 (cons (const vm)
1211 (choice
1212 (const vm-visit-folder)
1213 (const vm-visit-folder-other-window)
1214 (const vm-visit-folder-other-frame)))
1215 (cons (const gnus)
1216 (choice
1217 (const gnus)
1218 (const gnus-other-frame)))
1219 (cons (const file)
1220 (choice
1221 (const find-file)
1222 (const find-file-other-window)
1223 (const find-file-other-frame)))))
1225 (defcustom org-display-internal-link-with-indirect-buffer nil
1226 "Non-nil means, use indirect buffer to display infile links.
1227 Activating internal links (from one location in a file to another location
1228 in the same file) normally just jumps to the location. When the link is
1229 activated with a C-u prefix (or with mouse-3), the link is displayed in
1230 another window. When this option is set, the other window actually displays
1231 an indirect buffer clone of the current buffer, to avoid any visibility
1232 changes to the current buffer."
1233 :group 'org-link-follow
1234 :type 'boolean)
1236 (defcustom org-open-non-existing-files nil
1237 "Non-nil means, `org-open-file' will open non-existing files.
1238 When nil, an error will be generated."
1239 :group 'org-link-follow
1240 :type 'boolean)
1242 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1243 "Function and arguments to call for following mailto links.
1244 This is a list with the first element being a lisp function, and the
1245 remaining elements being arguments to the function. In string arguments,
1246 %a will be replaced by the address, and %s will be replaced by the subject
1247 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1248 :group 'org-link-follow
1249 :type '(choice
1250 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1251 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1252 (const :tag "message-mail" (message-mail "%a" "%s"))
1253 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1255 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1256 "Non-nil means, ask for confirmation before executing shell links.
1257 Shell links can be dangerous: just think about a link
1259 [[shell:rm -rf ~/*][Google Search]]
1261 This link would show up in your Org-mode document as \"Google Search\",
1262 but really it would remove your entire home directory.
1263 Therefore we advise against setting this variable to nil.
1264 Just change it to `y-or-n-p' of you want to confirm with a
1265 single keystroke rather than having to type \"yes\"."
1266 :group 'org-link-follow
1267 :type '(choice
1268 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1269 (const :tag "with y-or-n (faster)" y-or-n-p)
1270 (const :tag "no confirmation (dangerous)" nil)))
1272 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1273 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1274 Elisp links can be dangerous: just think about a link
1276 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1278 This link would show up in your Org-mode document as \"Google Search\",
1279 but really it would remove your entire home directory.
1280 Therefore we advise against setting this variable to nil.
1281 Just change it to `y-or-n-p' of you want to confirm with a
1282 single keystroke rather than having to type \"yes\"."
1283 :group 'org-link-follow
1284 :type '(choice
1285 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1286 (const :tag "with y-or-n (faster)" y-or-n-p)
1287 (const :tag "no confirmation (dangerous)" nil)))
1289 (defconst org-file-apps-defaults-gnu
1290 '((remote . emacs)
1291 (t . mailcap))
1292 "Default file applications on a UNIX or GNU/Linux system.
1293 See `org-file-apps'.")
1295 (defconst org-file-apps-defaults-macosx
1296 '((remote . emacs)
1297 (t . "open %s")
1298 ("ps" . "gv %s")
1299 ("ps.gz" . "gv %s")
1300 ("eps" . "gv %s")
1301 ("eps.gz" . "gv %s")
1302 ("dvi" . "xdvi %s")
1303 ("fig" . "xfig %s"))
1304 "Default file applications on a MacOS X system.
1305 The system \"open\" is known as a default, but we use X11 applications
1306 for some files for which the OS does not have a good default.
1307 See `org-file-apps'.")
1309 (defconst org-file-apps-defaults-windowsnt
1310 (list
1311 '(remote . emacs)
1312 (cons t
1313 (list (if (featurep 'xemacs)
1314 'mswindows-shell-execute
1315 'w32-shell-execute)
1316 "open" 'file)))
1317 "Default file applications on a Windows NT system.
1318 The system \"open\" is used for most files.
1319 See `org-file-apps'.")
1321 (defcustom org-file-apps
1323 ("txt" . emacs)
1324 ("tex" . emacs)
1325 ("ltx" . emacs)
1326 ("org" . emacs)
1327 ("el" . emacs)
1328 ("bib" . emacs)
1330 "External applications for opening `file:path' items in a document.
1331 Org-mode uses system defaults for different file types, but
1332 you can use this variable to set the application for a given file
1333 extension. The entries in this list are cons cells where the car identifies
1334 files and the cdr the corresponding command. Possible values for the
1335 file identifier are
1336 \"ext\" A string identifying an extension
1337 `directory' Matches a directory
1338 `remote' Matches a remote file, accessible through tramp or efs.
1339 Remote files most likely should be visited through Emacs
1340 because external applications cannot handle such paths.
1341 t Default for all remaining files
1343 Possible values for the command are:
1344 `emacs' The file will be visited by the current Emacs process.
1345 `default' Use the default application for this file type.
1346 string A command to be executed by a shell; %s will be replaced
1347 by the path to the file.
1348 sexp A Lisp form which will be evaluated. The file path will
1349 be available in the Lisp variable `file'.
1350 For more examples, see the system specific constants
1351 `org-file-apps-defaults-macosx'
1352 `org-file-apps-defaults-windowsnt'
1353 `org-file-apps-defaults-gnu'."
1354 :group 'org-link-follow
1355 :type '(repeat
1356 (cons (choice :value ""
1357 (string :tag "Extension")
1358 (const :tag "Default for unrecognized files" t)
1359 (const :tag "Remote file" remote)
1360 (const :tag "Links to a directory" directory))
1361 (choice :value ""
1362 (const :tag "Visit with Emacs" emacs)
1363 (const :tag "Use system default" default)
1364 (string :tag "Command")
1365 (sexp :tag "Lisp form")))))
1367 (defcustom org-mhe-search-all-folders nil
1368 "Non-nil means, that the search for the mh-message will be extended to
1369 all folders if the message cannot be found in the folder given in the link.
1370 Searching all folders is very efficient with one of the search engines
1371 supported by MH-E, but will be slow with pick."
1372 :group 'org-link-follow
1373 :type 'boolean)
1375 (defgroup org-remember nil
1376 "Options concerning interaction with remember.el."
1377 :tag "Org Remember"
1378 :group 'org)
1380 (defcustom org-directory "~/org"
1381 "Directory with org files.
1382 This directory will be used as default to prompt for org files.
1383 Used by the hooks for remember.el."
1384 :group 'org-remember
1385 :type 'directory)
1387 (defcustom org-default-notes-file "~/.notes"
1388 "Default target for storing notes.
1389 Used by the hooks for remember.el. This can be a string, or nil to mean
1390 the value of `remember-data-file'.
1391 You can set this on a per-template basis with the variable
1392 `org-remember-templates'."
1393 :group 'org-remember
1394 :type '(choice
1395 (const :tag "Default from remember-data-file" nil)
1396 file))
1398 (defcustom org-remember-store-without-prompt t
1399 "Non-nil means, `C-c C-c' stores remember note without further promts.
1400 In this case, you need `C-u C-c C-c' to get the prompts for
1401 note file and headline.
1402 When this variable is nil, `C-c C-c' give you the prompts, and
1403 `C-u C-c C-c' trigger the fasttrack."
1404 :group 'org-remember
1405 :type 'boolean)
1407 (defcustom org-remember-default-headline ""
1408 "The headline that should be the default location in the notes file.
1409 When filing remember notes, the cursor will start at that position.
1410 You can set this on a per-template basis with the variable
1411 `org-remember-templates'."
1412 :group 'org-remember
1413 :type 'string)
1415 (defcustom org-remember-templates nil
1416 "Templates for the creation of remember buffers.
1417 When nil, just let remember make the buffer.
1418 When not nil, this is a list of 5-element lists. In each entry, the first
1419 element is a the name of the template, It should be a single short word.
1420 The second element is a character, a unique key to select this template.
1421 The third element is the template. The forth element is optional and can
1422 specify a destination file for remember items created with this template.
1423 The default file is given by `org-default-notes-file'. An optional fifth
1424 element can specify the headline in that file that should be offered
1425 first when the user is asked to file the entry. The default headline is
1426 given in the variable `org-remember-default-headline'.
1428 The template specifies the structure of the remember buffer. It should have
1429 a first line starting with a star, to act as the org-mode headline.
1430 Furthermore, the following %-escapes will be replaced with content:
1432 %^{prompt} prompt the user for a string and replace this sequence with it.
1433 %t time stamp, date only
1434 %T time stamp with date and time
1435 %u, %U like the above, but inactive time stamps
1436 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1437 You may define a prompt like %^{Please specify birthday}t
1438 %n user name (taken from `user-full-name')
1439 %a annotation, normally the link created with org-store-link
1440 %i initial content, the region when remember is called with C-u.
1441 If %i is indented, the entire inserted text will be indented
1442 as well.
1444 %? After completing the template, position cursor here.
1446 Apart from these general escapes, you can access information specific to the
1447 link type that is created. For example, calling `remember' in emails or gnus
1448 will record the author and the subject of the message, which you can access
1449 with %:author and %:subject, respectively. Here is a complete list of what
1450 is recorded for each link type.
1452 Link type | Available information
1453 -------------------+------------------------------------------------------
1454 bbdb | %:type %:name %:company
1455 vm, wl, mh, rmail | %:type %:subject %:message-id
1456 | %:from %:fromname %:fromaddress
1457 | %:to %:toname %:toaddress
1458 | %:fromto (either \"to NAME\" or \"from NAME\")
1459 gnus | %:group, for messages also all email fields
1460 w3, w3m | %:type %:url
1461 info | %:type %:file %:node
1462 calendar | %:type %:date"
1463 :group 'org-remember
1464 :get (lambda (var) ; Make sure all entries have 5 elements
1465 (mapcar (lambda (x)
1466 (if (not (stringp (car x))) (setq x (cons "" x)))
1467 (cond ((= (length x) 4) (append x '("")))
1468 ((= (length x) 3) (append x '("" "")))
1469 (t x)))
1470 (default-value var)))
1471 :type '(repeat
1472 :tag "enabled"
1473 (list :value ("" ?a "\n" nil nil)
1474 (string :tag "Name")
1475 (character :tag "Selection Key")
1476 (string :tag "Template")
1477 (choice
1478 (file :tag "Destination file")
1479 (const :tag "Prompt for file" nil))
1480 (choice
1481 (string :tag "Destination headline")
1482 (const :tag "Selection interface for heading")))))
1484 (defcustom org-reverse-note-order nil
1485 "Non-nil means, store new notes at the beginning of a file or entry.
1486 When nil, new notes will be filed to the end of a file or entry."
1487 :group 'org-remember
1488 :type '(choice
1489 (const :tag "Reverse always" t)
1490 (const :tag "Reverse never" nil)
1491 (repeat :tag "By file name regexp"
1492 (cons regexp boolean))))
1494 (defgroup org-todo nil
1495 "Options concerning TODO items in Org-mode."
1496 :tag "Org TODO"
1497 :group 'org)
1499 (defgroup org-progress nil
1500 "Options concerning Progress logging in Org-mode."
1501 :tag "Org Progress"
1502 :group 'org-time)
1504 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1505 "List of TODO entry keyword sequences and their interpretation.
1506 \\<org-mode-map>This is a list of sequences.
1508 Each sequence starts with a symbol, either `sequence' or `type',
1509 indicating if the keywords should be interpreted as a sequence of
1510 action steps, or as different types of TODO items. The first
1511 keywords are states requiring action - these states will select a headline
1512 for inclusion into the global TODO list Org-mode produces. If one of
1513 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1514 signify that no further action is necessary. If \"|\" is not found,
1515 the last keyword is treated as the only DONE state of the sequence.
1517 The command \\[org-todo] cycles an entry through these states, and one
1518 additional state where no keyword is present. For details about this
1519 cycling, see the manual.
1521 TODO keywords and interpretation can also be set on a per-file basis with
1522 the special #+SEQ_TODO and #+TYP_TODO lines.
1524 For backward compatibility, this variable may also be just a list
1525 of keywords - in this case the interptetation (sequence or type) will be
1526 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1527 :group 'org-todo
1528 :group 'org-keywords
1529 :type '(choice
1530 (repeat :tag "Old syntax, just keywords"
1531 (string :tag "Keyword"))
1532 (repeat :tag "New syntax"
1533 (cons
1534 (choice
1535 :tag "Interpretation"
1536 (const :tag "Sequence (cycling hits every state)" sequence)
1537 (const :tag "Type (cycling directly to DONE)" type))
1538 (repeat
1539 (string :tag "Keyword"))))))
1541 (defvar org-todo-keywords-1 nil)
1542 (make-variable-buffer-local 'org-todo-keywords-1)
1543 (defvar org-todo-keywords-for-agenda nil)
1544 (defvar org-done-keywords-for-agenda nil)
1545 (defvar org-not-done-keywords nil)
1546 (make-variable-buffer-local 'org-not-done-keywords)
1547 (defvar org-done-keywords nil)
1548 (make-variable-buffer-local 'org-done-keywords)
1549 (defvar org-todo-heads nil)
1550 (make-variable-buffer-local 'org-todo-heads)
1551 (defvar org-todo-sets nil)
1552 (make-variable-buffer-local 'org-todo-sets)
1553 (defvar org-todo-log-states nil)
1554 (make-variable-buffer-local 'org-todo-log-states)
1555 (defvar org-todo-kwd-alist nil)
1556 (make-variable-buffer-local 'org-todo-kwd-alist)
1557 (defvar org-todo-key-alist nil)
1558 (make-variable-buffer-local 'org-todo-key-alist)
1559 (defvar org-todo-key-trigger nil)
1560 (make-variable-buffer-local 'org-todo-key-trigger)
1562 (defcustom org-todo-interpretation 'sequence
1563 "Controls how TODO keywords are interpreted.
1564 This variable is in principle obsolete and is only used for
1565 backward compatibility, if the interpretation of todo keywords is
1566 not given already in `org-todo-keywords'. See that variable for
1567 more information."
1568 :group 'org-todo
1569 :group 'org-keywords
1570 :type '(choice (const sequence)
1571 (const type)))
1573 (defcustom org-use-fast-todo-selection 'prefix
1574 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1575 This variable describes if and under what circumstances the cycling
1576 mechanism for TODO keywords will be replaced by a single-key, direct
1577 selection scheme.
1579 When nil, fast selection is never used.
1581 When the symbol `prefix', it will be used when `org-todo' is called with
1582 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1583 in an agenda buffer.
1585 When t, fast selection is used by default. In this case, the prefix
1586 argument forces cycling instead.
1588 In all cases, the special interface is only used if access keys have actually
1589 been assigned by the user, i.e. if keywords in the configuration are followed
1590 by a letter in parenthesis, like TODO(t)."
1591 :group 'org-todo
1592 :type '(choice
1593 (const :tag "Never" nil)
1594 (const :tag "By default" t)
1595 (const :tag "Only with C-u C-c C-t" prefix)))
1597 (defcustom org-after-todo-state-change-hook nil
1598 "Hook which is run after the state of a TODO item was changed.
1599 The new state (a string with a TODO keyword, or nil) is available in the
1600 Lisp variable `state'."
1601 :group 'org-todo
1602 :type 'hook)
1604 (defcustom org-log-done nil
1605 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1606 When the state of an entry is changed from nothing or a DONE state to
1607 a not-done TODO state, remove a previous closing date.
1609 This can also be a list of symbols indicating under which conditions
1610 the time stamp recording the action should be annotated with a short note.
1611 Valid members of this list are
1613 done Offer to record a note when marking entries done
1614 state Offer to record a note whenever changing the TODO state
1615 of an item. This is only relevant if TODO keywords are
1616 interpreted as sequence, see variable `org-todo-interpretation'.
1617 When `state' is set, this includes tracking `done'.
1618 clock-out Offer to record a note when clocking out of an item.
1620 A separate window will then pop up and allow you to type a note.
1621 After finishing with C-c C-c, the note will be added directly after the
1622 timestamp, as a plain list item. See also the variable
1623 `org-log-note-headings'.
1625 Logging can also be configured on a per-file basis by adding one of
1626 the following lines anywhere in the buffer:
1628 #+STARTUP: logdone
1629 #+STARTUP: nologging
1630 #+STARTUP: lognotedone
1631 #+STARTUP: lognotestate
1632 #+STARTUP: lognoteclock-out
1634 You can have local logging settings for a subtree by setting the LOGGING
1635 property to one or more of these keywords."
1636 :group 'org-todo
1637 :group 'org-progress
1638 :type '(choice
1639 (const :tag "off" nil)
1640 (const :tag "on" t)
1641 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1642 (const :tag "when item is marked DONE" done)
1643 (const :tag "when TODO state changes" state)
1644 (const :tag "when clocking out" clock-out))))
1646 (defcustom org-log-done-with-time t
1647 "Non-nil means, the CLOSED time stamp will contain date and time.
1648 When nil, only the date will be recorded."
1649 :group 'org-progress
1650 :type 'boolean)
1652 (defcustom org-log-note-headings
1653 '((done . "CLOSING NOTE %t")
1654 (state . "State %-12s %t")
1655 (clock-out . ""))
1656 "Headings for notes added when clocking out or closing TODO items.
1657 The value is an alist, with the car being a symbol indicating the note
1658 context, and the cdr is the heading to be used. The heading may also be the
1659 empty string.
1660 %t in the heading will be replaced by a time stamp.
1661 %s will be replaced by the new TODO state, in double quotes.
1662 %u will be replaced by the user name.
1663 %U will be replaced by the full user name."
1664 :group 'org-todo
1665 :group 'org-progress
1666 :type '(list :greedy t
1667 (cons (const :tag "Heading when closing an item" done) string)
1668 (cons (const :tag
1669 "Heading when changing todo state (todo sequence only)"
1670 state) string)
1671 (cons (const :tag "Heading when clocking out" clock-out) string)))
1673 (defcustom org-log-states-order-reversed t
1674 "Non-nil means, the latest state change note will be directly after heading.
1675 When nil, the notes will be orderer according to time."
1676 :group 'org-todo
1677 :group 'org-progress
1678 :type 'boolean)
1680 (defcustom org-log-repeat t
1681 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1682 When nil, no note will be taken.
1683 This option can also be set with on a per-file-basis with
1685 #+STARTUP: logrepeat
1686 #+STARTUP: nologrepeat
1688 You can have local logging settings for a subtree by setting the LOGGING
1689 property to one or more of these keywords."
1690 :group 'org-todo
1691 :group 'org-progress
1692 :type 'boolean)
1694 (defcustom org-clock-into-drawer 2
1695 "Should clocking info be wrapped into a drawer?
1696 When t, clocking info will always be inserted into a :CLOCK: drawer.
1697 If necessary, the drawer will be created.
1698 When nil, the drawer will not be created, but used when present.
1699 When an integer and the number of clocking entries in an item
1700 reaches or exceeds this number, a drawer will be created."
1701 :group 'org-todo
1702 :group 'org-progress
1703 :type '(choice
1704 (const :tag "Always" t)
1705 (const :tag "Only when drawer exists" nil)
1706 (integer :tag "When at least N clock entries")))
1708 (defcustom org-clock-out-when-done t
1709 "When t, the clock will be stopped when the relevant entry is marked DONE.
1710 Nil means, clock will keep running until stopped explicitly with
1711 `C-c C-x C-o', or until the clock is started in a different item."
1712 :group 'org-progress
1713 :type 'boolean)
1715 (defgroup org-priorities nil
1716 "Priorities in Org-mode."
1717 :tag "Org Priorities"
1718 :group 'org-todo)
1720 (defcustom org-highest-priority ?A
1721 "The highest priority of TODO items. A character like ?A, ?B etc.
1722 Must have a smaller ASCII number than `org-lowest-priority'."
1723 :group 'org-priorities
1724 :type 'character)
1726 (defcustom org-lowest-priority ?C
1727 "The lowest priority of TODO items. A character like ?A, ?B etc.
1728 Must have a larger ASCII number than `org-highest-priority'."
1729 :group 'org-priorities
1730 :type 'character)
1732 (defcustom org-default-priority ?B
1733 "The default priority of TODO items.
1734 This is the priority an item get if no explicit priority is given."
1735 :group 'org-priorities
1736 :type 'character)
1738 (defcustom org-priority-start-cycle-with-default t
1739 "Non-nil means, start with default priority when starting to cycle.
1740 When this is nil, the first step in the cycle will be (depending on the
1741 command used) one higher or lower that the default priority."
1742 :group 'org-priorities
1743 :type 'boolean)
1745 (defgroup org-time nil
1746 "Options concerning time stamps and deadlines in Org-mode."
1747 :tag "Org Time"
1748 :group 'org)
1750 (defcustom org-insert-labeled-timestamps-at-point nil
1751 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1752 When nil, these labeled time stamps are forces into the second line of an
1753 entry, just after the headline. When scheduling from the global TODO list,
1754 the time stamp will always be forced into the second line."
1755 :group 'org-time
1756 :type 'boolean)
1758 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1759 "Formats for `format-time-string' which are used for time stamps.
1760 It is not recommended to change this constant.")
1762 (defcustom org-time-stamp-rounding-minutes 0
1763 "Number of minutes to round time stamps to upon insertion.
1764 When zero, insert the time unmodified. Useful rounding numbers
1765 should be factors of 60, so for example 5, 10, 15.
1766 When this is not zero, you can still force an exact time-stamp by using
1767 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1768 :group 'org-time
1769 :type 'integer)
1771 (defcustom org-display-custom-times nil
1772 "Non-nil means, overlay custom formats over all time stamps.
1773 The formats are defined through the variable `org-time-stamp-custom-formats'.
1774 To turn this on on a per-file basis, insert anywhere in the file:
1775 #+STARTUP: customtime"
1776 :group 'org-time
1777 :set 'set-default
1778 :type 'sexp)
1779 (make-variable-buffer-local 'org-display-custom-times)
1781 (defcustom org-time-stamp-custom-formats
1782 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1783 "Custom formats for time stamps. See `format-time-string' for the syntax.
1784 These are overlayed over the default ISO format if the variable
1785 `org-display-custom-times' is set. Time like %H:%M should be at the
1786 end of the second format."
1787 :group 'org-time
1788 :type 'sexp)
1790 (defun org-time-stamp-format (&optional long inactive)
1791 "Get the right format for a time string."
1792 (let ((f (if long (cdr org-time-stamp-formats)
1793 (car org-time-stamp-formats))))
1794 (if inactive
1795 (concat "[" (substring f 1 -1) "]")
1796 f)))
1798 (defcustom org-popup-calendar-for-date-prompt t
1799 "Non-nil means, pop up a calendar when prompting for a date.
1800 In the calendar, the date can be selected with mouse-1. However, the
1801 minibuffer will also be active, and you can simply enter the date as well.
1802 When nil, only the minibuffer will be available."
1803 :group 'org-time
1804 :type 'boolean)
1806 (defcustom org-edit-timestamp-down-means-later nil
1807 "Non-nil means, S-down will increase the time in a time stamp.
1808 When nil, S-up will increase."
1809 :group 'org-time
1810 :type 'boolean)
1812 (defcustom org-calendar-follow-timestamp-change t
1813 "Non-nil means, make the calendar window follow timestamp changes.
1814 When a timestamp is modified and the calendar window is visible, it will be
1815 moved to the new date."
1816 :group 'org-time
1817 :type 'boolean)
1819 (defgroup org-tags nil
1820 "Options concerning tags in Org-mode."
1821 :tag "Org Tags"
1822 :group 'org)
1824 (defcustom org-tag-alist nil
1825 "List of tags allowed in Org-mode files.
1826 When this list is nil, Org-mode will base TAG input on what is already in the
1827 buffer.
1828 The value of this variable is an alist, the car of each entry must be a
1829 keyword as a string, the cdr may be a character that is used to select
1830 that tag through the fast-tag-selection interface.
1831 See the manual for details."
1832 :group 'org-tags
1833 :type '(repeat
1834 (choice
1835 (cons (string :tag "Tag name")
1836 (character :tag "Access char"))
1837 (const :tag "Start radio group" (:startgroup))
1838 (const :tag "End radio group" (:endgroup)))))
1840 (defcustom org-use-fast-tag-selection 'auto
1841 "Non-nil means, use fast tag selection scheme.
1842 This is a special interface to select and deselect tags with single keys.
1843 When nil, fast selection is never used.
1844 When the symbol `auto', fast selection is used if and only if selection
1845 characters for tags have been configured, either through the variable
1846 `org-tag-alist' or through a #+TAGS line in the buffer.
1847 When t, fast selection is always used and selection keys are assigned
1848 automatically if necessary."
1849 :group 'org-tags
1850 :type '(choice
1851 (const :tag "Always" t)
1852 (const :tag "Never" nil)
1853 (const :tag "When selection characters are configured" 'auto)))
1855 (defcustom org-fast-tag-selection-single-key nil
1856 "Non-nil means, fast tag selection exits after first change.
1857 When nil, you have to press RET to exit it.
1858 During fast tag selection, you can toggle this flag with `C-c'.
1859 This variable can also have the value `expert'. In this case, the window
1860 displaying the tags menu is not even shown, until you press C-c again."
1861 :group 'org-tags
1862 :type '(choice
1863 (const :tag "No" nil)
1864 (const :tag "Yes" t)
1865 (const :tag "Expert" expert)))
1867 (defvar org-fast-tag-selection-include-todo nil
1868 "Non-nil means, fast tags selection interface will also offer TODO states.
1869 This is an undocumented feature, you should not rely on it.")
1871 (defcustom org-tags-column -80
1872 "The column to which tags should be indented in a headline.
1873 If this number is positive, it specifies the column. If it is negative,
1874 it means that the tags should be flushright to that column. For example,
1875 -80 works well for a normal 80 character screen."
1876 :group 'org-tags
1877 :type 'integer)
1879 (defcustom org-auto-align-tags t
1880 "Non-nil means, realign tags after pro/demotion of TODO state change.
1881 These operations change the length of a headline and therefore shift
1882 the tags around. With this options turned on, after each such operation
1883 the tags are again aligned to `org-tags-column'."
1884 :group 'org-tags
1885 :type 'boolean)
1887 (defcustom org-use-tag-inheritance t
1888 "Non-nil means, tags in levels apply also for sublevels.
1889 When nil, only the tags directly given in a specific line apply there.
1890 If you turn off this option, you very likely want to turn on the
1891 companion option `org-tags-match-list-sublevels'."
1892 :group 'org-tags
1893 :type 'boolean)
1895 (defcustom org-tags-match-list-sublevels nil
1896 "Non-nil means list also sublevels of headlines matching tag search.
1897 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1898 the sublevels of a headline matching a tag search often also match
1899 the same search. Listing all of them can create very long lists.
1900 Setting this variable to nil causes subtrees of a match to be skipped.
1901 This option is off by default, because inheritance in on. If you turn
1902 inheritance off, you very likely want to turn this option on.
1904 As a special case, if the tag search is restricted to TODO items, the
1905 value of this variable is ignored and sublevels are always checked, to
1906 make sure all corresponding TODO items find their way into the list."
1907 :group 'org-tags
1908 :type 'boolean)
1910 (defvar org-tags-history nil
1911 "History of minibuffer reads for tags.")
1912 (defvar org-last-tags-completion-table nil
1913 "The last used completion table for tags.")
1914 (defvar org-after-tags-change-hook nil
1915 "Hook that is run after the tags in a line have changed.")
1917 (defgroup org-properties nil
1918 "Options concerning properties in Org-mode."
1919 :tag "Org Properties"
1920 :group 'org)
1922 (defcustom org-property-format "%-10s %s"
1923 "How property key/value pairs should be formatted by `indent-line'.
1924 When `indent-line' hits a property definition, it will format the line
1925 according to this format, mainly to make sure that the values are
1926 lined-up with respect to each other."
1927 :group 'org-properties
1928 :type 'string)
1930 (defcustom org-use-property-inheritance nil
1931 "Non-nil means, properties apply also for sublevels.
1932 This can cause significant overhead when doing a search, so this is turned
1933 off by default.
1934 When nil, only the properties directly given in the current entry count.
1936 However, note that some special properties use inheritance under special
1937 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1938 and the properties ending in \"_ALL\" when they are used as descriptor
1939 for valid values of a property."
1940 :group 'org-properties
1941 :type 'boolean)
1943 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1944 "The default column format, if no other format has been defined.
1945 This variable can be set on the per-file basis by inserting a line
1947 #+COLUMNS: %25ITEM ....."
1948 :group 'org-properties
1949 :type 'string)
1951 (defcustom org-global-properties nil
1952 "List of property/value pairs that can be inherited by any entry.
1953 You can set buffer-local values for this by adding lines like
1955 #+PROPERTY: NAME VALUE"
1956 :group 'org-properties
1957 :type '(repeat
1958 (cons (string :tag "Property")
1959 (string :tag "Value"))))
1961 (defvar org-local-properties nil
1962 "List of property/value pairs that can be inherited by any entry.
1963 Valid for the current buffer.
1964 This variable is populated from #+PROPERTY lines.")
1966 (defgroup org-agenda nil
1967 "Options concerning agenda views in Org-mode."
1968 :tag "Org Agenda"
1969 :group 'org)
1971 (defvar org-category nil
1972 "Variable used by org files to set a category for agenda display.
1973 Such files should use a file variable to set it, for example
1975 # -*- mode: org; org-category: \"ELisp\"
1977 or contain a special line
1979 #+CATEGORY: ELisp
1981 If the file does not specify a category, then file's base name
1982 is used instead.")
1983 (make-variable-buffer-local 'org-category)
1985 (defcustom org-agenda-files nil
1986 "The files to be used for agenda display.
1987 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1988 \\[org-remove-file]. You can also use customize to edit the list.
1990 If an entry is a directory, all files in that directory that are matched by
1991 `org-agenda-file-regexp' will be part of the file list.
1993 If the value of the variable is not a list but a single file name, then
1994 the list of agenda files is actually stored and maintained in that file, one
1995 agenda file per line."
1996 :group 'org-agenda
1997 :type '(choice
1998 (repeat :tag "List of files and directories" file)
1999 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2001 (defcustom org-agenda-file-regexp "\\.org\\'"
2002 "Regular expression to match files for `org-agenda-files'.
2003 If any element in the list in that variable contains a directory instead
2004 of a normal file, all files in that directory that are matched by this
2005 regular expression will be included."
2006 :group 'org-agenda
2007 :type 'regexp)
2009 (defcustom org-agenda-skip-unavailable-files nil
2010 "t means to just skip non-reachable files in `org-agenda-files'.
2011 Nil means to remove them, after a query, from the list."
2012 :group 'org-agenda
2013 :type 'boolean)
2015 (defcustom org-agenda-multi-occur-extra-files nil
2016 "List of extra files to be searched by `org-occur-in-agenda-files'.
2017 The files in `org-agenda-files' are always searched."
2018 :group 'org-agenda
2019 :type '(repeat file))
2021 (defcustom org-agenda-confirm-kill 1
2022 "When set, remote killing from the agenda buffer needs confirmation.
2023 When t, a confirmation is always needed. When a number N, confirmation is
2024 only needed when the text to be killed contains more than N non-white lines."
2025 :group 'org-agenda
2026 :type '(choice
2027 (const :tag "Never" nil)
2028 (const :tag "Always" t)
2029 (number :tag "When more than N lines")))
2031 (defcustom org-calendar-to-agenda-key [?c]
2032 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2033 The command `org-calendar-goto-agenda' will be bound to this key. The
2034 default is the character `c' because then `c' can be used to switch back and
2035 forth between agenda and calendar."
2036 :group 'org-agenda
2037 :type 'sexp)
2039 (defcustom org-agenda-compact-blocks nil
2040 "Non-nil means, make the block agenda more compact.
2041 This is done by leaving out unnecessary lines."
2042 :group 'org-agenda
2043 :type nil)
2045 (defgroup org-agenda-export nil
2046 "Options concerning exporting agenda views in Org-mode."
2047 :tag "Org Agenda Export"
2048 :group 'org-agenda)
2050 (defcustom org-agenda-with-colors t
2051 "Non-nil means, use colors in agenda views."
2052 :group 'org-agenda-export
2053 :type 'boolean)
2055 (defcustom org-agenda-exporter-settings nil
2056 "Alist of variable/value pairs that should be active during agenda export.
2057 This is a good place to set uptions for ps-print and for htmlize."
2058 :group 'org-agenda-export
2059 :type '(repeat
2060 (list
2061 (variable)
2062 (sexp :tag "Value"))))
2064 (defcustom org-agenda-export-html-style ""
2065 "The style specification for exported HTML Agenda files.
2066 If this variable contains a string, it will replace the default <style>
2067 section as produced by `htmlize'.
2068 Since there are different ways of setting style information, this variable
2069 needs to contain the full HTML structure to provide a style, including the
2070 surrounding HTML tags. The style specifications should include definitions
2071 the fonts used by the agenda, here is an example:
2073 <style type=\"text/css\">
2074 p { font-weight: normal; color: gray; }
2075 .org-agenda-structure {
2076 font-size: 110%;
2077 color: #003399;
2078 font-weight: 600;
2080 .org-todo {
2081 color: #cc6666;Week-agenda:
2082 font-weight: bold;
2084 .org-done {
2085 color: #339933;
2087 .title { text-align: center; }
2088 .todo, .deadline { color: red; }
2089 .done { color: green; }
2090 </style>
2092 or, if you want to keep the style in a file,
2094 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2096 As the value of this option simply gets inserted into the HTML <head> header,
2097 you can \"misuse\" it to also add other text to the header. However,
2098 <style>...</style> is required, if not present the variable will be ignored."
2099 :group 'org-agenda-export
2100 :group 'org-export-html
2101 :type 'string)
2103 (defgroup org-agenda-custom-commands nil
2104 "Options concerning agenda views in Org-mode."
2105 :tag "Org Agenda Custom Commands"
2106 :group 'org-agenda)
2108 (defcustom org-agenda-custom-commands nil
2109 "Custom commands for the agenda.
2110 These commands will be offered on the splash screen displayed by the
2111 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2113 (key desc type match options files)
2115 key The key (one or more characters as a string) to be associated
2116 with the command.
2117 desc A description of the commend, when omitted or nil, a default
2118 description is built using MATCH.
2119 type The command type, any of the following symbols:
2120 todo Entries with a specific TODO keyword, in all agenda files.
2121 tags Tags match in all agenda files.
2122 tags-todo Tags match in all agenda files, TODO entries only.
2123 todo-tree Sparse tree of specific TODO keyword in *current* file.
2124 tags-tree Sparse tree with all tags matches in *current* file.
2125 occur-tree Occur sparse tree for *current* file.
2126 ... A user-defined function.
2127 match What to search for:
2128 - a single keyword for TODO keyword searches
2129 - a tags match expression for tags searches
2130 - a regular expression for occur searches
2131 options A list of option settings, similar to that in a let form, so like
2132 this: ((opt1 val1) (opt2 val2) ...)
2133 files A list of files file to write the produced agenda buffer to
2134 with the command `org-store-agenda-views'.
2135 If a file name ends in \".html\", an HTML version of the buffer
2136 is written out. If it ends in \".ps\", a postscript version is
2137 produced. Otherwide, only the plain text is written to the file.
2139 You can also define a set of commands, to create a composite agenda buffer.
2140 In this case, an entry looks like this:
2142 (key desc (cmd1 cmd2 ...) general-options file)
2144 where
2146 desc A description string to be displayed in the dispatcher menu.
2147 cmd An agenda command, similar to the above. However, tree commands
2148 are no allowed, but instead you can get agenda and global todo list.
2149 So valid commands for a set are:
2150 (agenda)
2151 (alltodo)
2152 (stuck)
2153 (todo \"match\" options files)
2154 (tags \"match\" options files)
2155 (tags-todo \"match\" options files)
2157 Each command can carry a list of options, and another set of options can be
2158 given for the whole set of commands. Individual command options take
2159 precedence over the general options.
2161 When using several characters as key to a command, the first characters
2162 are prefix commands. For the dispatcher to display useful information, you
2163 should provide a description for the prefix, like
2165 (setq org-agenda-custom-commands
2166 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2167 (\"hl\" tags \"+HOME+Lisa\")
2168 (\"hp\" tags \"+HOME+Peter\")
2169 (\"hk\" tags \"+HOME+Kim\")))"
2170 :group 'org-agenda-custom-commands
2171 :type '(repeat
2172 (choice :value ("a" "" tags "" nil)
2173 (list :tag "Single command"
2174 (string :tag "Access Key(s) ")
2175 (option (string :tag "Description"))
2176 (choice
2177 (const :tag "Agenda" agenda)
2178 (const :tag "TODO list" alltodo)
2179 (const :tag "Stuck projects" stuck)
2180 (const :tag "Tags search (all agenda files)" tags)
2181 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2182 (const :tag "TODO keyword search (all agenda files)" todo)
2183 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2184 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2185 (const :tag "Occur tree (current buffer)" occur-tree)
2186 (sexp :tag "Other, user-defined function"))
2187 (string :tag "Match")
2188 (repeat :tag "Local options"
2189 (list (variable :tag "Option") (sexp :tag "Value")))
2190 (option (repeat :tag "Export" (file :tag "Export to"))))
2191 (list :tag "Command series, all agenda files"
2192 (string :tag "Access Key(s)")
2193 (string :tag "Description ")
2194 (repeat
2195 (choice
2196 (const :tag "Agenda" (agenda))
2197 (const :tag "TODO list" (alltodo))
2198 (const :tag "Stuck projects" (stuck))
2199 (list :tag "Tags search"
2200 (const :format "" tags)
2201 (string :tag "Match")
2202 (repeat :tag "Local options"
2203 (list (variable :tag "Option")
2204 (sexp :tag "Value"))))
2206 (list :tag "Tags search, TODO entries only"
2207 (const :format "" tags-todo)
2208 (string :tag "Match")
2209 (repeat :tag "Local options"
2210 (list (variable :tag "Option")
2211 (sexp :tag "Value"))))
2213 (list :tag "TODO keyword search"
2214 (const :format "" todo)
2215 (string :tag "Match")
2216 (repeat :tag "Local options"
2217 (list (variable :tag "Option")
2218 (sexp :tag "Value"))))
2220 (list :tag "Other, user-defined function"
2221 (symbol :tag "function")
2222 (string :tag "Match")
2223 (repeat :tag "Local options"
2224 (list (variable :tag "Option")
2225 (sexp :tag "Value"))))))
2227 (repeat :tag "General options"
2228 (list (variable :tag "Option")
2229 (sexp :tag "Value")))
2230 (option (repeat :tag "Export" (file :tag "Export to"))))
2231 (cons :tag "Prefix key documentation"
2232 (string :tag "Access Key(s)")
2233 (string :tag "Description ")))))
2235 (defcustom org-stuck-projects
2236 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2237 "How to identify stuck projects.
2238 This is a list of four items:
2239 1. A tags/todo matcher string that is used to identify a project.
2240 The entire tree below a headline matched by this is considered one project.
2241 2. A list of TODO keywords identifying non-stuck projects.
2242 If the project subtree contains any headline with one of these todo
2243 keywords, the project is considered to be not stuck. If you specify
2244 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2245 3. A list of tags identifying non-stuck projects.
2246 If the project subtree contains any headline with one of these tags,
2247 the project is considered to be not stuck. If you specify \"*\" as
2248 a tag, any tag will mark the project unstuck.
2249 4. An arbitrary regular expression matching non-stuck projects.
2251 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2252 or `C-c a #' to produce the list."
2253 :group 'org-agenda-custom-commands
2254 :type '(list
2255 (string :tag "Tags/TODO match to identify a project")
2256 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2257 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2258 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2261 (defgroup org-agenda-skip nil
2262 "Options concerning skipping parts of agenda files."
2263 :tag "Org Agenda Skip"
2264 :group 'org-agenda)
2266 (defcustom org-agenda-todo-list-sublevels t
2267 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2268 When nil, the sublevels of a TODO entry are not checked, resulting in
2269 potentially much shorter TODO lists."
2270 :group 'org-agenda-skip
2271 :group 'org-todo
2272 :type 'boolean)
2274 (defcustom org-agenda-todo-ignore-with-date nil
2275 "Non-nil means, don't show entries with a date in the global todo list.
2276 You can use this if you prefer to mark mere appointments with a TODO keyword,
2277 but don't want them to show up in the TODO list.
2278 When this is set, it also covers deadlines and scheduled items, the settings
2279 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2280 will be ignored."
2281 :group 'org-agenda-skip
2282 :group 'org-todo
2283 :type 'boolean)
2285 (defcustom org-agenda-todo-ignore-scheduled nil
2286 "Non-nil means, don't show scheduled entries in the global todo list.
2287 The idea behind this is that by scheduling it, you have already taken care
2288 of this item.
2289 See also `org-agenda-todo-ignore-with-date'."
2290 :group 'org-agenda-skip
2291 :group 'org-todo
2292 :type 'boolean)
2294 (defcustom org-agenda-todo-ignore-deadlines nil
2295 "Non-nil means, don't show near deadline entries in the global todo list.
2296 Near means closer than `org-deadline-warning-days' days.
2297 The idea behind this is that such items will appear in the agenda anyway.
2298 See also `org-agenda-todo-ignore-with-date'."
2299 :group 'org-agenda-skip
2300 :group 'org-todo
2301 :type 'boolean)
2303 (defcustom org-agenda-skip-scheduled-if-done nil
2304 "Non-nil means don't show scheduled items in agenda when they are done.
2305 This is relevant for the daily/weekly agenda, not for the TODO list. And
2306 it applies only to the actual date of the scheduling. Warnings about
2307 an item with a past scheduling dates are always turned off when the item
2308 is DONE."
2309 :group 'org-agenda-skip
2310 :type 'boolean)
2312 (defcustom org-agenda-skip-deadline-if-done nil
2313 "Non-nil means don't show deadines when the corresponding item is done.
2314 When nil, the deadline is still shown and should give you a happy feeling.
2315 This is relevant for the daily/weekly agenda. And it applied only to the
2316 actualy date of the deadline. Warnings about approching and past-due
2317 deadlines are always turned off when the item is DONE."
2318 :group 'org-agenda-skip
2319 :type 'boolean)
2321 (defcustom org-timeline-show-empty-dates 3
2322 "Non-nil means, `org-timeline' also shows dates without an entry.
2323 When nil, only the days which actually have entries are shown.
2324 When t, all days between the first and the last date are shown.
2325 When an integer, show also empty dates, but if there is a gap of more than
2326 N days, just insert a special line indicating the size of the gap."
2327 :group 'org-agenda-skip
2328 :type '(choice
2329 (const :tag "None" nil)
2330 (const :tag "All" t)
2331 (number :tag "at most")))
2334 (defgroup org-agenda-startup nil
2335 "Options concerning initial settings in the Agenda in Org Mode."
2336 :tag "Org Agenda Startup"
2337 :group 'org-agenda)
2339 (defcustom org-finalize-agenda-hook nil
2340 "Hook run just before displaying an agenda buffer."
2341 :group 'org-agenda-startup
2342 :type 'hook)
2344 (defcustom org-agenda-mouse-1-follows-link nil
2345 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2346 A longer mouse click will still set point. Does not wortk on XEmacs.
2347 Needs to be set before org.el is loaded."
2348 :group 'org-agenda-startup
2349 :type 'boolean)
2351 (defcustom org-agenda-start-with-follow-mode nil
2352 "The initial value of follow-mode in a newly created agenda window."
2353 :group 'org-agenda-startup
2354 :type 'boolean)
2356 (defgroup org-agenda-windows nil
2357 "Options concerning the windows used by the Agenda in Org Mode."
2358 :tag "Org Agenda Windows"
2359 :group 'org-agenda)
2361 (defcustom org-agenda-window-setup 'reorganize-frame
2362 "How the agenda buffer should be displayed.
2363 Possible values for this option are:
2365 current-window Show agenda in the current window, keeping all other windows.
2366 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2367 other-window Use `switch-to-buffer-other-window' to display agenda.
2368 reorganize-frame Show only two windows on the current frame, the current
2369 window and the agenda.
2370 See also the variable `org-agenda-restore-windows-after-quit'."
2371 :group 'org-agenda-windows
2372 :type '(choice
2373 (const current-window)
2374 (const other-frame)
2375 (const other-window)
2376 (const reorganize-frame)))
2378 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2379 "The min and max height of the agenda window as a fraction of frame height.
2380 The value of the variable is a cons cell with two numbers between 0 and 1.
2381 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2382 :group 'org-agenda-windows
2383 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2385 (defcustom org-agenda-restore-windows-after-quit nil
2386 "Non-nil means, restore window configuration open exiting agenda.
2387 Before the window configuration is changed for displaying the agenda,
2388 the current status is recorded. When the agenda is exited with
2389 `q' or `x' and this option is set, the old state is restored. If
2390 `org-agenda-window-setup' is `other-frame', the value of this
2391 option will be ignored.."
2392 :group 'org-agenda-windows
2393 :type 'boolean)
2395 (defcustom org-indirect-buffer-display 'other-window
2396 "How should indirect tree buffers be displayed?
2397 This applies to indirect buffers created with the commands
2398 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2399 Valid values are:
2400 current-window Display in the current window
2401 other-window Just display in another window.
2402 dedicated-frame Create one new frame, and re-use it each time.
2403 new-frame Make a new frame each time."
2404 :group 'org-structure
2405 :group 'org-agenda-windows
2406 :type '(choice
2407 (const :tag "In current window" current-window)
2408 (const :tag "In current frame, other window" other-window)
2409 (const :tag "Each time a new frame" new-frame)
2410 (const :tag "One dedicated frame" dedicated-frame)))
2412 (defgroup org-agenda-daily/weekly nil
2413 "Options concerning the daily/weekly agenda."
2414 :tag "Org Agenda Daily/Weekly"
2415 :group 'org-agenda)
2417 (defcustom org-agenda-ndays 7
2418 "Number of days to include in overview display.
2419 Should be 1 or 7."
2420 :group 'org-agenda-daily/weekly
2421 :type 'number)
2423 (defcustom org-agenda-start-on-weekday 1
2424 "Non-nil means, start the overview always on the specified weekday.
2425 0 denotes Sunday, 1 denotes Monday etc.
2426 When nil, always start on the current day."
2427 :group 'org-agenda-daily/weekly
2428 :type '(choice (const :tag "Today" nil)
2429 (number :tag "Weekday No.")))
2431 (defcustom org-agenda-show-all-dates t
2432 "Non-nil means, `org-agenda' shows every day in the selected range.
2433 When nil, only the days which actually have entries are shown."
2434 :group 'org-agenda-daily/weekly
2435 :type 'boolean)
2437 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2438 "Format string for displaying dates in the agenda.
2439 Used by the daily/weekly agenda and by the timeline. This should be
2440 a format string understood by `format-time-string', or a function returning
2441 the formatted date as a string. The function must take a single argument,
2442 a calendar-style date list like (month day year)."
2443 :group 'org-agenda-daily/weekly
2444 :type '(choice
2445 (string :tag "Format string")
2446 (function :tag "Function")))
2448 (defun org-agenda-format-date-aligned (date)
2449 "Format a date string for display in the daily/weekly agenda, or timeline.
2450 This function makes sure that dates are aligned for easy reading."
2451 (format "%-9s %2d %s %4d"
2452 (calendar-day-name date)
2453 (extract-calendar-day date)
2454 (calendar-month-name (extract-calendar-month date))
2455 (extract-calendar-year date)))
2457 (defcustom org-agenda-include-diary nil
2458 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2459 :group 'org-agenda-daily/weekly
2460 :type 'boolean)
2462 (defcustom org-agenda-include-all-todo nil
2463 "Set means weekly/daily agenda will always contain all TODO entries.
2464 The TODO entries will be listed at the top of the agenda, before
2465 the entries for specific days."
2466 :group 'org-agenda-daily/weekly
2467 :type 'boolean)
2469 (defcustom org-agenda-repeating-timestamp-show-all t
2470 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2471 When nil, only one occurence is shown, either today or the
2472 nearest into the future."
2473 :group 'org-agenda-daily/weekly
2474 :type 'boolean)
2476 (defcustom org-deadline-warning-days 14
2477 "No. of days before expiration during which a deadline becomes active.
2478 This variable governs the display in sparse trees and in the agenda.
2479 When negative, it means use this number (the absolute value of it)
2480 even if a deadline has a different individual lead time specified."
2481 :group 'org-time
2482 :group 'org-agenda-daily/weekly
2483 :type 'number)
2485 (defcustom org-scheduled-past-days 10000
2486 "No. of days to continue listing scheduled items that are not marked DONE.
2487 When an item is scheduled on a date, it shows up in the agenda on this
2488 day and will be listed until it is marked done for the number of days
2489 given here."
2490 :group 'org-agenda-daily/weekly
2491 :type 'number)
2493 (defgroup org-agenda-time-grid nil
2494 "Options concerning the time grid in the Org-mode Agenda."
2495 :tag "Org Agenda Time Grid"
2496 :group 'org-agenda)
2498 (defcustom org-agenda-use-time-grid t
2499 "Non-nil means, show a time grid in the agenda schedule.
2500 A time grid is a set of lines for specific times (like every two hours between
2501 8:00 and 20:00). The items scheduled for a day at specific times are
2502 sorted in between these lines.
2503 For details about when the grid will be shown, and what it will look like, see
2504 the variable `org-agenda-time-grid'."
2505 :group 'org-agenda-time-grid
2506 :type 'boolean)
2508 (defcustom org-agenda-time-grid
2509 '((daily today require-timed)
2510 "----------------"
2511 (800 1000 1200 1400 1600 1800 2000))
2513 "The settings for time grid for agenda display.
2514 This is a list of three items. The first item is again a list. It contains
2515 symbols specifying conditions when the grid should be displayed:
2517 daily if the agenda shows a single day
2518 weekly if the agenda shows an entire week
2519 today show grid on current date, independent of daily/weekly display
2520 require-timed show grid only if at least one item has a time specification
2522 The second item is a string which will be places behing the grid time.
2524 The third item is a list of integers, indicating the times that should have
2525 a grid line."
2526 :group 'org-agenda-time-grid
2527 :type
2528 '(list
2529 (set :greedy t :tag "Grid Display Options"
2530 (const :tag "Show grid in single day agenda display" daily)
2531 (const :tag "Show grid in weekly agenda display" weekly)
2532 (const :tag "Always show grid for today" today)
2533 (const :tag "Show grid only if any timed entries are present"
2534 require-timed)
2535 (const :tag "Skip grid times already present in an entry"
2536 remove-match))
2537 (string :tag "Grid String")
2538 (repeat :tag "Grid Times" (integer :tag "Time"))))
2540 (defgroup org-agenda-sorting nil
2541 "Options concerning sorting in the Org-mode Agenda."
2542 :tag "Org Agenda Sorting"
2543 :group 'org-agenda)
2545 (let ((sorting-choice
2546 '(choice
2547 (const time-up) (const time-down)
2548 (const category-keep) (const category-up) (const category-down)
2549 (const tag-down) (const tag-up)
2550 (const priority-up) (const priority-down))))
2552 (defcustom org-agenda-sorting-strategy
2553 '((agenda time-up category-keep priority-down)
2554 (todo category-keep priority-down)
2555 (tags category-keep priority-down))
2556 "Sorting structure for the agenda items of a single day.
2557 This is a list of symbols which will be used in sequence to determine
2558 if an entry should be listed before another entry. The following
2559 symbols are recognized:
2561 time-up Put entries with time-of-day indications first, early first
2562 time-down Put entries with time-of-day indications first, late first
2563 category-keep Keep the default order of categories, corresponding to the
2564 sequence in `org-agenda-files'.
2565 category-up Sort alphabetically by category, A-Z.
2566 category-down Sort alphabetically by category, Z-A.
2567 tag-up Sort alphabetically by last tag, A-Z.
2568 tag-down Sort alphabetically by last tag, Z-A.
2569 priority-up Sort numerically by priority, high priority last.
2570 priority-down Sort numerically by priority, high priority first.
2572 The different possibilities will be tried in sequence, and testing stops
2573 if one comparison returns a \"not-equal\". For example, the default
2574 '(time-up category-keep priority-down)
2575 means: Pull out all entries having a specified time of day and sort them,
2576 in order to make a time schedule for the current day the first thing in the
2577 agenda listing for the day. Of the entries without a time indication, keep
2578 the grouped in categories, don't sort the categories, but keep them in
2579 the sequence given in `org-agenda-files'. Within each category sort by
2580 priority.
2582 Leaving out `category-keep' would mean that items will be sorted across
2583 categories by priority."
2584 :group 'org-agenda-sorting
2585 :type `(choice
2586 (repeat :tag "General" ,sorting-choice)
2587 (list :tag "Individually"
2588 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2589 (repeat ,sorting-choice))
2590 (cons (const :tag "Strategy for TODO lists" todo)
2591 (repeat ,sorting-choice))
2592 (cons (const :tag "Strategy for Tags matches" tags)
2593 (repeat ,sorting-choice))))))
2595 (defcustom org-sort-agenda-notime-is-late t
2596 "Non-nil means, items without time are considered late.
2597 This is only relevant for sorting. When t, items which have no explicit
2598 time like 15:30 will be considered as 99:01, i.e. later than any items which
2599 do have a time. When nil, the default time is before 0:00. You can use this
2600 option to decide if the schedule for today should come before or after timeless
2601 agenda entries."
2602 :group 'org-agenda-sorting
2603 :type 'boolean)
2605 (defgroup org-agenda-line-format nil
2606 "Options concerning the entry prefix in the Org-mode agenda display."
2607 :tag "Org Agenda Line Format"
2608 :group 'org-agenda)
2610 (defcustom org-agenda-prefix-format
2611 '((agenda . " %-12:c%?-12t% s")
2612 (timeline . " % s")
2613 (todo . " %-12:c")
2614 (tags . " %-12:c"))
2615 "Format specifications for the prefix of items in the agenda views.
2616 An alist with four entries, for the different agenda types. The keys to the
2617 sublists are `agenda', `timeline', `todo', and `tags'. The values
2618 are format strings.
2619 This format works similar to a printf format, with the following meaning:
2621 %c the category of the item, \"Diary\" for entries from the diary, or
2622 as given by the CATEGORY keyword or derived from the file name.
2623 %T the *last* tag of the item. Last because inherited tags come
2624 first in the list.
2625 %t the time-of-day specification if one applies to the entry, in the
2626 format HH:MM
2627 %s Scheduling/Deadline information, a short string
2629 All specifiers work basically like the standard `%s' of printf, but may
2630 contain two additional characters: A question mark just after the `%' and
2631 a whitespace/punctuation character just before the final letter.
2633 If the first character after `%' is a question mark, the entire field
2634 will only be included if the corresponding value applies to the
2635 current entry. This is useful for fields which should have fixed
2636 width when present, but zero width when absent. For example,
2637 \"%?-12t\" will result in a 12 character time field if a time of the
2638 day is specified, but will completely disappear in entries which do
2639 not contain a time.
2641 If there is punctuation or whitespace character just before the final
2642 format letter, this character will be appended to the field value if
2643 the value is not empty. For example, the format \"%-12:c\" leads to
2644 \"Diary: \" if the category is \"Diary\". If the category were be
2645 empty, no additional colon would be interted.
2647 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2648 - Indent the line with two space characters
2649 - Give the category in a 12 chars wide field, padded with whitespace on
2650 the right (because of `-'). Append a colon if there is a category
2651 (because of `:').
2652 - If there is a time-of-day, put it into a 12 chars wide field. If no
2653 time, don't put in an empty field, just skip it (because of '?').
2654 - Finally, put the scheduling information and append a whitespace.
2656 As another example, if you don't want the time-of-day of entries in
2657 the prefix, you could use:
2659 (setq org-agenda-prefix-format \" %-11:c% s\")
2661 See also the variables `org-agenda-remove-times-when-in-prefix' and
2662 `org-agenda-remove-tags'."
2663 :type '(choice
2664 (string :tag "General format")
2665 (list :greedy t :tag "View dependent"
2666 (cons (const agenda) (string :tag "Format"))
2667 (cons (const timeline) (string :tag "Format"))
2668 (cons (const todo) (string :tag "Format"))
2669 (cons (const tags) (string :tag "Format"))))
2670 :group 'org-agenda-line-format)
2672 (defvar org-prefix-format-compiled nil
2673 "The compiled version of the most recently used prefix format.
2674 See the variable `org-agenda-prefix-format'.")
2676 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2677 "Text preceeding scheduled items in the agenda view.
2678 THis is a list with two strings. The first applies when the item is
2679 scheduled on the current day. The second applies when it has been scheduled
2680 previously, it may contain a %d to capture how many days ago the item was
2681 scheduled."
2682 :group 'org-agenda-line-format
2683 :type '(list
2684 (string :tag "Scheduled today ")
2685 (string :tag "Scheduled previously")))
2687 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2688 "Text preceeding deadline items in the agenda view.
2689 This is a list with two strings. The first applies when the item has its
2690 deadline on the current day. The second applies when it is in the past or
2691 in the future, it may contain %d to capture how many days away the deadline
2692 is (was)."
2693 :group 'org-agenda-line-format
2694 :type '(list
2695 (string :tag "Deadline today ")
2696 (string :tag "Deadline relative")))
2698 (defcustom org-agenda-remove-times-when-in-prefix t
2699 "Non-nil means, remove duplicate time specifications in agenda items.
2700 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2701 time-of-day specification in a headline or diary entry is extracted and
2702 placed into the prefix. If this option is non-nil, the original specification
2703 \(a timestamp or -range, or just a plain time(range) specification like
2704 11:30-4pm) will be removed for agenda display. This makes the agenda less
2705 cluttered.
2706 The option can be t or nil. It may also be the symbol `beg', indicating
2707 that the time should only be removed what it is located at the beginning of
2708 the headline/diary entry."
2709 :group 'org-agenda-line-format
2710 :type '(choice
2711 (const :tag "Always" t)
2712 (const :tag "Never" nil)
2713 (const :tag "When at beginning of entry" beg)))
2716 (defcustom org-agenda-default-appointment-duration nil
2717 "Default duration for appointments that only have a starting time.
2718 When nil, no duration is specified in such cases.
2719 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2720 :group 'org-agenda-line-format
2721 :type '(choice
2722 (integer :tag "Minutes")
2723 (const :tag "No default duration")))
2726 (defcustom org-agenda-remove-tags nil
2727 "Non-nil means, remove the tags from the headline copy in the agenda.
2728 When this is the symbol `prefix', only remove tags when
2729 `org-agenda-prefix-format' contains a `%T' specifier."
2730 :group 'org-agenda-line-format
2731 :type '(choice
2732 (const :tag "Always" t)
2733 (const :tag "Never" nil)
2734 (const :tag "When prefix format contains %T" prefix)))
2736 (if (fboundp 'defvaralias)
2737 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2738 'org-agenda-remove-tags))
2740 (defcustom org-agenda-tags-column -80
2741 "Shift tags in agenda items to this column.
2742 If this number is positive, it specifies the column. If it is negative,
2743 it means that the tags should be flushright to that column. For example,
2744 -80 works well for a normal 80 character screen."
2745 :group 'org-agenda-line-format
2746 :type 'integer)
2748 (if (fboundp 'defvaralias)
2749 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2751 (defcustom org-agenda-fontify-priorities t
2752 "Non-nil means, highlight low and high priorities in agenda.
2753 When t, the highest priority entries are bold, lowest priority italic.
2754 This may also be an association list of priority faces. The face may be
2755 a names face, or a list like `(:background \"Red\")'."
2756 :group 'org-agenda-line-format
2757 :type '(choice
2758 (const :tag "Never" nil)
2759 (const :tag "Defaults" t)
2760 (repeat :tag "Specify"
2761 (list (character :tag "Priority" :value ?A)
2762 (sexp :tag "face")))))
2764 (defgroup org-latex nil
2765 "Options for embedding LaTeX code into Org-mode"
2766 :tag "Org LaTeX"
2767 :group 'org)
2769 (defcustom org-format-latex-options
2770 '(:foreground default :background default :scale 1.0
2771 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2772 :matchers ("begin" "$" "$$" "\\(" "\\["))
2773 "Options for creating images from LaTeX fragments.
2774 This is a property list with the following properties:
2775 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2776 `default' means use the forground of the default face.
2777 :background the background color, or \"Transparent\".
2778 `default' means use the background of the default face.
2779 :scale a scaling factor for the size of the images
2780 :html-foreground, :html-background, :html-scale
2781 The same numbers for HTML export.
2782 :matchers a list indicating which matchers should be used to
2783 find LaTeX fragments. Valid members of this list are:
2784 \"begin\" find environments
2785 \"$\" find math expressions surrounded by $...$
2786 \"$$\" find math expressions surrounded by $$....$$
2787 \"\\(\" find math expressions surrounded by \\(...\\)
2788 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2789 :group 'org-latex
2790 :type 'plist)
2792 (defcustom org-format-latex-header "\\documentclass{article}
2793 \\usepackage{fullpage} % do not remove
2794 \\usepackage{amssymb}
2795 \\usepackage[usenames]{color}
2796 \\usepackage{amsmath}
2797 \\usepackage{latexsym}
2798 \\usepackage[mathscr]{eucal}
2799 \\pagestyle{empty} % do not remove"
2800 "The document header used for processing LaTeX fragments."
2801 :group 'org-latex
2802 :type 'string)
2804 (defgroup org-export nil
2805 "Options for exporting org-listings."
2806 :tag "Org Export"
2807 :group 'org)
2809 (defgroup org-export-general nil
2810 "General options for exporting Org-mode files."
2811 :tag "Org Export General"
2812 :group 'org-export)
2814 (defcustom org-export-publishing-directory "."
2815 "Path to the location where exported files should be located.
2816 This path may be relative to the directory where the Org-mode file lives.
2817 The default is to put them into the same directory as the Org-mode file.
2818 The variable may also be an alist with export types `:html', `:ascii',
2819 `:ical', `:LaTeX', or `:xoxo' and the corresponding directories.
2820 If a directory path is relative, it is interpreted relative to the
2821 directory where the exported Org-mode files lives."
2822 :group 'org-export-general
2823 :type '(choice
2824 (directory)
2825 (repeat
2826 (cons
2827 (choice :tag "Type"
2828 (const :html) (const :LaTeX)
2829 (const :ascii) (const :ical) (const :xoxo))
2830 (directory)))))
2832 (defcustom org-export-language-setup
2833 '(("en" "Author" "Date" "Table of Contents")
2834 ("cs" "Autor" "Datum" "Obsah")
2835 ("da" "Ophavsmand" "Dato" "Indhold")
2836 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2837 ("es" "Autor" "Fecha" "\xcdndice")
2838 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2839 ("it" "Autore" "Data" "Indice")
2840 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2841 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2842 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2843 "Terms used in export text, translated to different languages.
2844 Use the variable `org-export-default-language' to set the language,
2845 or use the +OPTION lines for a per-file setting."
2846 :group 'org-export-general
2847 :type '(repeat
2848 (list
2849 (string :tag "HTML language tag")
2850 (string :tag "Author")
2851 (string :tag "Date")
2852 (string :tag "Table of Contents"))))
2854 (defcustom org-export-default-language "en"
2855 "The default language of HTML export, as a string.
2856 This should have an association in `org-export-language-setup'."
2857 :group 'org-export-general
2858 :type 'string)
2860 (defcustom org-export-skip-text-before-1st-heading t
2861 "Non-nil means, skip all text before the first headline when exporting.
2862 When nil, that text is exported as well."
2863 :group 'org-export-general
2864 :type 'boolean)
2866 (defcustom org-export-headline-levels 3
2867 "The last level which is still exported as a headline.
2868 Inferior levels will produce itemize lists when exported.
2869 Note that a numeric prefix argument to an exporter function overrides
2870 this setting.
2872 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2873 :group 'org-export-general
2874 :type 'number)
2876 (defcustom org-export-with-section-numbers t
2877 "Non-nil means, add section numbers to headlines when exporting.
2879 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2880 :group 'org-export-general
2881 :type 'boolean)
2883 (defcustom org-export-with-toc t
2884 "Non-nil means, create a table of contents in exported files.
2885 The TOC contains headlines with levels up to`org-export-headline-levels'.
2886 When an integer, include levels up to N in the toc, this may then be
2887 different from `org-export-headline-levels', but it will not be allowed
2888 to be larger than the number of headline levels.
2889 When nil, no table of contents is made.
2891 Headlines which contain any TODO items will be marked with \"(*)\" in
2892 ASCII export, and with red color in HTML output, if the option
2893 `org-export-mark-todo-in-toc' is set.
2895 In HTML output, the TOC will be clickable.
2897 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2898 or \"toc:3\"."
2899 :group 'org-export-general
2900 :type '(choice
2901 (const :tag "No Table of Contents" nil)
2902 (const :tag "Full Table of Contents" t)
2903 (integer :tag "TOC to level")))
2905 (defcustom org-export-mark-todo-in-toc nil
2906 "Non-nil means, mark TOC lines that contain any open TODO items."
2907 :group 'org-export-general
2908 :type 'boolean)
2910 (defcustom org-export-preserve-breaks nil
2911 "Non-nil means, preserve all line breaks when exporting.
2912 Normally, in HTML output paragraphs will be reformatted. In ASCII
2913 export, line breaks will always be preserved, regardless of this variable.
2915 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
2916 :group 'org-export-general
2917 :type 'boolean)
2919 (defcustom org-export-with-archived-trees 'headline
2920 "Whether subtrees with the ARCHIVE tag should be exported.
2921 This can have three different values
2922 nil Do not export, pretend this tree is not present
2923 t Do export the entire tree
2924 headline Only export the headline, but skip the tree below it."
2925 :group 'org-export-general
2926 :group 'org-archive
2927 :type '(choice
2928 (const :tag "not at all" nil)
2929 (const :tag "headline only" 'headline)
2930 (const :tag "entirely" t)))
2932 (defcustom org-export-author-info t
2933 "Non-nil means, insert author name and email into the exported file.
2935 This option can also be set with the +OPTIONS line,
2936 e.g. \"author-info:nil\"."
2937 :group 'org-export-general
2938 :type 'boolean)
2940 (defcustom org-export-time-stamp-file t
2941 "Non-nil means, insert a time stamp into the exported file.
2942 The time stamp shows when the file was created.
2944 This option can also be set with the +OPTIONS line,
2945 e.g. \"timestamp:nil\"."
2946 :group 'org-export-general
2947 :type 'boolean)
2949 (defcustom org-export-with-timestamps t
2950 "If nil, do not export time stamps and associated keywords."
2951 :group 'org-export-general
2952 :type 'boolean)
2954 (defcustom org-export-remove-timestamps-from-toc t
2955 "If nil, remove timestamps from the table of contents entries."
2956 :group 'org-export-general
2957 :type 'boolean)
2959 (defcustom org-export-with-tags 'not-in-toc
2960 "If nil, do not export tags, just remove them from headlines.
2961 If this is the symbol `not-in-toc', tags will be removed from table of
2962 contents entries, but still be shown in the headlines of the document.
2964 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
2965 :group 'org-export-general
2966 :type '(choice
2967 (const :tag "Off" nil)
2968 (const :tag "Not in TOC" not-in-toc)
2969 (const :tag "On" t)))
2971 (defcustom org-export-with-drawers nil
2972 "Non-nil means, export with drawers like the property drawer.
2973 When t, all drawers are exported. This may also be a list of
2974 drawer names to export."
2975 :group 'org-export-general
2976 :type '(choice
2977 (const :tag "All drawers" t)
2978 (const :tag "None" nil)
2979 (repeat :tag "Selected drawers"
2980 (string :tag "Drawer name"))))
2982 (defgroup org-export-translation nil
2983 "Options for translating special ascii sequences for the export backends."
2984 :tag "Org Export Translation"
2985 :group 'org-export)
2987 (defcustom org-export-with-emphasize t
2988 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
2989 If the export target supports emphasizing text, the word will be
2990 typeset in bold, italic, or underlined, respectively. Works only for
2991 single words, but you can say: I *really* *mean* *this*.
2992 Not all export backends support this.
2994 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
2995 :group 'org-export-translation
2996 :type 'boolean)
2998 (defcustom org-export-with-footnotes t
2999 "If nil, export [1] as a footnote marker.
3000 Lines starting with [1] will be formatted as footnotes.
3002 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3003 :group 'org-export-translation
3004 :type 'boolean)
3006 (defcustom org-export-with-sub-superscripts t
3007 "Non-nil means, interpret \"_\" and \"^\" for export.
3008 When this option is turned on, you can use TeX-like syntax for sub- and
3009 superscripts. Several characters after \"_\" or \"^\" will be
3010 considered as a single item - so grouping with {} is normally not
3011 needed. For example, the following things will be parsed as single
3012 sub- or superscripts.
3014 10^24 or 10^tau several digits will be considered 1 item.
3015 10^-12 or 10^-tau a leading sign with digits or a word
3016 x^2-y^3 will be read as x^2 - y^3, because items are
3017 terminated by almost any nonword/nondigit char.
3018 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3020 Still, ambiguity is possible - so when in doubt use {} to enclose the
3021 sub/superscript. If you set this variable to the symbol `{}',
3022 the braces are *required* in order to trigger interpretations as
3023 sub/superscript. This can be helpful in documents that need \"_\"
3024 frequently in plain text.
3026 Not all export backends support this, but HTML does.
3028 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3029 :group 'org-export-translation
3030 :type '(choice
3031 (const :tag "Always interpret" t)
3032 (const :tag "Only with braces" {})
3033 (const :tag "Never interpret" nil)))
3035 (defcustom org-export-with-TeX-macros t
3036 "Non-nil means, interpret simple TeX-like macros when exporting.
3037 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3038 No only real TeX macros will work here, but the standard HTML entities
3039 for math can be used as macro names as well. For a list of supported
3040 names in HTML export, see the constant `org-html-entities'.
3041 Not all export backends support this.
3043 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3044 :group 'org-export-translation
3045 :group 'org-export-latex
3046 :type 'boolean)
3048 (defcustom org-export-with-LaTeX-fragments nil
3049 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3050 When set, the exporter will find LaTeX environments if the \\begin line is
3051 the first non-white thing on a line. It will also find the math delimiters
3052 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3053 display math.
3055 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3056 :group 'org-export-translation
3057 :group 'org-export-latex
3058 :type 'boolean)
3060 (defcustom org-export-with-fixed-width t
3061 "Non-nil means, lines starting with \":\" will be in fixed width font.
3062 This can be used to have pre-formatted text, fragments of code etc. For
3063 example:
3064 : ;; Some Lisp examples
3065 : (while (defc cnt)
3066 : (ding))
3067 will be looking just like this in also HTML. See also the QUOTE keyword.
3068 Not all export backends support this.
3070 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3071 :group 'org-export-translation
3072 :type 'boolean)
3074 (defcustom org-match-sexp-depth 3
3075 "Number of stacked braces for sub/superscript matching.
3076 This has to be set before loading org.el to be effective."
3077 :group 'org-export-translation
3078 :type 'integer)
3080 (defgroup org-export-tables nil
3081 "Options for exporting tables in Org-mode."
3082 :tag "Org Export Tables"
3083 :group 'org-export)
3085 (defcustom org-export-with-tables t
3086 "If non-nil, lines starting with \"|\" define a table.
3087 For example:
3089 | Name | Address | Birthday |
3090 |-------------+----------+-----------|
3091 | Arthur Dent | England | 29.2.2100 |
3093 Not all export backends support this.
3095 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3096 :group 'org-export-tables
3097 :type 'boolean)
3099 (defcustom org-export-highlight-first-table-line t
3100 "Non-nil means, highlight the first table line.
3101 In HTML export, this means use <th> instead of <td>.
3102 In tables created with table.el, this applies to the first table line.
3103 In Org-mode tables, all lines before the first horizontal separator
3104 line will be formatted with <th> tags."
3105 :group 'org-export-tables
3106 :type 'boolean)
3108 (defcustom org-export-table-remove-special-lines t
3109 "Remove special lines and marking characters in calculating tables.
3110 This removes the special marking character column from tables that are set
3111 up for spreadsheet calculations. It also removes the entire lines
3112 marked with `!', `_', or `^'. The lines with `$' are kept, because
3113 the values of constants may be useful to have."
3114 :group 'org-export-tables
3115 :type 'boolean)
3117 (defcustom org-export-prefer-native-exporter-for-tables nil
3118 "Non-nil means, always export tables created with table.el natively.
3119 Natively means, use the HTML code generator in table.el.
3120 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3121 the table does not use row- or column-spanning). This has the
3122 advantage, that the automatic HTML conversions for math symbols and
3123 sub/superscripts can be applied. Org-mode's HTML generator is also
3124 much faster."
3125 :group 'org-export-tables
3126 :type 'boolean)
3128 (defgroup org-export-ascii nil
3129 "Options specific for ASCII export of Org-mode files."
3130 :tag "Org Export ASCII"
3131 :group 'org-export)
3133 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3134 "Characters for underlining headings in ASCII export.
3135 In the given sequence, these characters will be used for level 1, 2, ..."
3136 :group 'org-export-ascii
3137 :type '(repeat character))
3139 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3140 "Bullet characters for headlines converted to lists in ASCII export.
3141 The first character is is used for the first lest level generated in this
3142 way, and so on. If there are more levels than characters given here,
3143 the list will be repeated.
3144 Note that plain lists will keep the same bullets as the have in the
3145 Org-mode file."
3146 :group 'org-export-ascii
3147 :type '(repeat character))
3149 (defgroup org-export-xml nil
3150 "Options specific for XML export of Org-mode files."
3151 :tag "Org Export XML"
3152 :group 'org-export)
3154 (defgroup org-export-html nil
3155 "Options specific for HTML export of Org-mode files."
3156 :tag "Org Export HTML"
3157 :group 'org-export)
3159 (defcustom org-export-html-coding-system nil
3161 :group 'org-export-html
3162 :type 'coding-system)
3164 (defcustom org-export-html-extension "html"
3165 "The extension for exported HTML files."
3166 :group 'org-export-html
3167 :type 'string)
3169 (defcustom org-export-html-style
3170 "<style type=\"text/css\">
3171 html {
3172 font-family: Times, serif;
3173 font-size: 12pt;
3175 .title { text-align: center; }
3176 .todo { color: red; }
3177 .done { color: green; }
3178 .timestamp { color: grey }
3179 .timestamp-kwd { color: CadetBlue }
3180 .tag { background-color:lightblue; font-weight:normal }
3181 .target { background-color: lavender; }
3182 pre {
3183 border: 1pt solid #AEBDCC;
3184 background-color: #F3F5F7;
3185 padding: 5pt;
3186 font-family: courier, monospace;
3188 table { border-collapse: collapse; }
3189 td, th {
3190 vertical-align: top;
3191 <!--border: 1pt solid #ADB9CC;-->
3193 </style>"
3194 "The default style specification for exported HTML files.
3195 Since there are different ways of setting style information, this variable
3196 needs to contain the full HTML structure to provide a style, including the
3197 surrounding HTML tags. The style specifications should include definitions
3198 for new classes todo, done, title, and deadline. For example, legal values
3199 would be:
3201 <style type=\"text/css\">
3202 p { font-weight: normal; color: gray; }
3203 h1 { color: black; }
3204 .title { text-align: center; }
3205 .todo, .deadline { color: red; }
3206 .done { color: green; }
3207 </style>
3209 or, if you want to keep the style in a file,
3211 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3213 As the value of this option simply gets inserted into the HTML <head> header,
3214 you can \"misuse\" it to add arbitrary text to the header."
3215 :group 'org-export-html
3216 :type 'string)
3219 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3220 "Format for typesetting the document title in HTML export."
3221 :group 'org-export-html
3222 :type 'string)
3224 (defcustom org-export-html-toplevel-hlevel 2
3225 "The <H> level for level 1 headings in HTML export."
3226 :group 'org-export-html
3227 :type 'string)
3229 (defcustom org-export-html-link-org-files-as-html t
3230 "Non-nil means, make file links to `file.org' point to `file.html'.
3231 When org-mode is exporting an org-mode file to HTML, links to
3232 non-html files are directly put into a href tag in HTML.
3233 However, links to other Org-mode files (recognized by the
3234 extension `.org.) should become links to the corresponding html
3235 file, assuming that the linked org-mode file will also be
3236 converted to HTML.
3237 When nil, the links still point to the plain `.org' file."
3238 :group 'org-export-html
3239 :type 'boolean)
3241 (defcustom org-export-html-inline-images 'maybe
3242 "Non-nil means, inline images into exported HTML pages.
3243 This is done using an <img> tag. When nil, an anchor with href is used to
3244 link to the image. If this option is `maybe', then images in links with
3245 an empty description will be inlined, while images with a description will
3246 be linked only."
3247 :group 'org-export-html
3248 :type '(choice (const :tag "Never" nil)
3249 (const :tag "Always" t)
3250 (const :tag "When there is no description" maybe)))
3252 ;; FIXME: rename
3253 (defcustom org-export-html-expand t
3254 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3255 When nil, these tags will be exported as plain text and therefore
3256 not be interpreted by a browser.
3258 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3259 :group 'org-export-html
3260 :type 'boolean)
3262 (defcustom org-export-html-table-tag
3263 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3264 "The HTML tag that is used to start a table.
3265 This must be a <table> tag, but you may change the options like
3266 borders and spacing."
3267 :group 'org-export-html
3268 :type 'string)
3270 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3271 "The opening tag for table header fields.
3272 This is customizable so that alignment options can be specified."
3273 :group 'org-export-tables
3274 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3276 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3277 "The opening tag for table data fields.
3278 This is customizable so that alignment options can be specified."
3279 :group 'org-export-tables
3280 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3282 (defcustom org-export-html-with-timestamp nil
3283 "If non-nil, write `org-export-html-html-helper-timestamp'
3284 into the exported HTML text. Otherwise, the buffer will just be saved
3285 to a file."
3286 :group 'org-export-html
3287 :type 'boolean)
3289 (defcustom org-export-html-html-helper-timestamp
3290 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3291 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3292 :group 'org-export-html
3293 :type 'string)
3295 (defgroup org-export-icalendar nil
3296 "Options specific for iCalendar export of Org-mode files."
3297 :tag "Org Export iCalendar"
3298 :group 'org-export)
3300 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3301 "The file name for the iCalendar file covering all agenda files.
3302 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3303 The file name should be absolute, the file will be overwritten without warning."
3304 :group 'org-export-icalendar
3305 :type 'file)
3307 (defcustom org-icalendar-include-todo nil
3308 "Non-nil means, export to iCalendar files should also cover TODO items."
3309 :group 'org-export-icalendar
3310 :type '(choice
3311 (const :tag "None" nil)
3312 (const :tag "Unfinished" t)
3313 (const :tag "All" all)))
3315 (defcustom org-icalendar-include-sexps t
3316 "Non-nil means, export to iCalendar files should also cover sexp entries.
3317 These are entries like in the diary, but directly in an Org-mode file."
3318 :group 'org-export-icalendar
3319 :type 'boolean)
3321 (defcustom org-icalendar-include-body 100
3322 "Amount of text below headline to be included in iCalendar export.
3323 This is a number of characters that should maximally be included.
3324 Properties, scheduling and clocking lines will always be removed.
3325 The text will be inserted into the DESCRIPTION field."
3326 :group 'org-export-icalendar
3327 :type '(choice
3328 (const :tag "Nothing" nil)
3329 (const :tag "Everything" t)
3330 (integer :tag "Max characters")))
3332 (defcustom org-icalendar-combined-name "OrgMode"
3333 "Calendar name for the combined iCalendar representing all agenda files."
3334 :group 'org-export-icalendar
3335 :type 'string)
3337 (defgroup org-font-lock nil
3338 "Font-lock settings for highlighting in Org-mode."
3339 :tag "Org Font Lock"
3340 :group 'org)
3342 (defcustom org-level-color-stars-only nil
3343 "Non-nil means fontify only the stars in each headline.
3344 When nil, the entire headline is fontified.
3345 Changing it requires restart of `font-lock-mode' to become effective
3346 also in regions already fontified."
3347 :group 'org-font-lock
3348 :type 'boolean)
3350 (defcustom org-hide-leading-stars nil
3351 "Non-nil means, hide the first N-1 stars in a headline.
3352 This works by using the face `org-hide' for these stars. This
3353 face is white for a light background, and black for a dark
3354 background. You may have to customize the face `org-hide' to
3355 make this work.
3356 Changing it requires restart of `font-lock-mode' to become effective
3357 also in regions already fontified.
3358 You may also set this on a per-file basis by adding one of the following
3359 lines to the buffer:
3361 #+STARTUP: hidestars
3362 #+STARTUP: showstars"
3363 :group 'org-font-lock
3364 :type 'boolean)
3366 (defcustom org-fontify-done-headline nil
3367 "Non-nil means, change the face of a headline if it is marked DONE.
3368 Normally, only the TODO/DONE keyword indicates the state of a headline.
3369 When this is non-nil, the headline after the keyword is set to the
3370 `org-headline-done' as an additional indication."
3371 :group 'org-font-lock
3372 :type 'boolean)
3374 (defcustom org-fontify-emphasized-text t
3375 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3376 Changing this variable requires a restart of Emacs to take effect."
3377 :group 'org-font-lock
3378 :type 'boolean)
3380 (defvar org-emph-re nil
3381 "Regular expression for matching emphasis.")
3382 (defvar org-emphasis-regexp-components) ; defined just below
3383 (defvar org-emphasis-alist) ; defined just below
3384 (defun org-set-emph-re (var val)
3385 "Set variable and compute the emphasis regular expression."
3386 (set var val)
3387 (when (and (boundp 'org-emphasis-alist)
3388 (boundp 'org-emphasis-regexp-components)
3389 org-emphasis-alist org-emphasis-regexp-components)
3390 (let* ((e org-emphasis-regexp-components)
3391 (pre (car e))
3392 (post (nth 1 e))
3393 (border (nth 2 e))
3394 (body (nth 3 e))
3395 (nl (nth 4 e))
3396 (stacked (nth 5 e))
3397 (body1 (concat body "*?"))
3398 (markers (mapconcat 'car org-emphasis-alist "")))
3399 ;; make sure special characters appear at the right position in the class
3400 (if (string-match "\\^" markers)
3401 (setq markers (concat (replace-match "" t t markers) "^")))
3402 (if (string-match "-" markers)
3403 (setq markers (concat (replace-match "" t t markers) "-")))
3404 (if (> nl 0)
3405 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3406 (int-to-string nl) "\\}")))
3407 ;; Make the regexp
3408 (setq org-emph-re
3409 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
3410 "\\("
3411 "\\([" markers "]\\)"
3412 "\\("
3413 "[^" border (if (and nil stacked) markers) "]"
3414 body1
3415 "[^" border (if (and nil stacked) markers) "]"
3416 "\\)"
3417 "\\3\\)"
3418 "\\([" post (if stacked markers) "]\\|$\\)")))))
3420 (defcustom org-emphasis-regexp-components
3421 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1 nil)
3422 "Components used to build the reqular expression for emphasis.
3423 This is a list with 6 entries. Terminology: In an emphasis string
3424 like \" *strong word* \", we call the initial space PREMATCH, the final
3425 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3426 and \"trong wor\" is the body. The different components in this variable
3427 specify what is allowed/forbidden in each part:
3429 pre Chars allowed as prematch. Beginning of line will be allowed too.
3430 post Chars allowed as postmatch. End of line will be allowed too.
3431 border The chars *forbidden* as border characters.
3432 body-regexp A regexp like \".\" to match a body character. Don't use
3433 non-shy groups here, and don't allow newline here.
3434 newline The maximum number of newlines allowed in an emphasis exp.
3435 stacked Non-nil means, allow stacked styles. This works only in HTML
3436 export. When this is set, all marker characters (as given in
3437 `org-emphasis-alist') will be allowed as pre/post, aiding
3438 inside-out matching.
3439 Use customize to modify this, or restart Emacs after changing it."
3440 :group 'org-font-lock
3441 :set 'org-set-emph-re
3442 :type '(list
3443 (sexp :tag "Allowed chars in pre ")
3444 (sexp :tag "Allowed chars in post ")
3445 (sexp :tag "Forbidden chars in border ")
3446 (sexp :tag "Regexp for body ")
3447 (integer :tag "number of newlines allowed")
3448 (boolean :tag "Stacking allowed ")))
3450 (defcustom org-emphasis-alist
3451 '(("*" bold "<b>" "</b>")
3452 ("/" italic "<i>" "</i>")
3453 ("_" underline "<u>" "</u>")
3454 ("=" org-code "<code>" "</code>")
3455 ("+" (:strike-through t) "<del>" "</del>")
3457 "Special syntax for emphasized text.
3458 Text starting and ending with a special character will be emphasized, for
3459 example *bold*, _underlined_ and /italic/. This variable sets the marker
3460 characters, the face to be used by font-lock for highlighting in Org-mode
3461 Emacs buffers, and the HTML tags to be used for this.
3462 Use customize to modify this, or restart Emacs after changing it."
3463 :group 'org-font-lock
3464 :set 'org-set-emph-re
3465 :type '(repeat
3466 (list
3467 (string :tag "Marker character")
3468 (choice
3469 (face :tag "Font-lock-face")
3470 (plist :tag "Face property list"))
3471 (string :tag "HTML start tag")
3472 (string :tag "HTML end tag"))))
3474 ;;; The faces
3476 (defgroup org-faces nil
3477 "Faces in Org-mode."
3478 :tag "Org Faces"
3479 :group 'org-font-lock)
3481 (defun org-compatible-face (inherits specs)
3482 "Make a compatible face specification.
3483 If INHERITS is an existing face and if the Emacs version supports it,
3484 just inherit the face. If not, use SPECS to define the face.
3485 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3486 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3487 to the top of the list. The `min-colors' attribute will be removed from
3488 any other entries, and any resulting duplicates will be removed entirely."
3489 (cond
3490 ((and inherits (facep inherits)
3491 (not (featurep 'xemacs)) (> emacs-major-version 22))
3492 ;; In Emacs 23, we use inheritance where possible.
3493 ;; We only do this in Emacs 23, because only there the outline
3494 ;; faces have been changed to the original org-mode-level-faces.
3495 (list (list t :inherit inherits)))
3496 ((or (featurep 'xemacs) (< emacs-major-version 22))
3497 ;; These do not understand the `min-colors' attribute.
3498 (let (r e a)
3499 (while (setq e (pop specs))
3500 (cond
3501 ((memq (car e) '(t default)) (push e r))
3502 ((setq a (member '(min-colors 8) (car e)))
3503 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3504 (cdr e)))))
3505 ((setq a (assq 'min-colors (car e)))
3506 (setq e (cons (delq a (car e)) (cdr e)))
3507 (or (assoc (car e) r) (push e r)))
3508 (t (or (assoc (car e) r) (push e r)))))
3509 (nreverse r)))
3510 (t specs)))
3512 (defface org-hide
3513 '((((background light)) (:foreground "white"))
3514 (((background dark)) (:foreground "black")))
3515 "Face used to hide leading stars in headlines.
3516 The forground color of this face should be equal to the background
3517 color of the frame."
3518 :group 'org-faces)
3520 (defface org-level-1 ;; font-lock-function-name-face
3521 (org-compatible-face
3522 'outline-1
3523 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3524 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3525 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3526 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3527 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3528 (t (:bold t))))
3529 "Face used for level 1 headlines."
3530 :group 'org-faces)
3532 (defface org-level-2 ;; font-lock-variable-name-face
3533 (org-compatible-face
3534 'outline-2
3535 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3536 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3537 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3538 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3539 (t (:bold t))))
3540 "Face used for level 2 headlines."
3541 :group 'org-faces)
3543 (defface org-level-3 ;; font-lock-keyword-face
3544 (org-compatible-face
3545 'outline-3
3546 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3547 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3548 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3549 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3550 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3551 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3552 (t (:bold t))))
3553 "Face used for level 3 headlines."
3554 :group 'org-faces)
3556 (defface org-level-4 ;; font-lock-comment-face
3557 (org-compatible-face
3558 'outline-4
3559 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3560 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3561 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3562 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3563 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3564 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3565 (t (:bold t))))
3566 "Face used for level 4 headlines."
3567 :group 'org-faces)
3569 (defface org-level-5 ;; font-lock-type-face
3570 (org-compatible-face
3571 'outline-5
3572 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3573 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3574 (((class color) (min-colors 8)) (:foreground "green"))))
3575 "Face used for level 5 headlines."
3576 :group 'org-faces)
3578 (defface org-level-6 ;; font-lock-constant-face
3579 (org-compatible-face
3580 'outline-6
3581 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3582 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3583 (((class color) (min-colors 8)) (:foreground "magenta"))))
3584 "Face used for level 6 headlines."
3585 :group 'org-faces)
3587 (defface org-level-7 ;; font-lock-builtin-face
3588 (org-compatible-face
3589 'outline-7
3590 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3591 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3592 (((class color) (min-colors 8)) (:foreground "blue"))))
3593 "Face used for level 7 headlines."
3594 :group 'org-faces)
3596 (defface org-level-8 ;; font-lock-string-face
3597 (org-compatible-face
3598 'outline-8
3599 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3600 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3601 (((class color) (min-colors 8)) (:foreground "green"))))
3602 "Face used for level 8 headlines."
3603 :group 'org-faces)
3605 (defface org-special-keyword ;; font-lock-string-face
3606 (org-compatible-face
3608 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3609 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3610 (t (:italic t))))
3611 "Face used for special keywords."
3612 :group 'org-faces)
3614 (defface org-drawer ;; font-lock-function-name-face
3615 (org-compatible-face
3617 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3618 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3619 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3620 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3621 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3622 (t (:bold t))))
3623 "Face used for drawers."
3624 :group 'org-faces)
3626 (defface org-property-value nil
3627 "Face used for the value of a property."
3628 :group 'org-faces)
3630 (defface org-column
3631 (org-compatible-face
3633 '((((class color) (min-colors 16) (background light))
3634 (:background "grey90"))
3635 (((class color) (min-colors 16) (background dark))
3636 (:background "grey30"))
3637 (((class color) (min-colors 8))
3638 (:background "cyan" :foreground "black"))
3639 (t (:inverse-video t))))
3640 "Face for column display of entry properties."
3641 :group 'org-faces)
3643 (when (fboundp 'set-face-attribute)
3644 ;; Make sure that a fixed-width face is used when we have a column table.
3645 (set-face-attribute 'org-column nil
3646 :height (face-attribute 'default :height)
3647 :family (face-attribute 'default :family)))
3649 (defface org-warning
3650 (org-compatible-face
3651 'font-lock-warning-face
3652 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3653 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3654 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3655 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3656 (t (:bold t))))
3657 "Face for deadlines and TODO keywords."
3658 :group 'org-faces)
3660 (defface org-archived ; similar to shadow
3661 (org-compatible-face
3662 'shadow
3663 '((((class color grayscale) (min-colors 88) (background light))
3664 (:foreground "grey50"))
3665 (((class color grayscale) (min-colors 88) (background dark))
3666 (:foreground "grey70"))
3667 (((class color) (min-colors 8) (background light))
3668 (:foreground "green"))
3669 (((class color) (min-colors 8) (background dark))
3670 (:foreground "yellow"))))
3671 "Face for headline with the ARCHIVE tag."
3672 :group 'org-faces)
3674 (defface org-link
3675 '((((class color) (background light)) (:foreground "Purple" :underline t))
3676 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3677 (t (:underline t)))
3678 "Face for links."
3679 :group 'org-faces)
3681 (defface org-ellipsis
3682 '((((class color) (background light)) (:foreground "DarkGoldenrod" :strike-through t))
3683 (((class color) (background dark)) (:foreground "LightGoldenrod" :strike-through t))
3684 (t (:strike-through t)))
3685 "Face for the ellipsis in folded text."
3686 :group 'org-faces)
3688 (defface org-target
3689 '((((class color) (background light)) (:underline t))
3690 (((class color) (background dark)) (:underline t))
3691 (t (:underline t)))
3692 "Face for links."
3693 :group 'org-faces)
3695 (defface org-date
3696 '((((class color) (background light)) (:foreground "Purple" :underline t))
3697 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3698 (t (:underline t)))
3699 "Face for links."
3700 :group 'org-faces)
3702 (defface org-sexp-date
3703 '((((class color) (background light)) (:foreground "Purple"))
3704 (((class color) (background dark)) (:foreground "Cyan"))
3705 (t (:underline t)))
3706 "Face for links."
3707 :group 'org-faces)
3709 (defface org-tag
3710 '((t (:bold t)))
3711 "Face for tags."
3712 :group 'org-faces)
3714 (defface org-todo ; font-lock-warning-face
3715 (org-compatible-face
3717 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3718 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3719 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3720 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3721 (t (:inverse-video t :bold t))))
3722 "Face for TODO keywords."
3723 :group 'org-faces)
3725 (defface org-done ;; font-lock-type-face
3726 (org-compatible-face
3728 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3729 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3730 (((class color) (min-colors 8)) (:foreground "green"))
3731 (t (:bold t))))
3732 "Face used for todo keywords that indicate DONE items."
3733 :group 'org-faces)
3735 (defface org-headline-done ;; font-lock-string-face
3736 (org-compatible-face
3738 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3739 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3740 (((class color) (min-colors 8) (background light)) (:bold nil))))
3741 "Face used to indicate that a headline is DONE.
3742 This face is only used if `org-fontify-done-headline' is set. If applies
3743 to the part of the headline after the DONE keyword."
3744 :group 'org-faces)
3746 (defcustom org-todo-keyword-faces nil
3747 "Faces for specific TODO keywords.
3748 This is a list of cons cells, with TODO keywords in the car
3749 and faces in the cdr. The face can be a symbol, or a property
3750 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3751 :group 'org-faces
3752 :group 'org-todo
3753 :type '(repeat
3754 (cons
3755 (string :tag "keyword")
3756 (sexp :tag "face"))))
3758 (defface org-table ;; font-lock-function-name-face
3759 (org-compatible-face
3761 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3762 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3763 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3764 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3765 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3766 (((class color) (min-colors 8) (background dark)))))
3767 "Face used for tables."
3768 :group 'org-faces)
3770 (defface org-formula
3771 (org-compatible-face
3773 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3774 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3775 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3776 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3777 (t (:bold t :italic t))))
3778 "Face for formulas."
3779 :group 'org-faces)
3781 (defface org-code
3782 (org-compatible-face
3784 '((((class color grayscale) (min-colors 88) (background light))
3785 (:foreground "grey50"))
3786 (((class color grayscale) (min-colors 88) (background dark))
3787 (:foreground "grey70"))
3788 (((class color) (min-colors 8) (background light))
3789 (:foreground "green"))
3790 (((class color) (min-colors 8) (background dark))
3791 (:foreground "yellow"))))
3792 "Face for fixed-with text like code snippets."
3793 :group 'org-faces
3794 :version "22.1")
3796 (defface org-agenda-structure ;; font-lock-function-name-face
3797 (org-compatible-face
3799 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3800 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3801 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3802 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3803 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3804 (t (:bold t))))
3805 "Face used in agenda for captions and dates."
3806 :group 'org-faces)
3808 (defface org-scheduled-today
3809 (org-compatible-face
3811 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3812 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3813 (((class color) (min-colors 8)) (:foreground "green"))
3814 (t (:bold t :italic t))))
3815 "Face for items scheduled for a certain day."
3816 :group 'org-faces)
3818 (defface org-scheduled-previously
3819 (org-compatible-face
3821 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3822 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3823 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3824 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3825 (t (:bold t))))
3826 "Face for items scheduled previously, and not yet done."
3827 :group 'org-faces)
3829 (defface org-upcoming-deadline
3830 (org-compatible-face
3832 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3833 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3834 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3835 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3836 (t (:bold t))))
3837 "Face for items scheduled previously, and not yet done."
3838 :group 'org-faces)
3840 (defcustom org-agenda-deadline-faces
3841 '((1.0 . org-warning)
3842 (0.5 . org-upcoming-deadline)
3843 (0.0 . default))
3844 "Faces for showing deadlines in the agenda.
3845 This is a list of cons cells. The cdr of each cess is a face to be used,
3846 and it can also just be a like like '(:foreground \"yellow\").
3847 Each car is a fraction of the head-warning time that must have passed for
3848 this the face in the cdr to be used for display. The numbers must be
3849 given in descending order. The head-warning time is normally taken
3850 from `org-deadline-warning-days', but can also be specified in the deadline
3851 timestamp itself, like this:
3853 DEADLINE: <2007-08-13 Mon -8d>
3855 You may use d for days, w for weeks, m for months and y for years. Months
3856 and years will only be treated in an approximate fashion (30.4 days for a
3857 month and 365.24 days for a year)."
3858 :group 'org-faces
3859 :group 'org-agenda-daily/weekly
3860 :type '(repeat
3861 (cons
3862 (number :tag "Fraction of head-warning time passed")
3863 (sexp :tag "Face"))))
3865 (defface org-time-grid ;; font-lock-variable-name-face
3866 (org-compatible-face
3868 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3869 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3870 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
3871 "Face used for time grids."
3872 :group 'org-faces)
3874 (defconst org-level-faces
3875 '(org-level-1 org-level-2 org-level-3 org-level-4
3876 org-level-5 org-level-6 org-level-7 org-level-8
3879 (defcustom org-n-level-faces (length org-level-faces)
3880 "The number different faces to be used for headlines.
3881 Org-mode defines 8 different headline faces, so this can be at most 8.
3882 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
3883 :type 'number
3884 :group 'org-faces)
3886 ;;; Variables for pre-computed regular expressions, all buffer local
3888 (defvar org-drawer-regexp nil
3889 "Matches first line of a hidden block.")
3890 (make-variable-buffer-local 'org-drawer-regexp)
3891 (defvar org-todo-regexp nil
3892 "Matches any of the TODO state keywords.")
3893 (make-variable-buffer-local 'org-todo-regexp)
3894 (defvar org-not-done-regexp nil
3895 "Matches any of the TODO state keywords except the last one.")
3896 (make-variable-buffer-local 'org-not-done-regexp)
3897 (defvar org-todo-line-regexp nil
3898 "Matches a headline and puts TODO state into group 2 if present.")
3899 (make-variable-buffer-local 'org-todo-line-regexp)
3900 (defvar org-complex-heading-regexp nil
3901 "Matches a headline and puts everything into groups:
3902 group 1: the stars
3903 group 2: The todo keyword, maybe
3904 group 3: Priority cookie
3905 group 4: True headline
3906 group 5: Tags")
3907 (make-variable-buffer-local 'org-complex-heading-regexp)
3908 (defvar org-todo-line-tags-regexp nil
3909 "Matches a headline and puts TODO state into group 2 if present.
3910 Also put tags into group 4 if tags are present.")
3911 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3912 (defvar org-nl-done-regexp nil
3913 "Matches newline followed by a headline with the DONE keyword.")
3914 (make-variable-buffer-local 'org-nl-done-regexp)
3915 (defvar org-looking-at-done-regexp nil
3916 "Matches the DONE keyword a point.")
3917 (make-variable-buffer-local 'org-looking-at-done-regexp)
3918 (defvar org-ds-keyword-length 12
3919 "Maximum length of the Deadline and SCHEDULED keywords.")
3920 (make-variable-buffer-local 'org-ds-keyword-length)
3921 (defvar org-deadline-regexp nil
3922 "Matches the DEADLINE keyword.")
3923 (make-variable-buffer-local 'org-deadline-regexp)
3924 (defvar org-deadline-time-regexp nil
3925 "Matches the DEADLINE keyword together with a time stamp.")
3926 (make-variable-buffer-local 'org-deadline-time-regexp)
3927 (defvar org-deadline-line-regexp nil
3928 "Matches the DEADLINE keyword and the rest of the line.")
3929 (make-variable-buffer-local 'org-deadline-line-regexp)
3930 (defvar org-scheduled-regexp nil
3931 "Matches the SCHEDULED keyword.")
3932 (make-variable-buffer-local 'org-scheduled-regexp)
3933 (defvar org-scheduled-time-regexp nil
3934 "Matches the SCHEDULED keyword together with a time stamp.")
3935 (make-variable-buffer-local 'org-scheduled-time-regexp)
3936 (defvar org-closed-time-regexp nil
3937 "Matches the CLOSED keyword together with a time stamp.")
3938 (make-variable-buffer-local 'org-closed-time-regexp)
3940 (defvar org-keyword-time-regexp nil
3941 "Matches any of the 4 keywords, together with the time stamp.")
3942 (make-variable-buffer-local 'org-keyword-time-regexp)
3943 (defvar org-keyword-time-not-clock-regexp nil
3944 "Matches any of the 3 keywords, together with the time stamp.")
3945 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3946 (defvar org-maybe-keyword-time-regexp nil
3947 "Matches a timestamp, possibly preceeded by a keyword.")
3948 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3949 (defvar org-planning-or-clock-line-re nil
3950 "Matches a line with planning or clock info.")
3951 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3953 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
3954 rear-nonsticky t mouse-map t fontified t)
3955 "Properties to remove when a string without properties is wanted.")
3957 (defsubst org-match-string-no-properties (num &optional string)
3958 (if (featurep 'xemacs)
3959 (let ((s (match-string num string)))
3960 (remove-text-properties 0 (length s) org-rm-props s)
3962 (match-string-no-properties num string)))
3964 (defsubst org-no-properties (s)
3965 (if (fboundp 'set-text-properties)
3966 (set-text-properties 0 (length s) nil s)
3967 (remove-text-properties 0 (length s) org-rm-props s))
3970 (defsubst org-get-alist-option (option key)
3971 (cond ((eq key t) t)
3972 ((eq option t) t)
3973 ((assoc key option) (cdr (assoc key option)))
3974 (t (cdr (assq 'default option)))))
3976 (defsubst org-inhibit-invisibility ()
3977 "Modified `buffer-invisibility-spec' for Emacs 21.
3978 Some ops with invisible text do not work correctly on Emacs 21. For these
3979 we turn off invisibility temporarily. Use this in a `let' form."
3980 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
3982 (defsubst org-set-local (var value)
3983 "Make VAR local in current buffer and set it to VALUE."
3984 (set (make-variable-buffer-local var) value))
3986 (defsubst org-mode-p ()
3987 "Check if the current buffer is in Org-mode."
3988 (eq major-mode 'org-mode))
3990 (defsubst org-last (list)
3991 "Return the last element of LIST."
3992 (car (last list)))
3994 (defun org-let (list &rest body)
3995 (eval (cons 'let (cons list body))))
3996 (put 'org-let 'lisp-indent-function 1)
3998 (defun org-let2 (list1 list2 &rest body)
3999 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4000 (put 'org-let2 'lisp-indent-function 2)
4001 (defconst org-startup-options
4002 '(("fold" org-startup-folded t)
4003 ("overview" org-startup-folded t)
4004 ("nofold" org-startup-folded nil)
4005 ("showall" org-startup-folded nil)
4006 ("content" org-startup-folded content)
4007 ("hidestars" org-hide-leading-stars t)
4008 ("showstars" org-hide-leading-stars nil)
4009 ("odd" org-odd-levels-only t)
4010 ("oddeven" org-odd-levels-only nil)
4011 ("align" org-startup-align-all-tables t)
4012 ("noalign" org-startup-align-all-tables nil)
4013 ("customtime" org-display-custom-times t)
4014 ("logging" org-log-done t)
4015 ("logdone" org-log-done t)
4016 ("nologging" org-log-done nil)
4017 ("lognotedone" org-log-done done push)
4018 ("lognotestate" org-log-done state push)
4019 ("lognoteclock-out" org-log-done clock-out push)
4020 ("logrepeat" org-log-repeat t)
4021 ("nologrepeat" org-log-repeat nil)
4022 ("constcgs" constants-unit-system cgs)
4023 ("constSI" constants-unit-system SI))
4024 "Variable associated with STARTUP options for org-mode.
4025 Each element is a list of three items: The startup options as written
4026 in the #+STARTUP line, the corresponding variable, and the value to
4027 set this variable to if the option is found. An optional forth element PUSH
4028 means to push this value onto the list in the variable.")
4030 (defun org-set-regexps-and-options ()
4031 "Precompute regular expressions for current buffer."
4032 (when (org-mode-p)
4033 (org-set-local 'org-todo-kwd-alist nil)
4034 (org-set-local 'org-todo-key-alist nil)
4035 (org-set-local 'org-todo-key-trigger nil)
4036 (org-set-local 'org-todo-keywords-1 nil)
4037 (org-set-local 'org-done-keywords nil)
4038 (org-set-local 'org-todo-heads nil)
4039 (org-set-local 'org-todo-sets nil)
4040 (org-set-local 'org-todo-log-states nil)
4041 (let ((re (org-make-options-regexp
4042 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4043 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4044 "CONSTANTS" "PROPERTY" "DRAWERS")))
4045 (splitre "[ \t]+")
4046 kwds kws0 kwsa key value cat arch tags const links hw dws
4047 tail sep kws1 prio props drawers
4048 ex log)
4049 (save-excursion
4050 (save-restriction
4051 (widen)
4052 (goto-char (point-min))
4053 (while (re-search-forward re nil t)
4054 (setq key (match-string 1) value (org-match-string-no-properties 2))
4055 (cond
4056 ((equal key "CATEGORY")
4057 (if (string-match "[ \t]+$" value)
4058 (setq value (replace-match "" t t value)))
4059 (setq cat (intern value)))
4060 ((member key '("SEQ_TODO" "TODO"))
4061 (push (cons 'sequence (org-split-string value splitre)) kwds))
4062 ((equal key "TYP_TODO")
4063 (push (cons 'type (org-split-string value splitre)) kwds))
4064 ((equal key "TAGS")
4065 (setq tags (append tags (org-split-string value splitre))))
4066 ((equal key "COLUMNS")
4067 (org-set-local 'org-columns-default-format value))
4068 ((equal key "LINK")
4069 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4070 (push (cons (match-string 1 value)
4071 (org-trim (match-string 2 value)))
4072 links)))
4073 ((equal key "PRIORITIES")
4074 (setq prio (org-split-string value " +")))
4075 ((equal key "PROPERTY")
4076 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4077 (push (cons (match-string 1 value) (match-string 2 value))
4078 props)))
4079 ((equal key "DRAWERS")
4080 (setq drawers (org-split-string value splitre)))
4081 ((equal key "CONSTANTS")
4082 (setq const (append const (org-split-string value splitre))))
4083 ((equal key "STARTUP")
4084 (let ((opts (org-split-string value splitre))
4085 l var val)
4086 (while (setq l (pop opts))
4087 (when (setq l (assoc l org-startup-options))
4088 (setq var (nth 1 l) val (nth 2 l))
4089 (if (not (nth 3 l))
4090 (set (make-local-variable var) val)
4091 (if (not (listp (symbol-value var)))
4092 (set (make-local-variable var) nil))
4093 (set (make-local-variable var) (symbol-value var))
4094 (add-to-list var val))))))
4095 ((equal key "ARCHIVE")
4096 (string-match " *$" value)
4097 (setq arch (replace-match "" t t value))
4098 (remove-text-properties 0 (length arch)
4099 '(face t fontified t) arch)))
4101 (and cat (org-set-local 'org-category cat))
4102 (when prio
4103 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4104 (setq prio (mapcar 'string-to-char prio))
4105 (org-set-local 'org-highest-priority (nth 0 prio))
4106 (org-set-local 'org-lowest-priority (nth 1 prio))
4107 (org-set-local 'org-default-priority (nth 2 prio)))
4108 (and props (org-set-local 'org-local-properties (nreverse props)))
4109 (and drawers (org-set-local 'org-drawers drawers))
4110 (and arch (org-set-local 'org-archive-location arch))
4111 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4112 ;; Process the TODO keywords
4113 (unless kwds
4114 ;; Use the global values as if they had been given locally.
4115 (setq kwds (default-value 'org-todo-keywords))
4116 (if (stringp (car kwds))
4117 (setq kwds (list (cons org-todo-interpretation
4118 (default-value 'org-todo-keywords)))))
4119 (setq kwds (reverse kwds)))
4120 (setq kwds (nreverse kwds))
4121 (let (inter kws kw)
4122 (while (setq kws (pop kwds))
4123 (setq inter (pop kws) sep (member "|" kws)
4124 kws0 (delete "|" (copy-sequence kws))
4125 kwsa nil
4126 kws1 (mapcar
4127 (lambda (x)
4128 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4129 (progn
4130 (setq kw (match-string 1 x)
4131 ex (and (match-end 2) (match-string 2 x))
4132 log (and ex (string-match "@" ex))
4133 key (and ex (substring ex 0 1)))
4134 (if (equal key "@") (setq key nil))
4135 (push (cons kw (and key (string-to-char key))) kwsa)
4136 (and log (push kw org-todo-log-states))
4138 (error "Invalid TODO keyword %s" x)))
4139 kws0)
4140 kwsa (if kwsa (append '((:startgroup))
4141 (nreverse kwsa)
4142 '((:endgroup))))
4143 hw (car kws1)
4144 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4145 tail (list inter hw (car dws) (org-last dws)))
4146 (add-to-list 'org-todo-heads hw 'append)
4147 (push kws1 org-todo-sets)
4148 (setq org-done-keywords (append org-done-keywords dws nil))
4149 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4150 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4151 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4152 (setq org-todo-sets (nreverse org-todo-sets)
4153 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4154 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4155 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4156 ;; Process the constants
4157 (when const
4158 (let (e cst)
4159 (while (setq e (pop const))
4160 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4161 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4162 (setq org-table-formula-constants-local cst)))
4164 ;; Process the tags.
4165 (when tags
4166 (let (e tgs)
4167 (while (setq e (pop tags))
4168 (cond
4169 ((equal e "{") (push '(:startgroup) tgs))
4170 ((equal e "}") (push '(:endgroup) tgs))
4171 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4172 (push (cons (match-string 1 e)
4173 (string-to-char (match-string 2 e)))
4174 tgs))
4175 (t (push (list e) tgs))))
4176 (org-set-local 'org-tag-alist nil)
4177 (while (setq e (pop tgs))
4178 (or (and (stringp (car e))
4179 (assoc (car e) org-tag-alist))
4180 (push e org-tag-alist))))))
4182 ;; Compute the regular expressions and other local variables
4183 (if (not org-done-keywords)
4184 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4185 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4186 (length org-scheduled-string)))
4187 org-drawer-regexp
4188 (concat "^[ \t]*:\\("
4189 (mapconcat 'regexp-quote org-drawers "\\|")
4190 "\\):[ \t]*$")
4191 org-not-done-keywords
4192 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4193 org-todo-regexp
4194 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4195 "\\|") "\\)\\>")
4196 org-not-done-regexp
4197 (concat "\\<\\("
4198 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4199 "\\)\\>")
4200 org-todo-line-regexp
4201 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4202 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4203 "\\)\\>\\)?[ \t]*\\(.*\\)")
4204 org-complex-heading-regexp
4205 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4206 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4207 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4208 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4209 org-nl-done-regexp
4210 (concat "\n\\*+[ \t]+"
4211 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4212 "\\)" "\\>")
4213 org-todo-line-tags-regexp
4214 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4215 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4216 (org-re
4217 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4218 org-looking-at-done-regexp
4219 (concat "^" "\\(?:"
4220 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4221 "\\>")
4222 org-deadline-regexp (concat "\\<" org-deadline-string)
4223 org-deadline-time-regexp
4224 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4225 org-deadline-line-regexp
4226 (concat "\\<\\(" org-deadline-string "\\).*")
4227 org-scheduled-regexp
4228 (concat "\\<" org-scheduled-string)
4229 org-scheduled-time-regexp
4230 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4231 org-closed-time-regexp
4232 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4233 org-keyword-time-regexp
4234 (concat "\\<\\(" org-scheduled-string
4235 "\\|" org-deadline-string
4236 "\\|" org-closed-string
4237 "\\|" org-clock-string "\\)"
4238 " *[[<]\\([^]>]+\\)[]>]")
4239 org-keyword-time-not-clock-regexp
4240 (concat "\\<\\(" org-scheduled-string
4241 "\\|" org-deadline-string
4242 "\\|" org-closed-string
4243 "\\)"
4244 " *[[<]\\([^]>]+\\)[]>]")
4245 org-maybe-keyword-time-regexp
4246 (concat "\\(\\<\\(" org-scheduled-string
4247 "\\|" org-deadline-string
4248 "\\|" org-closed-string
4249 "\\|" org-clock-string "\\)\\)?"
4250 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4251 org-planning-or-clock-line-re
4252 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4253 "\\|" org-deadline-string
4254 "\\|" org-closed-string "\\|" org-clock-string
4255 "\\)\\>\\)")
4258 (org-set-font-lock-defaults)))
4260 (defun org-remove-keyword-keys (list)
4261 (mapcar (lambda (x)
4262 (if (string-match "(..?)$" x)
4263 (substring x 0 (match-beginning 0))
4265 list))
4267 ;;; Some variables ujsed in various places
4269 (defvar org-window-configuration nil
4270 "Used in various places to store a window configuration.")
4271 (defvar org-finish-function nil
4272 "Function to be called when `C-c C-c' is used.
4273 This is for getting out of special buffers like remember.")
4275 ;;; Foreign variables, to inform the compiler
4277 ;; XEmacs only
4278 (defvar outline-mode-menu-heading)
4279 (defvar outline-mode-menu-show)
4280 (defvar outline-mode-menu-hide)
4281 (defvar zmacs-regions) ; XEmacs regions
4282 ;; Emacs only
4283 (defvar mark-active)
4285 ;; Packages that org-mode interacts with
4286 (defvar calc-embedded-close-formula)
4287 (defvar calc-embedded-open-formula)
4288 (defvar font-lock-unfontify-region-function)
4289 (defvar org-goto-start-pos)
4290 (defvar vm-message-pointer)
4291 (defvar vm-folder-directory)
4292 (defvar wl-summary-buffer-elmo-folder)
4293 (defvar wl-summary-buffer-folder-name)
4294 (defvar gnus-other-frame-object)
4295 (defvar gnus-group-name)
4296 (defvar gnus-article-current)
4297 (defvar w3m-current-url)
4298 (defvar w3m-current-title)
4299 (defvar mh-progs)
4300 (defvar mh-current-folder)
4301 (defvar mh-show-folder-buffer)
4302 (defvar mh-index-folder)
4303 (defvar mh-searcher)
4304 (defvar calendar-mode-map)
4305 (defvar Info-current-file)
4306 (defvar Info-current-node)
4307 (defvar texmathp-why)
4308 (defvar remember-save-after-remembering)
4309 (defvar remember-data-file)
4310 (defvar remember-register)
4311 (defvar remember-buffer)
4312 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4313 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4314 (defvar org-latex-regexps)
4315 (defvar constants-unit-system)
4317 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4319 ;; FIXME: Occasionally check by commenting these, to make sure
4320 ;; no other functions uses these, forgetting to let-bind them.
4321 (defvar entry)
4322 (defvar state)
4323 (defvar last-state)
4324 (defvar date)
4325 (defvar description)
4328 ;; Defined somewhere in this file, but used before definition.
4329 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4330 (defvar org-agenda-buffer-name)
4331 (defvar org-agenda-undo-list)
4332 (defvar org-agenda-pending-undo-list)
4333 (defvar org-agenda-overriding-header)
4334 (defvar orgtbl-mode)
4335 (defvar org-html-entities)
4336 (defvar org-struct-menu)
4337 (defvar org-org-menu)
4338 (defvar org-tbl-menu)
4339 (defvar org-agenda-keymap)
4341 ;;;; Emacs/XEmacs compatibility
4343 ;; Overlay compatibility functions
4344 (defun org-make-overlay (beg end &optional buffer)
4345 (if (featurep 'xemacs)
4346 (make-extent beg end buffer)
4347 (make-overlay beg end buffer)))
4348 (defun org-delete-overlay (ovl)
4349 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4350 (defun org-detach-overlay (ovl)
4351 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4352 (defun org-move-overlay (ovl beg end &optional buffer)
4353 (if (featurep 'xemacs)
4354 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4355 (move-overlay ovl beg end buffer)))
4356 (defun org-overlay-put (ovl prop value)
4357 (if (featurep 'xemacs)
4358 (set-extent-property ovl prop value)
4359 (overlay-put ovl prop value)))
4360 (defun org-overlay-display (ovl text &optional face evap)
4361 "Make overlay OVL display TEXT with face FACE."
4362 (if (featurep 'xemacs)
4363 (let ((gl (make-glyph text)))
4364 (and face (set-glyph-face gl face))
4365 (set-extent-property ovl 'invisible t)
4366 (set-extent-property ovl 'end-glyph gl))
4367 (overlay-put ovl 'display text)
4368 (if face (overlay-put ovl 'face face))
4369 (if evap (overlay-put ovl 'evaporate t))))
4370 (defun org-overlay-before-string (ovl text &optional face evap)
4371 "Make overlay OVL display TEXT with face FACE."
4372 (if (featurep 'xemacs)
4373 (let ((gl (make-glyph text)))
4374 (and face (set-glyph-face gl face))
4375 (set-extent-property ovl 'begin-glyph gl))
4376 (if face (org-add-props text nil 'face face))
4377 (overlay-put ovl 'before-string text)
4378 (if evap (overlay-put ovl 'evaporate t))))
4379 (defun org-overlay-get (ovl prop)
4380 (if (featurep 'xemacs)
4381 (extent-property ovl prop)
4382 (overlay-get ovl prop)))
4383 (defun org-overlays-at (pos)
4384 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4385 (defun org-overlays-in (&optional start end)
4386 (if (featurep 'xemacs)
4387 (extent-list nil start end)
4388 (overlays-in start end)))
4389 (defun org-overlay-start (o)
4390 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4391 (defun org-overlay-end (o)
4392 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4393 (defun org-find-overlays (prop &optional pos delete)
4394 "Find all overlays specifying PROP at POS or point.
4395 If DELETE is non-nil, delete all those overlays."
4396 (let ((overlays (org-overlays-at (or pos (point))))
4397 ov found)
4398 (while (setq ov (pop overlays))
4399 (if (org-overlay-get ov prop)
4400 (if delete (org-delete-overlay ov) (push ov found))))
4401 found))
4403 ;; Region compatibility
4405 (defun org-add-hook (hook function &optional append local)
4406 "Add-hook, compatible with both Emacsen."
4407 (if (and local (featurep 'xemacs))
4408 (add-local-hook hook function append)
4409 (add-hook hook function append local)))
4411 (defvar org-ignore-region nil
4412 "To temporarily disable the active region.")
4414 (defun org-region-active-p ()
4415 "Is `transient-mark-mode' on and the region active?
4416 Works on both Emacs and XEmacs."
4417 (if org-ignore-region
4419 (if (featurep 'xemacs)
4420 (and zmacs-regions (region-active-p))
4421 (and transient-mark-mode mark-active))))
4423 ;; Invisibility compatibility
4425 (defun org-add-to-invisibility-spec (arg)
4426 "Add elements to `buffer-invisibility-spec'.
4427 See documentation for `buffer-invisibility-spec' for the kind of elements
4428 that can be added."
4429 (cond
4430 ((fboundp 'add-to-invisibility-spec)
4431 (add-to-invisibility-spec arg))
4432 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4433 (setq buffer-invisibility-spec (list arg)))
4435 (setq buffer-invisibility-spec
4436 (cons arg buffer-invisibility-spec)))))
4438 (defun org-remove-from-invisibility-spec (arg)
4439 "Remove elements from `buffer-invisibility-spec'."
4440 (if (fboundp 'remove-from-invisibility-spec)
4441 (remove-from-invisibility-spec arg)
4442 (if (consp buffer-invisibility-spec)
4443 (setq buffer-invisibility-spec
4444 (delete arg buffer-invisibility-spec)))))
4446 (defun org-in-invisibility-spec-p (arg)
4447 "Is ARG a member of `buffer-invisibility-spec'?"
4448 (if (consp buffer-invisibility-spec)
4449 (member arg buffer-invisibility-spec)
4450 nil))
4452 ;;;; Define the Org-mode
4454 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4455 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
4458 ;; We use a before-change function to check if a table might need
4459 ;; an update.
4460 (defvar org-table-may-need-update t
4461 "Indicates that a table might need an update.
4462 This variable is set by `org-before-change-function'.
4463 `org-table-align' sets it back to nil.")
4464 (defvar org-mode-map)
4465 (defvar org-mode-hook nil)
4466 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4467 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4468 (defvar org-table-buffer-is-an nil)
4469 (defconst org-outline-regexp "\\*+ ")
4471 ;;;###autoload
4472 (define-derived-mode org-mode outline-mode "Org"
4473 "Outline-based notes management and organizer, alias
4474 \"Carsten's outline-mode for keeping track of everything.\"
4476 Org-mode develops organizational tasks around a NOTES file which
4477 contains information about projects as plain text. Org-mode is
4478 implemented on top of outline-mode, which is ideal to keep the content
4479 of large files well structured. It supports ToDo items, deadlines and
4480 time stamps, which magically appear in the diary listing of the Emacs
4481 calendar. Tables are easily created with a built-in table editor.
4482 Plain text URL-like links connect to websites, emails (VM), Usenet
4483 messages (Gnus), BBDB entries, and any files related to the project.
4484 For printing and sharing of notes, an Org-mode file (or a part of it)
4485 can be exported as a structured ASCII or HTML file.
4487 The following commands are available:
4489 \\{org-mode-map}"
4491 ;; Get rid of Outline menus, they are not needed
4492 ;; Need to do this here because define-derived-mode sets up
4493 ;; the keymap so late. Still, it is a waste to call this each time
4494 ;; we switch another buffer into org-mode.
4495 (if (featurep 'xemacs)
4496 (when (boundp 'outline-mode-menu-heading)
4497 ;; Assume this is Greg's port, it used easymenu
4498 (easy-menu-remove outline-mode-menu-heading)
4499 (easy-menu-remove outline-mode-menu-show)
4500 (easy-menu-remove outline-mode-menu-hide))
4501 (define-key org-mode-map [menu-bar headings] 'undefined)
4502 (define-key org-mode-map [menu-bar hide] 'undefined)
4503 (define-key org-mode-map [menu-bar show] 'undefined))
4505 (easy-menu-add org-org-menu)
4506 (easy-menu-add org-tbl-menu)
4507 (org-install-agenda-files-menu)
4508 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4509 (org-add-to-invisibility-spec '(org-cwidth))
4510 (when (featurep 'xemacs)
4511 (org-set-local 'line-move-ignore-invisible t))
4512 (org-set-local 'outline-regexp org-outline-regexp)
4513 (org-set-local 'outline-level 'org-outline-level)
4514 (when (and org-ellipsis
4515 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4516 (fboundp 'make-glyph-code))
4517 (unless org-display-table
4518 (setq org-display-table (make-display-table)))
4519 (set-display-table-slot
4520 org-display-table 4
4521 (vconcat (mapcar
4522 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4523 org-ellipsis)))
4524 (if (stringp org-ellipsis) org-ellipsis "..."))))
4525 (setq buffer-display-table org-display-table))
4526 (org-set-regexps-and-options)
4527 ;; Calc embedded
4528 (org-set-local 'calc-embedded-open-mode "# ")
4529 (modify-syntax-entry ?# "<")
4530 (modify-syntax-entry ?@ "w")
4531 (if org-startup-truncated (setq truncate-lines t))
4532 (org-set-local 'font-lock-unfontify-region-function
4533 'org-unfontify-region)
4534 ;; Activate before-change-function
4535 (org-set-local 'org-table-may-need-update t)
4536 (org-add-hook 'before-change-functions 'org-before-change-function nil
4537 'local)
4538 ;; Check for running clock before killing a buffer
4539 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4540 ;; Paragraphs and auto-filling
4541 (org-set-autofill-regexps)
4542 (setq indent-line-function 'org-indent-line-function)
4543 (org-update-radio-target-regexp)
4545 ;; Comment characters
4546 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4547 (org-set-local 'comment-padding " ")
4549 ;; Make isearch reveal context
4550 (if (or (featurep 'xemacs)
4551 (not (boundp 'outline-isearch-open-invisible-function)))
4552 ;; Emacs 21 and XEmacs make use of the hook
4553 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4554 ;; Emacs 22 deals with this through a special variable
4555 (org-set-local 'outline-isearch-open-invisible-function
4556 (lambda (&rest ignore) (org-show-context 'isearch))))
4558 ;; If empty file that did not turn on org-mode automatically, make it to.
4559 (if (and org-insert-mode-line-in-empty-file
4560 (interactive-p)
4561 (= (point-min) (point-max)))
4562 (insert "# -*- mode: org -*-\n\n"))
4564 (unless org-inhibit-startup
4565 (when org-startup-align-all-tables
4566 (let ((bmp (buffer-modified-p)))
4567 (org-table-map-tables 'org-table-align)
4568 (set-buffer-modified-p bmp)))
4569 (org-cycle-hide-drawers 'all)
4570 (cond
4571 ((eq org-startup-folded t)
4572 (org-cycle '(4)))
4573 ((eq org-startup-folded 'content)
4574 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4575 (org-cycle '(4)) (org-cycle '(4)))))))
4577 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4579 (defsubst org-call-with-arg (command arg)
4580 "Call COMMAND interactively, but pretend prefix are was ARG."
4581 (let ((current-prefix-arg arg)) (call-interactively command)))
4583 (defsubst org-current-line (&optional pos)
4584 (save-excursion
4585 (and pos (goto-char pos))
4586 ;; works also in narrowed buffer, because we start at 1, not point-min
4587 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4589 (defun org-current-time ()
4590 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4591 (if (> org-time-stamp-rounding-minutes 0)
4592 (let ((r org-time-stamp-rounding-minutes)
4593 (time (decode-time)))
4594 (apply 'encode-time
4595 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4596 (nthcdr 2 time))))
4597 (current-time)))
4599 (defun org-add-props (string plist &rest props)
4600 "Add text properties to entire string, from beginning to end.
4601 PLIST may be a list of properties, PROPS are individual properties and values
4602 that will be added to PLIST. Returns the string that was modified."
4603 (add-text-properties
4604 0 (length string) (if props (append plist props) plist) string)
4605 string)
4606 (put 'org-add-props 'lisp-indent-function 2)
4609 ;;;; Font-Lock stuff, including the activators
4611 (defvar org-mouse-map (make-sparse-keymap))
4612 (org-defkey org-mouse-map
4613 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4614 (org-defkey org-mouse-map
4615 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4616 (when org-mouse-1-follows-link
4617 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4618 (when org-tab-follows-link
4619 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4620 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4621 (when org-return-follows-link
4622 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4623 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4625 (require 'font-lock)
4627 (defconst org-non-link-chars "]\t\n\r<>")
4628 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4629 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4630 (defvar org-link-re-with-space nil
4631 "Matches a link with spaces, optional angular brackets around it.")
4632 (defvar org-link-re-with-space2 nil
4633 "Matches a link with spaces, optional angular brackets around it.")
4634 (defvar org-angle-link-re nil
4635 "Matches link with angular brackets, spaces are allowed.")
4636 (defvar org-plain-link-re nil
4637 "Matches plain link, without spaces.")
4638 (defvar org-bracket-link-regexp nil
4639 "Matches a link in double brackets.")
4640 (defvar org-bracket-link-analytic-regexp nil
4641 "Regular expression used to analyze links.
4642 Here is what the match groups contain after a match:
4643 1: http:
4644 2: http
4645 3: path
4646 4: [desc]
4647 5: desc")
4648 (defvar org-any-link-re nil
4649 "Regular expression matching any link.")
4651 (defun org-make-link-regexps ()
4652 "Update the link regular expressions.
4653 This should be called after the variable `org-link-types' has changed."
4654 (setq org-link-re-with-space
4655 (concat
4656 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4657 "\\([^" org-non-link-chars " ]"
4658 "[^" org-non-link-chars "]*"
4659 "[^" org-non-link-chars " ]\\)>?")
4660 org-link-re-with-space2
4661 (concat
4662 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4663 "\\([^" org-non-link-chars " ]"
4664 "[^]\t\n\r]*"
4665 "[^" org-non-link-chars " ]\\)>?")
4666 org-angle-link-re
4667 (concat
4668 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4669 "\\([^" org-non-link-chars " ]"
4670 "[^" org-non-link-chars "]*"
4671 "\\)>")
4672 org-plain-link-re
4673 (concat
4674 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4675 "\\([^]\t\n\r<>,;() ]+\\)")
4676 org-bracket-link-regexp
4677 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4678 org-bracket-link-analytic-regexp
4679 (concat
4680 "\\[\\["
4681 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4682 "\\([^]]+\\)"
4683 "\\]"
4684 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4685 "\\]")
4686 org-any-link-re
4687 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4688 org-angle-link-re "\\)\\|\\("
4689 org-plain-link-re "\\)")))
4691 (org-make-link-regexps)
4693 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4694 "Regular expression for fast time stamp matching.")
4695 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4696 "Regular expression for fast time stamp matching.")
4697 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4698 "Regular expression matching time strings for analysis.
4699 This one does not require the space after the date.")
4700 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4701 "Regular expression matching time strings for analysis.")
4702 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4703 "Regular expression matching time stamps, with groups.")
4704 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4705 "Regular expression matching time stamps (also [..]), with groups.")
4706 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4707 "Regular expression matching a time stamp range.")
4708 (defconst org-tr-regexp-both
4709 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4710 "Regular expression matching a time stamp range.")
4711 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4712 org-ts-regexp "\\)?")
4713 "Regular expression matching a time stamp or time stamp range.")
4714 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4715 org-ts-regexp-both "\\)?")
4716 "Regular expression matching a time stamp or time stamp range.
4717 The time stamps may be either active or inactive.")
4719 (defvar org-emph-face nil)
4721 (defun org-do-emphasis-faces (limit)
4722 "Run through the buffer and add overlays to links."
4723 (let (rtn)
4724 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4725 (if (not (= (char-after (match-beginning 3))
4726 (char-after (match-beginning 4))))
4727 (progn
4728 (setq rtn t)
4729 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4730 'face
4731 (nth 1 (assoc (match-string 3)
4732 org-emphasis-alist)))
4733 (add-text-properties (match-beginning 2) (match-end 2)
4734 '(font-lock-multiline t))
4735 (backward-char 1))))
4736 rtn))
4738 (defun org-emphasize (&optional char)
4739 "Insert or change an emphasis, i.e. a font like bold or italic.
4740 If there is an active region, change that region to a new emphasis.
4741 If there is no region, just insert the marker characters and position
4742 the cursor between them.
4743 CHAR should be either the marker character, or the first character of the
4744 HTML tag associated with that emphasis. If CHAR is a space, the means
4745 to remove the emphasis of the selected region.
4746 If char is not given (for example in an interactive call) it
4747 will be prompted for."
4748 (interactive)
4749 (let ((eal org-emphasis-alist) e det
4750 (erc org-emphasis-regexp-components)
4751 (prompt "")
4752 (string "") beg end move tag c s)
4753 (if (org-region-active-p)
4754 (setq beg (region-beginning) end (region-end)
4755 string (buffer-substring beg end))
4756 (setq move t))
4758 (while (setq e (pop eal))
4759 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4760 c (aref tag 0))
4761 (push (cons c (string-to-char (car e))) det)
4762 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4763 (substring tag 1)))))
4764 (unless char
4765 (message "%s" (concat "Emphasis marker or tag:" prompt))
4766 (setq char (read-char-exclusive)))
4767 (setq char (or (cdr (assoc char det)) char))
4768 (if (equal char ?\ )
4769 (setq s "" move nil)
4770 (unless (assoc (char-to-string char) org-emphasis-alist)
4771 (error "No such emphasis marker: \"%c\"" char))
4772 (setq s (char-to-string char)))
4773 (while (and (> (length string) 1)
4774 (equal (substring string 0 1) (substring string -1))
4775 (assoc (substring string 0 1) org-emphasis-alist))
4776 (setq string (substring string 1 -1)))
4777 (setq string (concat s string s))
4778 (if beg (delete-region beg end))
4779 (unless (or (bolp)
4780 (string-match (concat "[" (nth 0 erc) "\n]")
4781 (char-to-string (char-before (point)))))
4782 (insert " "))
4783 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4784 (char-to-string (char-after (point))))
4785 (insert " ") (backward-char 1))
4786 (insert string)
4787 (and move (backward-char 1))))
4789 (defconst org-nonsticky-props
4790 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4793 (defun org-activate-plain-links (limit)
4794 "Run through the buffer and add overlays to links."
4795 (catch 'exit
4796 (let (f)
4797 (while (re-search-forward org-plain-link-re limit t)
4798 (setq f (get-text-property (match-beginning 0) 'face))
4799 (if (or (eq f 'org-tag)
4800 (and (listp f) (memq 'org-tag f)))
4802 (add-text-properties (match-beginning 0) (match-end 0)
4803 (list 'mouse-face 'highlight
4804 'rear-nonsticky org-nonsticky-props
4805 'keymap org-mouse-map
4807 (throw 'exit t))))))
4809 (defun org-activate-code (limit)
4810 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4811 (unless (get-text-property (match-beginning 1) 'face)
4812 (remove-text-properties (match-beginning 0) (match-end 0)
4813 '(display t invisible t intangible t))
4814 t)))
4816 (defun org-activate-angle-links (limit)
4817 "Run through the buffer and add overlays to links."
4818 (if (re-search-forward org-angle-link-re limit t)
4819 (progn
4820 (add-text-properties (match-beginning 0) (match-end 0)
4821 (list 'mouse-face 'highlight
4822 'rear-nonsticky org-nonsticky-props
4823 'keymap org-mouse-map
4825 t)))
4827 (defmacro org-maybe-intangible (props)
4828 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4829 In emacs 21, invisible text is not avoided by the command loop, so the
4830 intangible property is needed to make sure point skips this text.
4831 In Emacs 22, this is not necessary. The intangible text property has
4832 led to problems with flyspell. These problems are fixed in flyspell.el,
4833 but we still avoid setting the property in Emacs 22 and later.
4834 We use a macro so that the test can happen at compilation time."
4835 (if (< emacs-major-version 22)
4836 `(append '(intangible t) ,props)
4837 props))
4839 (defun org-activate-bracket-links (limit)
4840 "Run through the buffer and add overlays to bracketed links."
4841 (if (re-search-forward org-bracket-link-regexp limit t)
4842 (let* ((help (concat "LINK: "
4843 (org-match-string-no-properties 1)))
4844 ;; FIXME: above we should remove the escapes.
4845 ;; but that requires another match, protecting match data,
4846 ;; a lot of overhead for font-lock.
4847 (ip (org-maybe-intangible
4848 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4849 'keymap org-mouse-map 'mouse-face 'highlight
4850 'help-echo help)))
4851 (vp (list 'rear-nonsticky org-nonsticky-props
4852 'keymap org-mouse-map 'mouse-face 'highlight
4853 'help-echo help)))
4854 ;; We need to remove the invisible property here. Table narrowing
4855 ;; may have made some of this invisible.
4856 (remove-text-properties (match-beginning 0) (match-end 0)
4857 '(invisible nil))
4858 (if (match-end 3)
4859 (progn
4860 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4861 (add-text-properties (match-beginning 3) (match-end 3) vp)
4862 (add-text-properties (match-end 3) (match-end 0) ip))
4863 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4864 (add-text-properties (match-beginning 1) (match-end 1) vp)
4865 (add-text-properties (match-end 1) (match-end 0) ip))
4866 t)))
4868 (defun org-activate-dates (limit)
4869 "Run through the buffer and add overlays to dates."
4870 (if (re-search-forward org-tsr-regexp-both limit t)
4871 (progn
4872 (add-text-properties (match-beginning 0) (match-end 0)
4873 (list 'mouse-face 'highlight
4874 'rear-nonsticky org-nonsticky-props
4875 'keymap org-mouse-map))
4876 (when org-display-custom-times
4877 (if (match-end 3)
4878 (org-display-custom-time (match-beginning 3) (match-end 3)))
4879 (org-display-custom-time (match-beginning 1) (match-end 1)))
4880 t)))
4882 (defvar org-target-link-regexp nil
4883 "Regular expression matching radio targets in plain text.")
4884 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4885 "Regular expression matching a link target.")
4886 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4887 "Regular expression matching a radio target.")
4888 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4889 "Regular expression matching any target.")
4891 (defun org-activate-target-links (limit)
4892 "Run through the buffer and add overlays to target matches."
4893 (when org-target-link-regexp
4894 (let ((case-fold-search t))
4895 (if (re-search-forward org-target-link-regexp limit t)
4896 (progn
4897 (add-text-properties (match-beginning 0) (match-end 0)
4898 (list 'mouse-face 'highlight
4899 'rear-nonsticky org-nonsticky-props
4900 'keymap org-mouse-map
4901 'help-echo "Radio target link"
4902 'org-linked-text t))
4903 t)))))
4905 (defun org-update-radio-target-regexp ()
4906 "Find all radio targets in this file and update the regular expression."
4907 (interactive)
4908 (when (memq 'radio org-activate-links)
4909 (setq org-target-link-regexp
4910 (org-make-target-link-regexp (org-all-targets 'radio)))
4911 (org-restart-font-lock)))
4913 (defun org-hide-wide-columns (limit)
4914 (let (s e)
4915 (setq s (text-property-any (point) (or limit (point-max))
4916 'org-cwidth t))
4917 (when s
4918 (setq e (next-single-property-change s 'org-cwidth))
4919 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4920 (goto-char e)
4921 t)))
4923 (defun org-restart-font-lock ()
4924 "Restart font-lock-mode, to force refontification."
4925 (when (and (boundp 'font-lock-mode) font-lock-mode)
4926 (font-lock-mode -1)
4927 (font-lock-mode 1)))
4929 (defun org-all-targets (&optional radio)
4930 "Return a list of all targets in this file.
4931 With optional argument RADIO, only find radio targets."
4932 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4933 rtn)
4934 (save-excursion
4935 (goto-char (point-min))
4936 (while (re-search-forward re nil t)
4937 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4938 rtn)))
4940 (defun org-make-target-link-regexp (targets)
4941 "Make regular expression matching all strings in TARGETS.
4942 The regular expression finds the targets also if there is a line break
4943 between words."
4944 (and targets
4945 (concat
4946 "\\<\\("
4947 (mapconcat
4948 (lambda (x)
4949 (while (string-match " +" x)
4950 (setq x (replace-match "\\s-+" t t x)))
4952 targets
4953 "\\|")
4954 "\\)\\>")))
4956 (defun org-activate-tags (limit)
4957 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4958 (progn
4959 (add-text-properties (match-beginning 1) (match-end 1)
4960 (list 'mouse-face 'highlight
4961 'rear-nonsticky org-nonsticky-props
4962 'keymap org-mouse-map))
4963 t)))
4965 (defun org-outline-level ()
4966 (save-excursion
4967 (looking-at outline-regexp)
4968 (if (match-beginning 1)
4969 (+ (org-get-string-indentation (match-string 1)) 1000)
4970 (1- (- (match-end 0) (match-beginning 0))))))
4972 (defvar org-font-lock-keywords nil)
4974 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
4975 "Regular expression matching a property line.")
4977 (defun org-set-font-lock-defaults ()
4978 (let* ((em org-fontify-emphasized-text)
4979 (lk org-activate-links)
4980 (org-font-lock-extra-keywords
4981 (list
4982 ;; Headlines
4983 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4984 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4985 ;; Table lines
4986 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4987 (1 'org-table t))
4988 ;; Table internals
4989 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4990 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4991 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4992 ;; Drawers
4993 (list org-drawer-regexp '(0 'org-special-keyword t))
4994 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4995 ;; Properties
4996 (list org-property-re
4997 '(1 'org-special-keyword t)
4998 '(3 'org-property-value t))
4999 (if org-format-transports-properties-p
5000 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5001 ;; Links
5002 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5003 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5004 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5005 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5006 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5007 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5008 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5009 '(org-hide-wide-columns (0 nil append))
5010 ;; TODO lines
5011 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5012 '(1 (org-get-todo-face 1) t))
5013 ;; DONE
5014 (if org-fontify-done-headline
5015 (list (concat "^[*]+ +\\<\\("
5016 (mapconcat 'regexp-quote org-done-keywords "\\|")
5017 "\\)\\(.*\\)")
5018 '(2 'org-headline-done t))
5019 nil)
5020 ;; Priorities
5021 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5022 ;; Special keywords
5023 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5024 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5025 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5026 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5027 ;; Emphasis
5028 (if em
5029 (if (featurep 'xemacs)
5030 '(org-do-emphasis-faces (0 nil append))
5031 '(org-do-emphasis-faces)))
5032 ;; Checkboxes
5033 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5034 2 'bold prepend)
5035 (if org-provide-checkbox-statistics
5036 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5037 (0 (org-get-checkbox-statistics-face) t)))
5038 ;; COMMENT
5039 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5040 "\\|" org-quote-string "\\)\\>")
5041 '(1 'org-special-keyword t))
5042 '("^#.*" (0 'font-lock-comment-face t))
5043 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
5044 ;; Code
5045 '(org-activate-code (1 'org-code t))
5047 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5048 ;; Now set the full font-lock-keywords
5049 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5050 (org-set-local 'font-lock-defaults
5051 '(org-font-lock-keywords t nil nil backward-paragraph))
5052 (kill-local-variable 'font-lock-keywords) nil))
5054 (defvar org-m nil)
5055 (defvar org-l nil)
5056 (defvar org-f nil)
5057 (defun org-get-level-face (n)
5058 "Get the right face for match N in font-lock matching of healdines."
5059 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5060 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5061 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5062 (cond
5063 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5064 ((eq n 2) org-f)
5065 (t (if org-level-color-stars-only nil org-f))))
5067 (defun org-get-todo-face (kwd)
5068 "Get the right face for a TODO keyword KWD.
5069 If KWD is a number, get the corresponding match group."
5070 (if (numberp kwd) (setq kwd (match-string kwd)))
5071 (or (cdr (assoc kwd org-todo-keyword-faces))
5072 (and (member kwd org-done-keywords) 'org-done)
5073 'org-todo))
5075 (defun org-unfontify-region (beg end &optional maybe_loudly)
5076 "Remove fontification and activation overlays from links."
5077 (font-lock-default-unfontify-region beg end)
5078 (let* ((buffer-undo-list t)
5079 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5080 (inhibit-modification-hooks t)
5081 deactivate-mark buffer-file-name buffer-file-truename)
5082 (remove-text-properties beg end
5083 '(mouse-face t keymap t org-linked-text t
5084 invisible t intangible t))))
5086 ;;;; Visibility cycling, including org-goto and indirect buffer
5088 ;;; Cycling
5090 (defvar org-cycle-global-status nil)
5091 (make-variable-buffer-local 'org-cycle-global-status)
5092 (defvar org-cycle-subtree-status nil)
5093 (make-variable-buffer-local 'org-cycle-subtree-status)
5095 ;;;###autoload
5096 (defun org-cycle (&optional arg)
5097 "Visibility cycling for Org-mode.
5099 - When this function is called with a prefix argument, rotate the entire
5100 buffer through 3 states (global cycling)
5101 1. OVERVIEW: Show only top-level headlines.
5102 2. CONTENTS: Show all headlines of all levels, but no body text.
5103 3. SHOW ALL: Show everything.
5105 - When point is at the beginning of a headline, rotate the subtree started
5106 by this line through 3 different states (local cycling)
5107 1. FOLDED: Only the main headline is shown.
5108 2. CHILDREN: The main headline and the direct children are shown.
5109 From this state, you can move to one of the children
5110 and zoom in further.
5111 3. SUBTREE: Show the entire subtree, including body text.
5113 - When there is a numeric prefix, go up to a heading with level ARG, do
5114 a `show-subtree' and return to the previous cursor position. If ARG
5115 is negative, go up that many levels.
5117 - When point is not at the beginning of a headline, execute
5118 `indent-relative', like TAB normally does. See the option
5119 `org-cycle-emulate-tab' for details.
5121 - Special case: if point is at the beginning of the buffer and there is
5122 no headline in line 1, this function will act as if called with prefix arg.
5123 But only if also the variable `org-cycle-global-at-bob' is t."
5124 (interactive "P")
5125 (let* ((outline-regexp
5126 (if (and (org-mode-p) org-cycle-include-plain-lists)
5127 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5128 outline-regexp))
5129 (bob-special (and org-cycle-global-at-bob (bobp)
5130 (not (looking-at outline-regexp))))
5131 (org-cycle-hook
5132 (if bob-special
5133 (delq 'org-optimize-window-after-visibility-change
5134 (copy-sequence org-cycle-hook))
5135 org-cycle-hook))
5136 (pos (point)))
5138 (if (or bob-special (equal arg '(4)))
5139 ;; special case: use global cycling
5140 (setq arg t))
5142 (cond
5144 ((org-at-table-p 'any)
5145 ;; Enter the table or move to the next field in the table
5146 (or (org-table-recognize-table.el)
5147 (progn
5148 (if arg (org-table-edit-field t)
5149 (org-table-justify-field-maybe)
5150 (call-interactively 'org-table-next-field)))))
5152 ((eq arg t) ;; Global cycling
5154 (cond
5155 ((and (eq last-command this-command)
5156 (eq org-cycle-global-status 'overview))
5157 ;; We just created the overview - now do table of contents
5158 ;; This can be slow in very large buffers, so indicate action
5159 (message "CONTENTS...")
5160 (org-content)
5161 (message "CONTENTS...done")
5162 (setq org-cycle-global-status 'contents)
5163 (run-hook-with-args 'org-cycle-hook 'contents))
5165 ((and (eq last-command this-command)
5166 (eq org-cycle-global-status 'contents))
5167 ;; We just showed the table of contents - now show everything
5168 (show-all)
5169 (message "SHOW ALL")
5170 (setq org-cycle-global-status 'all)
5171 (run-hook-with-args 'org-cycle-hook 'all))
5174 ;; Default action: go to overview
5175 (org-overview)
5176 (message "OVERVIEW")
5177 (setq org-cycle-global-status 'overview)
5178 (run-hook-with-args 'org-cycle-hook 'overview))))
5180 ((and org-drawers org-drawer-regexp
5181 (save-excursion
5182 (beginning-of-line 1)
5183 (looking-at org-drawer-regexp)))
5184 ;; Toggle block visibility
5185 (org-flag-drawer
5186 (not (get-char-property (match-end 0) 'invisible))))
5188 ((integerp arg)
5189 ;; Show-subtree, ARG levels up from here.
5190 (save-excursion
5191 (org-back-to-heading)
5192 (outline-up-heading (if (< arg 0) (- arg)
5193 (- (funcall outline-level) arg)))
5194 (org-show-subtree)))
5196 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5197 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5198 ;; At a heading: rotate between three different views
5199 (org-back-to-heading)
5200 (let ((goal-column 0) eoh eol eos)
5201 ;; First, some boundaries
5202 (save-excursion
5203 (org-back-to-heading)
5204 (save-excursion
5205 (beginning-of-line 2)
5206 (while (and (not (eobp)) ;; this is like `next-line'
5207 (get-char-property (1- (point)) 'invisible))
5208 (beginning-of-line 2)) (setq eol (point)))
5209 (outline-end-of-heading) (setq eoh (point))
5210 (org-end-of-subtree t)
5211 (unless (eobp)
5212 (skip-chars-forward " \t\n")
5213 (beginning-of-line 1) ; in case this is an item
5215 (setq eos (1- (point))))
5216 ;; Find out what to do next and set `this-command'
5217 (cond
5218 ((= eos eoh)
5219 ;; Nothing is hidden behind this heading
5220 (message "EMPTY ENTRY")
5221 (setq org-cycle-subtree-status nil)
5222 (save-excursion
5223 (goto-char eos)
5224 (outline-next-heading)
5225 (if (org-invisible-p) (org-flag-heading nil))))
5226 ((or (>= eol eos)
5227 (not (string-match "\\S-" (buffer-substring eol eos))))
5228 ;; Entire subtree is hidden in one line: open it
5229 (org-show-entry)
5230 (show-children)
5231 (message "CHILDREN")
5232 (save-excursion
5233 (goto-char eos)
5234 (outline-next-heading)
5235 (if (org-invisible-p) (org-flag-heading nil)))
5236 (setq org-cycle-subtree-status 'children)
5237 (run-hook-with-args 'org-cycle-hook 'children))
5238 ((and (eq last-command this-command)
5239 (eq org-cycle-subtree-status 'children))
5240 ;; We just showed the children, now show everything.
5241 (org-show-subtree)
5242 (message "SUBTREE")
5243 (setq org-cycle-subtree-status 'subtree)
5244 (run-hook-with-args 'org-cycle-hook 'subtree))
5246 ;; Default action: hide the subtree.
5247 (hide-subtree)
5248 (message "FOLDED")
5249 (setq org-cycle-subtree-status 'folded)
5250 (run-hook-with-args 'org-cycle-hook 'folded)))))
5252 ;; TAB emulation
5253 (buffer-read-only (org-back-to-heading))
5255 ((org-try-cdlatex-tab))
5257 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5258 (or (not (bolp))
5259 (not (looking-at outline-regexp))))
5260 (call-interactively (global-key-binding "\t")))
5262 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5263 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5264 (or (and (eq org-cycle-emulate-tab 'white)
5265 (= (match-end 0) (point-at-eol)))
5266 (and (eq org-cycle-emulate-tab 'whitestart)
5267 (>= (match-end 0) pos))))
5269 (eq org-cycle-emulate-tab t))
5270 (if (and (looking-at "[ \n\r\t]")
5271 (string-match "^[ \t]*$" (buffer-substring
5272 (point-at-bol) (point))))
5273 (progn
5274 (beginning-of-line 1)
5275 (and (looking-at "[ \t]+") (replace-match ""))))
5276 (call-interactively (global-key-binding "\t")))
5278 (t (save-excursion
5279 (org-back-to-heading)
5280 (org-cycle))))))
5282 ;;;###autoload
5283 (defun org-global-cycle (&optional arg)
5284 "Cycle the global visibility. For details see `org-cycle'."
5285 (interactive "P")
5286 (let ((org-cycle-include-plain-lists
5287 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5288 (if (integerp arg)
5289 (progn
5290 (show-all)
5291 (hide-sublevels arg)
5292 (setq org-cycle-global-status 'contents))
5293 (org-cycle '(4)))))
5295 (defun org-overview ()
5296 "Switch to overview mode, shoing only top-level headlines.
5297 Really, this shows all headlines with level equal or greater than the level
5298 of the first headline in the buffer. This is important, because if the
5299 first headline is not level one, then (hide-sublevels 1) gives confusing
5300 results."
5301 (interactive)
5302 (let ((level (save-excursion
5303 (goto-char (point-min))
5304 (if (re-search-forward (concat "^" outline-regexp) nil t)
5305 (progn
5306 (goto-char (match-beginning 0))
5307 (funcall outline-level))))))
5308 (and level (hide-sublevels level))))
5310 (defun org-content (&optional arg)
5311 "Show all headlines in the buffer, like a table of contents.
5312 With numerical argument N, show content up to level N."
5313 (interactive "P")
5314 (save-excursion
5315 ;; Visit all headings and show their offspring
5316 (and (integerp arg) (org-overview))
5317 (goto-char (point-max))
5318 (catch 'exit
5319 (while (and (progn (condition-case nil
5320 (outline-previous-visible-heading 1)
5321 (error (goto-char (point-min))))
5323 (looking-at outline-regexp))
5324 (if (integerp arg)
5325 (show-children (1- arg))
5326 (show-branches))
5327 (if (bobp) (throw 'exit nil))))))
5330 (defun org-optimize-window-after-visibility-change (state)
5331 "Adjust the window after a change in outline visibility.
5332 This function is the default value of the hook `org-cycle-hook'."
5333 (when (get-buffer-window (current-buffer))
5334 (cond
5335 ; ((eq state 'overview) (org-first-headline-recenter 1))
5336 ; ((eq state 'overview) (org-beginning-of-line))
5337 ((eq state 'content) nil)
5338 ((eq state 'all) nil)
5339 ((eq state 'folded) nil)
5340 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5341 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5344 (defun org-cycle-show-empty-lines (state)
5345 "Show empty lines above all visible headlines.
5346 The region to be covered depends on STATE when called through
5347 `org-cycle-hook'. Lisp program can use t for STATE to get the
5348 entire buffer covered. Note that an empty line is only shown if there
5349 are at least `org-cycle-separator-lines' empty lines before the headeline."
5350 (when (> org-cycle-separator-lines 0)
5351 (save-excursion
5352 (let* ((n org-cycle-separator-lines)
5353 (re (cond
5354 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5355 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5356 (t (let ((ns (number-to-string (- n 2))))
5357 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5358 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5359 beg end)
5360 (cond
5361 ((memq state '(overview contents t))
5362 (setq beg (point-min) end (point-max)))
5363 ((memq state '(children folded))
5364 (setq beg (point) end (progn (org-end-of-subtree t t)
5365 (beginning-of-line 2)
5366 (point)))))
5367 (when beg
5368 (goto-char beg)
5369 (while (re-search-forward re end t)
5370 (if (not (get-char-property (match-end 1) 'invisible))
5371 (outline-flag-region
5372 (match-beginning 1) (match-end 1) nil)))))))
5373 ;; Never hide empty lines at the end of the file.
5374 (save-excursion
5375 (goto-char (point-max))
5376 (outline-previous-heading)
5377 (outline-end-of-heading)
5378 (if (and (looking-at "[ \t\n]+")
5379 (= (match-end 0) (point-max)))
5380 (outline-flag-region (point) (match-end 0) nil))))
5382 (defun org-subtree-end-visible-p ()
5383 "Is the end of the current subtree visible?"
5384 (pos-visible-in-window-p
5385 (save-excursion (org-end-of-subtree t) (point))))
5387 (defun org-first-headline-recenter (&optional N)
5388 "Move cursor to the first headline and recenter the headline.
5389 Optional argument N means, put the headline into the Nth line of the window."
5390 (goto-char (point-min))
5391 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5392 (beginning-of-line)
5393 (recenter (prefix-numeric-value N))))
5395 ;;; Org-goto
5397 (defvar org-goto-window-configuration nil)
5398 (defvar org-goto-marker nil)
5399 (defvar org-goto-map
5400 (let ((map (make-sparse-keymap)))
5401 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5402 (while (setq cmd (pop cmds))
5403 (substitute-key-definition cmd cmd map global-map)))
5404 (suppress-keymap map)
5405 (org-defkey map "\C-m" 'org-goto-ret)
5406 (org-defkey map [(left)] 'org-goto-left)
5407 (org-defkey map [(right)] 'org-goto-right)
5408 (org-defkey map [(?q)] 'org-goto-quit)
5409 (org-defkey map [(control ?g)] 'org-goto-quit)
5410 (org-defkey map "\C-i" 'org-cycle)
5411 (org-defkey map [(tab)] 'org-cycle)
5412 (org-defkey map [(down)] 'outline-next-visible-heading)
5413 (org-defkey map [(up)] 'outline-previous-visible-heading)
5414 (org-defkey map "n" 'outline-next-visible-heading)
5415 (org-defkey map "p" 'outline-previous-visible-heading)
5416 (org-defkey map "f" 'outline-forward-same-level)
5417 (org-defkey map "b" 'outline-backward-same-level)
5418 (org-defkey map "u" 'outline-up-heading)
5419 (org-defkey map "/" 'org-occur)
5420 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5421 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5422 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5423 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5424 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5425 map))
5427 (defconst org-goto-help
5428 "Browse copy of buffer to find location or copy text.
5429 RET=jump to location [Q]uit and return to previous location
5430 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5433 (defun org-goto ()
5434 "Look up a different location in the current file, keeping current visibility.
5436 When you want look-up or go to a different location in a document, the
5437 fastest way is often to fold the entire buffer and then dive into the tree.
5438 This method has the disadvantage, that the previous location will be folded,
5439 which may not be what you want.
5441 This command works around this by showing a copy of the current buffer
5442 in an indirect buffer, in overview mode. You can dive into the tree in
5443 that copy, use org-occur and incremental search to find a location.
5444 When pressing RET or `Q', the command returns to the original buffer in
5445 which the visibility is still unchanged. After RET is will also jump to
5446 the location selected in the indirect buffer and expose the
5447 the headline hierarchy above."
5448 (interactive)
5449 (let* ((org-goto-start-pos (point))
5450 (selected-point
5451 (car (org-get-location (current-buffer) org-goto-help))))
5452 (if selected-point
5453 (progn
5454 (org-mark-ring-push org-goto-start-pos)
5455 (goto-char selected-point)
5456 (if (or (org-invisible-p) (org-invisible-p2))
5457 (org-show-context 'org-goto)))
5458 (message "Quit"))))
5460 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5461 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5463 (defun org-get-location (buf help)
5464 "Let the user select a location in the Org-mode buffer BUF.
5465 This function uses a recursive edit. It returns the selected position
5466 or nil."
5467 (let (org-goto-selected-point org-goto-exit-command)
5468 (save-excursion
5469 (save-window-excursion
5470 (delete-other-windows)
5471 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5472 (switch-to-buffer
5473 (condition-case nil
5474 (make-indirect-buffer (current-buffer) "*org-goto*")
5475 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5476 (with-output-to-temp-buffer "*Help*"
5477 (princ help))
5478 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5479 (setq buffer-read-only nil)
5480 (let ((org-startup-truncated t)
5481 (org-startup-folded nil)
5482 (org-startup-align-all-tables nil))
5483 (org-mode)
5484 (org-overview))
5485 (setq buffer-read-only t)
5486 (if (and (boundp 'org-goto-start-pos)
5487 (integer-or-marker-p org-goto-start-pos))
5488 (let ((org-show-hierarchy-above t)
5489 (org-show-siblings t)
5490 (org-show-following-heading t))
5491 (goto-char org-goto-start-pos)
5492 (and (org-invisible-p) (org-show-context)))
5493 (goto-char (point-min)))
5494 (org-beginning-of-line)
5495 (message "Select location and press RET")
5496 ;; now we make sure that during selection, ony very few keys work
5497 ;; and that it is impossible to switch to another window.
5498 ; (let ((gm (current-global-map))
5499 ; (overriding-local-map org-goto-map))
5500 ; (unwind-protect
5501 ; (progn
5502 ; (use-global-map org-goto-map)
5503 ; (recursive-edit))
5504 ; (use-global-map gm)))
5505 (use-local-map org-goto-map)
5506 (recursive-edit)
5508 (kill-buffer "*org-goto*")
5509 (cons org-goto-selected-point org-goto-exit-command)))
5511 (defun org-goto-ret (&optional arg)
5512 "Finish `org-goto' by going to the new location."
5513 (interactive "P")
5514 (setq org-goto-selected-point (point)
5515 org-goto-exit-command 'return)
5516 (throw 'exit nil))
5518 (defun org-goto-left ()
5519 "Finish `org-goto' by going to the new location."
5520 (interactive)
5521 (if (org-on-heading-p)
5522 (progn
5523 (beginning-of-line 1)
5524 (setq org-goto-selected-point (point)
5525 org-goto-exit-command 'left)
5526 (throw 'exit nil))
5527 (error "Not on a heading")))
5529 (defun org-goto-right ()
5530 "Finish `org-goto' by going to the new location."
5531 (interactive)
5532 (if (org-on-heading-p)
5533 (progn
5534 (setq org-goto-selected-point (point)
5535 org-goto-exit-command 'right)
5536 (throw 'exit nil))
5537 (error "Not on a heading")))
5539 (defun org-goto-quit ()
5540 "Finish `org-goto' without cursor motion."
5541 (interactive)
5542 (setq org-goto-selected-point nil)
5543 (setq org-goto-exit-command 'quit)
5544 (throw 'exit nil))
5546 ;;; Indirect buffer display of subtrees
5548 (defvar org-indirect-dedicated-frame nil
5549 "This is the frame being used for indirect tree display.")
5550 (defvar org-last-indirect-buffer nil)
5552 (defun org-tree-to-indirect-buffer (&optional arg)
5553 "Create indirect buffer and narrow it to current subtree.
5554 With numerical prefix ARG, go up to this level and then take that tree.
5555 If ARG is negative, go up that many levels.
5556 Normally this command removes the indirect buffer previously made
5557 with this command. However, when called with a C-u prefix, the last buffer
5558 is kept so that you can work with several indirect buffers at the same time.
5559 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5560 requests that a new frame be made for the new buffer, so that the dedicated
5561 frame is not changed."
5562 (interactive "P")
5563 (let ((cbuf (current-buffer))
5564 (cwin (selected-window))
5565 (pos (point))
5566 beg end level heading ibuf)
5567 (save-excursion
5568 (org-back-to-heading t)
5569 (when (numberp arg)
5570 (setq level (org-outline-level))
5571 (if (< arg 0) (setq arg (+ level arg)))
5572 (while (> (setq level (org-outline-level)) arg)
5573 (outline-up-heading 1 t)))
5574 (setq beg (point)
5575 heading (org-get-heading))
5576 (org-end-of-subtree t) (setq end (point)))
5577 (if (and (not arg)
5578 (buffer-live-p org-last-indirect-buffer))
5579 (kill-buffer org-last-indirect-buffer))
5580 (setq ibuf (org-get-indirect-buffer cbuf)
5581 org-last-indirect-buffer ibuf)
5582 (cond
5583 ((or (eq org-indirect-buffer-display 'new-frame)
5584 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5585 (select-frame (make-frame))
5586 (delete-other-windows)
5587 (switch-to-buffer ibuf)
5588 (org-set-frame-title heading))
5589 ((eq org-indirect-buffer-display 'dedicated-frame)
5590 (raise-frame
5591 (select-frame (or (and org-indirect-dedicated-frame
5592 (frame-live-p org-indirect-dedicated-frame)
5593 org-indirect-dedicated-frame)
5594 (setq org-indirect-dedicated-frame (make-frame)))))
5595 (delete-other-windows)
5596 (switch-to-buffer ibuf)
5597 (org-set-frame-title (concat "Indirect: " heading)))
5598 ((eq org-indirect-buffer-display 'current-window)
5599 (switch-to-buffer ibuf))
5600 ((eq org-indirect-buffer-display 'other-window)
5601 (pop-to-buffer ibuf))
5602 (t (error "Invalid value.")))
5603 (if (featurep 'xemacs)
5604 (save-excursion (org-mode) (turn-on-font-lock)))
5605 (narrow-to-region beg end)
5606 (show-all)
5607 (goto-char pos)
5608 (and (window-live-p cwin) (select-window cwin))))
5610 (defun org-get-indirect-buffer (&optional buffer)
5611 (setq buffer (or buffer (current-buffer)))
5612 (let ((n 1) (base (buffer-name buffer)) bname)
5613 (while (buffer-live-p
5614 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5615 (setq n (1+ n)))
5616 (condition-case nil
5617 (make-indirect-buffer buffer bname 'clone)
5618 (error (make-indirect-buffer buffer bname)))))
5620 (defun org-set-frame-title (title)
5621 "Set the title of the current frame to the string TITLE."
5622 ;; FIXME: how to name a single frame in XEmacs???
5623 (unless (featurep 'xemacs)
5624 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5626 ;;;; Structure editing
5628 ;;; Inserting headlines
5630 (defun org-insert-heading (&optional force-heading)
5631 "Insert a new heading or item with same depth at point.
5632 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5633 If point is at the beginning of a headline, insert a sibling before the
5634 current headline. If point is in the middle of a headline, split the headline
5635 at that position and make the rest of the headline part of the sibling below
5636 the current headline."
5637 (interactive "P")
5638 (if (= (buffer-size) 0)
5639 (insert "\n* ")
5640 (when (or force-heading (not (org-insert-item)))
5641 (let* ((head (save-excursion
5642 (condition-case nil
5643 (progn
5644 (org-back-to-heading)
5645 (match-string 0))
5646 (error "*"))))
5647 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5648 pos)
5649 (cond
5650 ((and (org-on-heading-p) (bolp)
5651 (or (bobp)
5652 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5653 (open-line (if blank 2 1)))
5654 ((and (bolp)
5655 (or (bobp)
5656 (save-excursion
5657 (backward-char 1) (not (org-invisible-p)))))
5658 nil)
5659 (t (newline (if blank 2 1))))
5660 (insert head) (just-one-space)
5661 (setq pos (point))
5662 (end-of-line 1)
5663 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5664 (run-hooks 'org-insert-heading-hook)))))
5666 (defun org-insert-heading-after-current ()
5667 "Insert a new heading with same level as current, after current subtree."
5668 (interactive)
5669 (org-back-to-heading)
5670 (org-insert-heading)
5671 (org-move-subtree-down)
5672 (end-of-line 1))
5674 (defun org-insert-todo-heading (arg)
5675 "Insert a new heading with the same level and TODO state as current heading.
5676 If the heading has no TODO state, or if the state is DONE, use the first
5677 state (TODO by default). Also with prefix arg, force first state."
5678 (interactive "P")
5679 (when (not (org-insert-item 'checkbox))
5680 (org-insert-heading)
5681 (save-excursion
5682 (org-back-to-heading)
5683 (outline-previous-heading)
5684 (looking-at org-todo-line-regexp))
5685 (if (or arg
5686 (not (match-beginning 2))
5687 (member (match-string 2) org-done-keywords))
5688 (insert (car org-todo-keywords-1) " ")
5689 (insert (match-string 2) " "))))
5691 (defun org-insert-subheading (arg)
5692 "Insert a new subheading and demote it.
5693 Works for outline headings and for plain lists alike."
5694 (interactive "P")
5695 (org-insert-heading arg)
5696 (cond
5697 ((org-on-heading-p) (org-do-demote))
5698 ((org-at-item-p) (org-indent-item 1))))
5700 (defun org-insert-todo-subheading (arg)
5701 "Insert a new subheading with TODO keyword or checkbox and demote it.
5702 Works for outline headings and for plain lists alike."
5703 (interactive "P")
5704 (org-insert-todo-heading arg)
5705 (cond
5706 ((org-on-heading-p) (org-do-demote))
5707 ((org-at-item-p) (org-indent-item 1))))
5709 ;;; Promotion and Demotion
5711 (defun org-promote-subtree ()
5712 "Promote the entire subtree.
5713 See also `org-promote'."
5714 (interactive)
5715 (save-excursion
5716 (org-map-tree 'org-promote))
5717 (org-fix-position-after-promote))
5719 (defun org-demote-subtree ()
5720 "Demote the entire subtree. See `org-demote'.
5721 See also `org-promote'."
5722 (interactive)
5723 (save-excursion
5724 (org-map-tree 'org-demote))
5725 (org-fix-position-after-promote))
5728 (defun org-do-promote ()
5729 "Promote the current heading higher up the tree.
5730 If the region is active in `transient-mark-mode', promote all headings
5731 in the region."
5732 (interactive)
5733 (save-excursion
5734 (if (org-region-active-p)
5735 (org-map-region 'org-promote (region-beginning) (region-end))
5736 (org-promote)))
5737 (org-fix-position-after-promote))
5739 (defun org-do-demote ()
5740 "Demote the current heading lower down the tree.
5741 If the region is active in `transient-mark-mode', demote all headings
5742 in the region."
5743 (interactive)
5744 (save-excursion
5745 (if (org-region-active-p)
5746 (org-map-region 'org-demote (region-beginning) (region-end))
5747 (org-demote)))
5748 (org-fix-position-after-promote))
5750 (defun org-fix-position-after-promote ()
5751 "Make sure that after pro/demotion cursor position is right."
5752 (let ((pos (point)))
5753 (when (save-excursion
5754 (beginning-of-line 1)
5755 (looking-at org-todo-line-regexp)
5756 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5757 (cond ((eobp) (insert " "))
5758 ((eolp) (insert " "))
5759 ((equal (char-after) ?\ ) (forward-char 1))))))
5761 (defun org-reduced-level (l)
5762 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5764 (defun org-get-legal-level (level &optional change)
5765 "Rectify a level change under the influence of `org-odd-levels-only'
5766 LEVEL is a current level, CHANGE is by how much the level should be
5767 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5768 even level numbers will become the next higher odd number."
5769 (if org-odd-levels-only
5770 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5771 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5772 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5773 (max 1 (+ level change))))
5775 (defun org-promote ()
5776 "Promote the current heading higher up the tree.
5777 If the region is active in `transient-mark-mode', promote all headings
5778 in the region."
5779 (org-back-to-heading t)
5780 (let* ((level (save-match-data (funcall outline-level)))
5781 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5782 (diff (abs (- level (length up-head) -1))))
5783 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5784 (replace-match up-head nil t)
5785 ;; Fixup tag positioning
5786 (and org-auto-align-tags (org-set-tags nil t))
5787 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5789 (defun org-demote ()
5790 "Demote the current heading lower down the tree.
5791 If the region is active in `transient-mark-mode', demote all headings
5792 in the region."
5793 (org-back-to-heading t)
5794 (let* ((level (save-match-data (funcall outline-level)))
5795 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5796 (diff (abs (- level (length down-head) -1))))
5797 (replace-match down-head nil t)
5798 ;; Fixup tag positioning
5799 (and org-auto-align-tags (org-set-tags nil t))
5800 (if org-adapt-indentation (org-fixup-indentation diff))))
5802 (defun org-map-tree (fun)
5803 "Call FUN for every heading underneath the current one."
5804 (org-back-to-heading)
5805 (let ((level (funcall outline-level)))
5806 (save-excursion
5807 (funcall fun)
5808 (while (and (progn
5809 (outline-next-heading)
5810 (> (funcall outline-level) level))
5811 (not (eobp)))
5812 (funcall fun)))))
5814 (defun org-map-region (fun beg end)
5815 "Call FUN for every heading between BEG and END."
5816 (let ((org-ignore-region t))
5817 (save-excursion
5818 (setq end (copy-marker end))
5819 (goto-char beg)
5820 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5821 (< (point) end))
5822 (funcall fun))
5823 (while (and (progn
5824 (outline-next-heading)
5825 (< (point) end))
5826 (not (eobp)))
5827 (funcall fun)))))
5829 (defun org-fixup-indentation (diff)
5830 "Change the indentation in the current entry by DIFF
5831 However, if any line in the current entry has no indentation, or if it
5832 would end up with no indentation after the change, nothing at all is done."
5833 (save-excursion
5834 (let ((end (save-excursion (outline-next-heading)
5835 (point-marker)))
5836 (prohibit (if (> diff 0)
5837 "^\\S-"
5838 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5839 col)
5840 (unless (save-excursion (end-of-line 1)
5841 (re-search-forward prohibit end t))
5842 (while (re-search-forward "^[ \t]+" end t)
5843 (goto-char (match-end 0))
5844 (setq col (current-column))
5845 (if (< diff 0) (replace-match ""))
5846 (indent-to (+ diff col))))
5847 (move-marker end nil))))
5849 (defun org-convert-to-odd-levels ()
5850 "Convert an org-mode file with all levels allowed to one with odd levels.
5851 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5852 level 5 etc."
5853 (interactive)
5854 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5855 (let ((org-odd-levels-only nil) n)
5856 (save-excursion
5857 (goto-char (point-min))
5858 (while (re-search-forward "^\\*\\*+ " nil t)
5859 (setq n (- (length (match-string 0)) 2))
5860 (while (>= (setq n (1- n)) 0)
5861 (org-demote))
5862 (end-of-line 1))))))
5865 (defun org-convert-to-oddeven-levels ()
5866 "Convert an org-mode file with only odd levels to one with odd and even levels.
5867 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5868 section with an even level, conversion would destroy the structure of the file. An error
5869 is signaled in this case."
5870 (interactive)
5871 (goto-char (point-min))
5872 ;; First check if there are no even levels
5873 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5874 (org-show-context t)
5875 (error "Not all levels are odd in this file. Conversion not possible."))
5876 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5877 (let ((org-odd-levels-only nil) n)
5878 (save-excursion
5879 (goto-char (point-min))
5880 (while (re-search-forward "^\\*\\*+ " nil t)
5881 (setq n (/ (1- (length (match-string 0))) 2))
5882 (while (>= (setq n (1- n)) 0)
5883 (org-promote))
5884 (end-of-line 1))))))
5886 (defun org-tr-level (n)
5887 "Make N odd if required."
5888 (if org-odd-levels-only (1+ (/ n 2)) n))
5890 ;;; Vertical tree motion, cutting and pasting of subtrees
5892 (defun org-move-subtree-up (&optional arg)
5893 "Move the current subtree up past ARG headlines of the same level."
5894 (interactive "p")
5895 (org-move-subtree-down (- (prefix-numeric-value arg))))
5897 (defun org-move-subtree-down (&optional arg)
5898 "Move the current subtree down past ARG headlines of the same level."
5899 (interactive "p")
5900 (setq arg (prefix-numeric-value arg))
5901 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5902 'outline-get-last-sibling))
5903 (ins-point (make-marker))
5904 (cnt (abs arg))
5905 beg end txt folded)
5906 ;; Select the tree
5907 (org-back-to-heading)
5908 (setq beg (point))
5909 (save-match-data
5910 (save-excursion (outline-end-of-heading)
5911 (setq folded (org-invisible-p)))
5912 (outline-end-of-subtree))
5913 (outline-next-heading)
5914 (setq end (point))
5915 ;; Find insertion point, with error handling
5916 (goto-char beg)
5917 (while (> cnt 0)
5918 (or (and (funcall movfunc) (looking-at outline-regexp))
5919 (progn (goto-char beg)
5920 (error "Cannot move past superior level or buffer limit")))
5921 (setq cnt (1- cnt)))
5922 (if (> arg 0)
5923 ;; Moving forward - still need to move over subtree
5924 (progn (outline-end-of-subtree)
5925 (outline-next-heading)
5926 (if (not (or (looking-at (concat "^" outline-regexp))
5927 (bolp)))
5928 (newline))))
5929 (move-marker ins-point (point))
5930 (setq txt (buffer-substring beg end))
5931 (delete-region beg end)
5932 (insert txt)
5933 (or (bolp) (insert "\n"))
5934 (goto-char ins-point)
5935 (if folded (hide-subtree))
5936 (move-marker ins-point nil)))
5938 (defvar org-subtree-clip ""
5939 "Clipboard for cut and paste of subtrees.
5940 This is actually only a copy of the kill, because we use the normal kill
5941 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5943 (defvar org-subtree-clip-folded nil
5944 "Was the last copied subtree folded?
5945 This is used to fold the tree back after pasting.")
5947 (defun org-cut-subtree (&optional n)
5948 "Cut the current subtree into the clipboard.
5949 With prefix arg N, cut this many sequential subtrees.
5950 This is a short-hand for marking the subtree and then cutting it."
5951 (interactive "p")
5952 (org-copy-subtree n 'cut))
5954 (defun org-copy-subtree (&optional n cut)
5955 "Cut the current subtree into the clipboard.
5956 With prefix arg N, cut this many sequential subtrees.
5957 This is a short-hand for marking the subtree and then copying it.
5958 If CUT is non-nil, actually cut the subtree."
5959 (interactive "p")
5960 (let (beg end folded)
5961 (if (interactive-p)
5962 (org-back-to-heading nil) ; take what looks like a subtree
5963 (org-back-to-heading t)) ; take what is really there
5964 (setq beg (point))
5965 (save-match-data
5966 (save-excursion (outline-end-of-heading)
5967 (setq folded (org-invisible-p)))
5968 (condition-case nil
5969 (outline-forward-same-level (1- n))
5970 (error nil))
5971 (org-end-of-subtree t t))
5972 (setq end (point))
5973 (goto-char beg)
5974 (when (> end beg)
5975 (setq org-subtree-clip-folded folded)
5976 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5977 (setq org-subtree-clip (current-kill 0))
5978 (message "%s: Subtree(s) with %d characters"
5979 (if cut "Cut" "Copied")
5980 (length org-subtree-clip)))))
5982 (defun org-paste-subtree (&optional level tree)
5983 "Paste the clipboard as a subtree, with modification of headline level.
5984 The entire subtree is promoted or demoted in order to match a new headline
5985 level. By default, the new level is derived from the visible headings
5986 before and after the insertion point, and taken to be the inferior headline
5987 level of the two. So if the previous visible heading is level 3 and the
5988 next is level 4 (or vice versa), level 4 will be used for insertion.
5989 This makes sure that the subtree remains an independent subtree and does
5990 not swallow low level entries.
5992 You can also force a different level, either by using a numeric prefix
5993 argument, or by inserting the heading marker by hand. For example, if the
5994 cursor is after \"*****\", then the tree will be shifted to level 5.
5996 If you want to insert the tree as is, just use \\[yank].
5998 If optional TREE is given, use this text instead of the kill ring."
5999 (interactive "P")
6000 (unless (org-kill-is-subtree-p tree)
6001 (error
6002 (substitute-command-keys
6003 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6004 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6005 (^re (concat "^\\(" outline-regexp "\\)"))
6006 (re (concat "\\(" outline-regexp "\\)"))
6007 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6009 (old-level (if (string-match ^re txt)
6010 (- (match-end 0) (match-beginning 0) 1)
6011 -1))
6012 (force-level (cond (level (prefix-numeric-value level))
6013 ((string-match
6014 ^re_ (buffer-substring (point-at-bol) (point)))
6015 (- (match-end 1) (match-beginning 1)))
6016 (t nil)))
6017 (previous-level (save-excursion
6018 (condition-case nil
6019 (progn
6020 (outline-previous-visible-heading 1)
6021 (if (looking-at re)
6022 (- (match-end 0) (match-beginning 0) 1)
6024 (error 1))))
6025 (next-level (save-excursion
6026 (condition-case nil
6027 (progn
6028 (or (looking-at outline-regexp)
6029 (outline-next-visible-heading 1))
6030 (if (looking-at re)
6031 (- (match-end 0) (match-beginning 0) 1)
6033 (error 1))))
6034 (new-level (or force-level (max previous-level next-level)))
6035 (shift (if (or (= old-level -1)
6036 (= new-level -1)
6037 (= old-level new-level))
6039 (- new-level old-level)))
6040 (delta (if (> shift 0) -1 1))
6041 (func (if (> shift 0) 'org-demote 'org-promote))
6042 (org-odd-levels-only nil)
6043 beg end)
6044 ;; Remove the forced level indicator
6045 (if force-level
6046 (delete-region (point-at-bol) (point)))
6047 ;; Paste
6048 (beginning-of-line 1)
6049 (setq beg (point))
6050 (insert txt)
6051 (unless (string-match "\n[ \t]*\\'" txt) (insert "\n"))
6052 (setq end (point))
6053 (goto-char beg)
6054 ;; Shift if necessary
6055 (unless (= shift 0)
6056 (save-restriction
6057 (narrow-to-region beg end)
6058 (while (not (= shift 0))
6059 (org-map-region func (point-min) (point-max))
6060 (setq shift (+ delta shift)))
6061 (goto-char (point-min))))
6062 (when (interactive-p)
6063 (message "Clipboard pasted as level %d subtree" new-level))
6064 (if (and kill-ring
6065 (eq org-subtree-clip (current-kill 0))
6066 org-subtree-clip-folded)
6067 ;; The tree was folded before it was killed/copied
6068 (hide-subtree))))
6070 (defun org-kill-is-subtree-p (&optional txt)
6071 "Check if the current kill is an outline subtree, or a set of trees.
6072 Returns nil if kill does not start with a headline, or if the first
6073 headline level is not the largest headline level in the tree.
6074 So this will actually accept several entries of equal levels as well,
6075 which is OK for `org-paste-subtree'.
6076 If optional TXT is given, check this string instead of the current kill."
6077 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6078 (start-level (and kill
6079 (string-match (concat "\\`" org-outline-regexp) kill)
6080 (- (match-end 0) (match-beginning 0) 1)))
6081 (re (concat "^" org-outline-regexp))
6082 (start 1))
6083 (if (not start-level)
6084 (progn
6085 nil) ;; does not even start with a heading
6086 (catch 'exit
6087 (while (setq start (string-match re kill (1+ start)))
6088 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6089 (throw 'exit nil)))
6090 t))))
6092 (defun org-narrow-to-subtree ()
6093 "Narrow buffer to the current subtree."
6094 (interactive)
6095 (save-excursion
6096 (narrow-to-region
6097 (progn (org-back-to-heading) (point))
6098 (progn (org-end-of-subtree t t) (point)))))
6101 ;;; Outline Sorting
6103 (defun org-sort (with-case)
6104 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6105 Optional argument WITH-CASE means sort case-sensitively."
6106 (interactive "P")
6107 (if (org-at-table-p)
6108 (org-call-with-arg 'org-table-sort-lines with-case)
6109 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6111 (defvar org-priority-regexp) ; defined later in the file
6113 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6114 "Sort entries on a certain level of an outline tree.
6115 If there is an active region, the entries in the region are sorted.
6116 Else, if the cursor is before the first entry, sort the top-level items.
6117 Else, the children of the entry at point are sorted.
6119 Sorting can be alphabetically, numerically, and by date/time as given by
6120 the first time stamp in the entry. The command prompts for the sorting
6121 type unless it has been given to the function through the SORTING-TYPE
6122 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6123 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6124 called with point at the beginning of the record. It must return either
6125 a string or a number that should serve as the sorting key for that record.
6127 Comparing entries ignores case by default. However, with an optional argument
6128 WITH-CASE, the sorting considers case as well."
6129 (interactive "P")
6130 (let ((case-func (if with-case 'identity 'downcase))
6131 start beg end stars re re2
6132 txt what tmp plain-list-p)
6133 ;; Find beginning and end of region to sort
6134 (cond
6135 ((org-region-active-p)
6136 ;; we will sort the region
6137 (setq end (region-end)
6138 what "region")
6139 (goto-char (region-beginning))
6140 (if (not (org-on-heading-p)) (outline-next-heading))
6141 (setq start (point)))
6142 ((org-at-item-p)
6143 ;; we will sort this plain list
6144 (org-beginning-of-item-list) (setq start (point))
6145 (org-end-of-item-list) (setq end (point))
6146 (goto-char start)
6147 (setq plain-list-p t
6148 what "plain list"))
6149 ((or (org-on-heading-p)
6150 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6151 ;; we will sort the children of the current headline
6152 (org-back-to-heading)
6153 (setq start (point) end (org-end-of-subtree) what "children")
6154 (goto-char start)
6155 (show-subtree)
6156 (outline-next-heading))
6158 ;; we will sort the top-level entries in this file
6159 (goto-char (point-min))
6160 (or (org-on-heading-p) (outline-next-heading))
6161 (setq start (point) end (point-max) what "top-level")
6162 (goto-char start)
6163 (show-all)))
6165 (setq beg (point))
6166 (if (>= beg end) (error "Nothing to sort"))
6168 (unless plain-list-p
6169 (looking-at "\\(\\*+\\)")
6170 (setq stars (match-string 1)
6171 re (concat "^" (regexp-quote stars) " +")
6172 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6173 txt (buffer-substring beg end))
6174 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6175 (if (and (not (equal stars "*")) (string-match re2 txt))
6176 (error "Region to sort contains a level above the first entry")))
6178 (unless sorting-type
6179 (message
6180 (if plain-list-p
6181 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6182 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6183 what)
6184 (setq sorting-type (read-char-exclusive))
6186 (and (= (downcase sorting-type) ?f)
6187 (setq getkey-func
6188 (completing-read "Sort using function: "
6189 obarray 'fboundp t nil nil))
6190 (setq getkey-func (intern getkey-func)))
6192 (and (= (downcase sorting-type) ?r)
6193 (setq property
6194 (completing-read "Property: "
6195 (mapcar 'list (org-buffer-property-keys t))
6196 nil t))))
6198 (message "Sorting entries...")
6200 (save-restriction
6201 (narrow-to-region start end)
6203 (let ((dcst (downcase sorting-type))
6204 (now (current-time)))
6205 (sort-subr
6206 (/= dcst sorting-type)
6207 ;; This function moves to the beginning character of the "record" to
6208 ;; be sorted.
6209 (if plain-list-p
6210 (lambda nil
6211 (if (org-at-item-p) t (goto-char (point-max))))
6212 (lambda nil
6213 (if (re-search-forward re nil t)
6214 (goto-char (match-beginning 0))
6215 (goto-char (point-max)))))
6216 ;; This function moves to the last character of the "record" being
6217 ;; sorted.
6218 (if plain-list-p
6219 'org-end-of-item
6220 (lambda nil
6221 (save-match-data
6222 (condition-case nil
6223 (outline-forward-same-level 1)
6224 (error
6225 (goto-char (point-max)))))))
6227 ;; This function returns the value that gets sorted against.
6228 (if plain-list-p
6229 (lambda nil
6230 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6231 (cond
6232 ((= dcst ?n)
6233 (string-to-number (buffer-substring (match-end 0)
6234 (line-end-position))))
6235 ((= dcst ?a)
6236 (buffer-substring (match-end 0) (line-end-position)))
6237 ((= dcst ?t)
6238 (if (re-search-forward org-ts-regexp
6239 (line-end-position) t)
6240 (org-time-string-to-time (match-string 0))
6241 now))
6242 ((= dcst ?f)
6243 (if getkey-func
6244 (progn
6245 (setq tmp (funcall getkey-func))
6246 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6247 tmp)
6248 (error "Invalid key function `%s'" getkey-func)))
6249 (t (error "Invalid sorting type `%c'" sorting-type)))))
6250 (lambda nil
6251 (cond
6252 ((= dcst ?n)
6253 (if (looking-at outline-regexp)
6254 (string-to-number (buffer-substring (match-end 0)
6255 (line-end-position)))
6256 nil))
6257 ((= dcst ?a)
6258 (funcall case-func (buffer-substring (line-beginning-position)
6259 (line-end-position))))
6260 ((= dcst ?t)
6261 (if (re-search-forward org-ts-regexp
6262 (save-excursion
6263 (forward-line 2)
6264 (point)) t)
6265 (org-time-string-to-time (match-string 0))
6266 now))
6267 ((= dcst ?p)
6268 (if (re-search-forward org-priority-regexp (line-end-position) t)
6269 (string-to-char (match-string 2))
6270 org-default-priority))
6271 ((= dcst ?r)
6272 (or (org-entry-get nil property) ""))
6273 ((= dcst ?f)
6274 (if getkey-func
6275 (progn
6276 (setq tmp (funcall getkey-func))
6277 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6278 tmp)
6279 (error "Invalid key function `%s'" getkey-func)))
6280 (t (error "Invalid sorting type `%c'" sorting-type)))))
6282 (cond
6283 ((= dcst ?a) 'string<)
6284 ((= dcst ?t) 'time-less-p)
6285 (t nil)))))
6286 (message "Sorting entries...done")))
6288 (defun org-do-sort (table what &optional with-case sorting-type)
6289 "Sort TABLE of WHAT according to SORTING-TYPE.
6290 The user will be prompted for the SORTING-TYPE if the call to this
6291 function does not specify it. WHAT is only for the prompt, to indicate
6292 what is being sorted. The sorting key will be extracted from
6293 the car of the elements of the table.
6294 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6295 (unless sorting-type
6296 (message
6297 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6298 what)
6299 (setq sorting-type (read-char-exclusive)))
6300 (let ((dcst (downcase sorting-type))
6301 extractfun comparefun)
6302 ;; Define the appropriate functions
6303 (cond
6304 ((= dcst ?n)
6305 (setq extractfun 'string-to-number
6306 comparefun (if (= dcst sorting-type) '< '>)))
6307 ((= dcst ?a)
6308 (setq extractfun (if with-case 'identity 'downcase)
6309 comparefun (if (= dcst sorting-type)
6310 'string<
6311 (lambda (a b) (and (not (string< a b))
6312 (not (string= a b)))))))
6313 ((= dcst ?t)
6314 (setq extractfun
6315 (lambda (x)
6316 (if (string-match org-ts-regexp x)
6317 (time-to-seconds
6318 (org-time-string-to-time (match-string 0 x)))
6320 comparefun (if (= dcst sorting-type) '< '>)))
6321 (t (error "Invalid sorting type `%c'" sorting-type)))
6323 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6324 table)
6325 (lambda (a b) (funcall comparefun (car a) (car b))))))
6327 ;;;; Plain list items, including checkboxes
6329 ;;; Plain list items
6331 (defun org-at-item-p ()
6332 "Is point in a line starting a hand-formatted item?"
6333 (let ((llt org-plain-list-ordered-item-terminator))
6334 (save-excursion
6335 (goto-char (point-at-bol))
6336 (looking-at
6337 (cond
6338 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6339 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6340 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6341 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6343 (defun org-in-item-p ()
6344 "It the cursor inside a plain list item.
6345 Does not have to be the first line."
6346 (save-excursion
6347 (condition-case nil
6348 (progn
6349 (org-beginning-of-item)
6350 (org-at-item-p)
6352 (error nil))))
6354 (defun org-insert-item (&optional checkbox)
6355 "Insert a new item at the current level.
6356 Return t when things worked, nil when we are not in an item."
6357 (when (save-excursion
6358 (condition-case nil
6359 (progn
6360 (org-beginning-of-item)
6361 (org-at-item-p)
6362 (if (org-invisible-p) (error "Invisible item"))
6364 (error nil)))
6365 (let* ((bul (match-string 0))
6366 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6367 (match-end 0)))
6368 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6369 pos)
6370 (cond
6371 ((and (org-at-item-p) (<= (point) eow))
6372 ;; before the bullet
6373 (beginning-of-line 1)
6374 (open-line (if blank 2 1)))
6375 ((<= (point) eow)
6376 (beginning-of-line 1))
6377 (t (newline (if blank 2 1))))
6378 (insert bul (if checkbox "[ ]" ""))
6379 (just-one-space)
6380 (setq pos (point))
6381 (end-of-line 1)
6382 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6383 (org-maybe-renumber-ordered-list)
6384 (and checkbox (org-update-checkbox-count-maybe))
6387 ;;; Checkboxes
6389 (defun org-at-item-checkbox-p ()
6390 "Is point at a line starting a plain-list item with a checklet?"
6391 (and (org-at-item-p)
6392 (save-excursion
6393 (goto-char (match-end 0))
6394 (skip-chars-forward " \t")
6395 (looking-at "\\[[- X]\\]"))))
6397 (defun org-toggle-checkbox (&optional arg)
6398 "Toggle the checkbox in the current line."
6399 (interactive "P")
6400 (catch 'exit
6401 (let (beg end status (firstnew 'unknown))
6402 (cond
6403 ((org-region-active-p)
6404 (setq beg (region-beginning) end (region-end)))
6405 ((org-on-heading-p)
6406 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6407 ((org-at-item-checkbox-p)
6408 (save-excursion
6409 (replace-match
6410 (cond (arg "[-]")
6411 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6412 (t "[ ]"))
6413 t t))
6414 (throw 'exit t))
6415 (t (error "Not at a checkbox or heading, and no active region")))
6416 (save-excursion
6417 (goto-char beg)
6418 (while (< (point) end)
6419 (when (org-at-item-checkbox-p)
6420 (setq status (equal (match-string 0) "[X]"))
6421 (when (eq firstnew 'unknown)
6422 (setq firstnew (not status)))
6423 (replace-match
6424 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6425 (beginning-of-line 2)))))
6426 (org-update-checkbox-count-maybe))
6428 (defun org-update-checkbox-count-maybe ()
6429 "Update checkbox statistics unless turned off by user."
6430 (when org-provide-checkbox-statistics
6431 (org-update-checkbox-count)))
6433 (defun org-update-checkbox-count (&optional all)
6434 "Update the checkbox statistics in the current section.
6435 This will find all statistic cookies like [57%] and [6/12] and update them
6436 with the current numbers. With optional prefix argument ALL, do this for
6437 the whole buffer."
6438 (interactive "P")
6439 (save-excursion
6440 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6441 (beg (condition-case nil
6442 (progn (outline-back-to-heading) (point))
6443 (error (point-min))))
6444 (end (move-marker (make-marker)
6445 (progn (outline-next-heading) (point))))
6446 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6447 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6448 b1 e1 f1 c-on c-off lim (cstat 0))
6449 (when all
6450 (goto-char (point-min))
6451 (outline-next-heading)
6452 (setq beg (point) end (point-max)))
6453 (goto-char beg)
6454 (while (re-search-forward re end t)
6455 (setq cstat (1+ cstat)
6456 b1 (match-beginning 0)
6457 e1 (match-end 0)
6458 f1 (match-beginning 1)
6459 lim (cond
6460 ((org-on-heading-p) (outline-next-heading) (point))
6461 ((org-at-item-p) (org-end-of-item) (point))
6462 (t nil))
6463 c-on 0 c-off 0)
6464 (goto-char e1)
6465 (when lim
6466 (while (re-search-forward re-box lim t)
6467 (if (member (match-string 2) '("[ ]" "[-]"))
6468 (setq c-off (1+ c-off))
6469 (setq c-on (1+ c-on))))
6470 ; (delete-region b1 e1)
6471 (goto-char b1)
6472 (insert (if f1
6473 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6474 (format "[%d/%d]" c-on (+ c-on c-off))))
6475 (and (looking-at "\\[.*?\\]")
6476 (replace-match ""))))
6477 (when (interactive-p)
6478 (message "Checkbox satistics updated %s (%d places)"
6479 (if all "in entire file" "in current outline entry") cstat)))))
6481 (defun org-get-checkbox-statistics-face ()
6482 "Select the face for checkbox statistics.
6483 The face will be `org-done' when all relevant boxes are checked. Otherwise
6484 it will be `org-todo'."
6485 (if (match-end 1)
6486 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6487 (if (and (> (match-end 2) (match-beginning 2))
6488 (equal (match-string 2) (match-string 3)))
6489 'org-done
6490 'org-todo)))
6492 (defun org-get-indentation (&optional line)
6493 "Get the indentation of the current line, interpreting tabs.
6494 When LINE is given, assume it represents a line and compute its indentation."
6495 (if line
6496 (if (string-match "^ *" (org-remove-tabs line))
6497 (match-end 0))
6498 (save-excursion
6499 (beginning-of-line 1)
6500 (skip-chars-forward " \t")
6501 (current-column))))
6503 (defun org-remove-tabs (s &optional width)
6504 "Replace tabulators in S with spaces.
6505 Assumes that s is a single line, starting in column 0."
6506 (setq width (or width tab-width))
6507 (while (string-match "\t" s)
6508 (setq s (replace-match
6509 (make-string
6510 (- (* width (/ (+ (match-beginning 0) width) width))
6511 (match-beginning 0)) ?\ )
6512 t t s)))
6515 (defun org-fix-indentation (line ind)
6516 "Fix indentation in LINE.
6517 IND is a cons cell with target and minimum indentation.
6518 If the current indenation in LINE is smaller than the minimum,
6519 leave it alone. If it is larger than ind, set it to the target."
6520 (let* ((l (org-remove-tabs line))
6521 (i (org-get-indentation l))
6522 (i1 (car ind)) (i2 (cdr ind)))
6523 (if (>= i i2) (setq l (substring line i2)))
6524 (if (> i1 0)
6525 (concat (make-string i1 ?\ ) l)
6526 l)))
6528 (defcustom org-empty-line-terminates-plain-lists nil
6529 "Non-nil means, an empty line ends all plain list levels.
6530 When nil, empty lines are part of the preceeding item."
6531 :group 'org-plain-lists
6532 :type 'boolean)
6534 (defun org-beginning-of-item ()
6535 "Go to the beginning of the current hand-formatted item.
6536 If the cursor is not in an item, throw an error."
6537 (interactive)
6538 (let ((pos (point))
6539 (limit (save-excursion
6540 (condition-case nil
6541 (progn
6542 (org-back-to-heading)
6543 (beginning-of-line 2) (point))
6544 (error (point-min)))))
6545 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6546 ind ind1)
6547 (if (org-at-item-p)
6548 (beginning-of-line 1)
6549 (beginning-of-line 1)
6550 (skip-chars-forward " \t")
6551 (setq ind (current-column))
6552 (if (catch 'exit
6553 (while t
6554 (beginning-of-line 0)
6555 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6557 (if (looking-at "[ \t]*$")
6558 (setq ind1 ind-empty)
6559 (skip-chars-forward " \t")
6560 (setq ind1 (current-column)))
6561 (if (< ind1 ind)
6562 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6564 (goto-char pos)
6565 (error "Not in an item")))))
6567 (defun org-end-of-item ()
6568 "Go to the end of the current hand-formatted item.
6569 If the cursor is not in an item, throw an error."
6570 (interactive)
6571 (let* ((pos (point))
6572 ind1
6573 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6574 (limit (save-excursion (outline-next-heading) (point)))
6575 (ind (save-excursion
6576 (org-beginning-of-item)
6577 (skip-chars-forward " \t")
6578 (current-column)))
6579 (end (catch 'exit
6580 (while t
6581 (beginning-of-line 2)
6582 (if (eobp) (throw 'exit (point)))
6583 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6584 (if (looking-at "[ \t]*$")
6585 (setq ind1 ind-empty)
6586 (skip-chars-forward " \t")
6587 (setq ind1 (current-column)))
6588 (if (<= ind1 ind)
6589 (throw 'exit (point-at-bol)))))))
6590 (if end
6591 (goto-char end)
6592 (goto-char pos)
6593 (error "Not in an item"))))
6595 (defun org-next-item ()
6596 "Move to the beginning of the next item in the current plain list.
6597 Error if not at a plain list, or if this is the last item in the list."
6598 (interactive)
6599 (let (ind ind1 (pos (point)))
6600 (org-beginning-of-item)
6601 (setq ind (org-get-indentation))
6602 (org-end-of-item)
6603 (setq ind1 (org-get-indentation))
6604 (unless (and (org-at-item-p) (= ind ind1))
6605 (goto-char pos)
6606 (error "On last item"))))
6608 (defun org-previous-item ()
6609 "Move to the beginning of the previous item in the current plain list.
6610 Error if not at a plain list, or if this is the first item in the list."
6611 (interactive)
6612 (let (beg ind ind1 (pos (point)))
6613 (org-beginning-of-item)
6614 (setq beg (point))
6615 (setq ind (org-get-indentation))
6616 (goto-char beg)
6617 (catch 'exit
6618 (while t
6619 (beginning-of-line 0)
6620 (if (looking-at "[ \t]*$")
6622 (if (<= (setq ind1 (org-get-indentation)) ind)
6623 (throw 'exit t)))))
6624 (condition-case nil
6625 (if (or (not (org-at-item-p))
6626 (< ind1 (1- ind)))
6627 (error "")
6628 (org-beginning-of-item))
6629 (error (goto-char pos)
6630 (error "On first item")))))
6632 (defun org-move-item-down ()
6633 "Move the plain list item at point down, i.e. swap with following item.
6634 Subitems (items with larger indentation) are considered part of the item,
6635 so this really moves item trees."
6636 (interactive)
6637 (let (beg end ind ind1 (pos (point)) txt)
6638 (org-beginning-of-item)
6639 (setq beg (point))
6640 (setq ind (org-get-indentation))
6641 (org-end-of-item)
6642 (setq end (point))
6643 (setq ind1 (org-get-indentation))
6644 (if (and (org-at-item-p) (= ind ind1))
6645 (progn
6646 (org-end-of-item)
6647 (setq txt (buffer-substring beg end))
6648 (save-excursion
6649 (delete-region beg end))
6650 (setq pos (point))
6651 (insert txt)
6652 (goto-char pos)
6653 (org-maybe-renumber-ordered-list))
6654 (goto-char pos)
6655 (error "Cannot move this item further down"))))
6657 (defun org-move-item-up (arg)
6658 "Move the plain list item at point up, i.e. swap with previous item.
6659 Subitems (items with larger indentation) are considered part of the item,
6660 so this really moves item trees."
6661 (interactive "p")
6662 (let (beg end ind ind1 (pos (point)) txt)
6663 (org-beginning-of-item)
6664 (setq beg (point))
6665 (setq ind (org-get-indentation))
6666 (org-end-of-item)
6667 (setq end (point))
6668 (goto-char beg)
6669 (catch 'exit
6670 (while t
6671 (beginning-of-line 0)
6672 (if (looking-at "[ \t]*$")
6673 (if org-empty-line-terminates-plain-lists
6674 (progn
6675 (goto-char pos)
6676 (error "Cannot move this item further up"))
6677 nil)
6678 (if (<= (setq ind1 (org-get-indentation)) ind)
6679 (throw 'exit t)))))
6680 (condition-case nil
6681 (org-beginning-of-item)
6682 (error (goto-char beg)
6683 (error "Cannot move this item further up")))
6684 (setq ind1 (org-get-indentation))
6685 (if (and (org-at-item-p) (= ind ind1))
6686 (progn
6687 (setq txt (buffer-substring beg end))
6688 (save-excursion
6689 (delete-region beg end))
6690 (setq pos (point))
6691 (insert txt)
6692 (goto-char pos)
6693 (org-maybe-renumber-ordered-list))
6694 (goto-char pos)
6695 (error "Cannot move this item further up"))))
6697 (defun org-maybe-renumber-ordered-list ()
6698 "Renumber the ordered list at point if setup allows it.
6699 This tests the user option `org-auto-renumber-ordered-lists' before
6700 doing the renumbering."
6701 (interactive)
6702 (when (and org-auto-renumber-ordered-lists
6703 (org-at-item-p))
6704 (if (match-beginning 3)
6705 (org-renumber-ordered-list 1)
6706 (org-fix-bullet-type))))
6708 (defun org-maybe-renumber-ordered-list-safe ()
6709 (condition-case nil
6710 (save-excursion
6711 (org-maybe-renumber-ordered-list))
6712 (error nil)))
6714 (defun org-cycle-list-bullet (&optional which)
6715 "Cycle through the different itemize/enumerate bullets.
6716 This cycle the entire list level through the sequence:
6718 `-' -> `+' -> `*' -> `1.' -> `1)'
6720 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6721 0 meand `-', 1 means `+' etc."
6722 (interactive "P")
6723 (org-preserve-lc
6724 (org-beginning-of-item-list)
6725 (org-at-item-p)
6726 (beginning-of-line 1)
6727 (let ((current (match-string 0))
6728 (prevp (eq which 'previous))
6729 new)
6730 (setq new (cond
6731 ((and (numberp which)
6732 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6733 ((string-match "-" current) (if prevp "1)" "+"))
6734 ((string-match "\\+" current)
6735 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6736 ((string-match "\\*" current) (if prevp "+" "1."))
6737 ((string-match "\\." current) (if prevp "*" "1)"))
6738 ((string-match ")" current) (if prevp "1." "-"))
6739 (t (error "This should not happen"))))
6740 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6741 (org-fix-bullet-type)
6742 (org-maybe-renumber-ordered-list))))
6744 (defun org-get-string-indentation (s)
6745 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6746 (let ((n -1) (i 0) (w tab-width) c)
6747 (catch 'exit
6748 (while (< (setq n (1+ n)) (length s))
6749 (setq c (aref s n))
6750 (cond ((= c ?\ ) (setq i (1+ i)))
6751 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6752 (t (throw 'exit t)))))
6755 (defun org-renumber-ordered-list (arg)
6756 "Renumber an ordered plain list.
6757 Cursor needs to be in the first line of an item, the line that starts
6758 with something like \"1.\" or \"2)\"."
6759 (interactive "p")
6760 (unless (and (org-at-item-p)
6761 (match-beginning 3))
6762 (error "This is not an ordered list"))
6763 (let ((line (org-current-line))
6764 (col (current-column))
6765 (ind (org-get-string-indentation
6766 (buffer-substring (point-at-bol) (match-beginning 3))))
6767 ;; (term (substring (match-string 3) -1))
6768 ind1 (n (1- arg))
6769 fmt)
6770 ;; find where this list begins
6771 (org-beginning-of-item-list)
6772 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6773 (setq fmt (concat "%d" (match-string 1)))
6774 (beginning-of-line 0)
6775 ;; walk forward and replace these numbers
6776 (catch 'exit
6777 (while t
6778 (catch 'next
6779 (beginning-of-line 2)
6780 (if (eobp) (throw 'exit nil))
6781 (if (looking-at "[ \t]*$") (throw 'next nil))
6782 (skip-chars-forward " \t") (setq ind1 (current-column))
6783 (if (> ind1 ind) (throw 'next t))
6784 (if (< ind1 ind) (throw 'exit t))
6785 (if (not (org-at-item-p)) (throw 'exit nil))
6786 (delete-region (match-beginning 2) (match-end 2))
6787 (goto-char (match-beginning 2))
6788 (insert (format fmt (setq n (1+ n)))))))
6789 (goto-line line)
6790 (move-to-column col)))
6792 (defun org-fix-bullet-type ()
6793 "Make sure all items in this list have the same bullet as the firsst item."
6794 (interactive)
6795 (unless (org-at-item-p) (error "This is not a list"))
6796 (let ((line (org-current-line))
6797 (col (current-column))
6798 (ind (current-indentation))
6799 ind1 bullet)
6800 ;; find where this list begins
6801 (org-beginning-of-item-list)
6802 (beginning-of-line 1)
6803 ;; find out what the bullet type is
6804 (looking-at "[ \t]*\\(\\S-+\\)")
6805 (setq bullet (match-string 1))
6806 ;; walk forward and replace these numbers
6807 (beginning-of-line 0)
6808 (catch 'exit
6809 (while t
6810 (catch 'next
6811 (beginning-of-line 2)
6812 (if (eobp) (throw 'exit nil))
6813 (if (looking-at "[ \t]*$") (throw 'next nil))
6814 (skip-chars-forward " \t") (setq ind1 (current-column))
6815 (if (> ind1 ind) (throw 'next t))
6816 (if (< ind1 ind) (throw 'exit t))
6817 (if (not (org-at-item-p)) (throw 'exit nil))
6818 (skip-chars-forward " \t")
6819 (looking-at "\\S-+")
6820 (replace-match bullet))))
6821 (goto-line line)
6822 (move-to-column col)
6823 (if (string-match "[0-9]" bullet)
6824 (org-renumber-ordered-list 1))))
6826 (defun org-beginning-of-item-list ()
6827 "Go to the beginning of the current item list.
6828 I.e. to the first item in this list."
6829 (interactive)
6830 (org-beginning-of-item)
6831 (let ((pos (point-at-bol))
6832 (ind (org-get-indentation))
6833 ind1)
6834 ;; find where this list begins
6835 (catch 'exit
6836 (while t
6837 (catch 'next
6838 (beginning-of-line 0)
6839 (if (looking-at "[ \t]*$")
6840 (throw (if (bobp) 'exit 'next) t))
6841 (skip-chars-forward " \t") (setq ind1 (current-column))
6842 (if (or (< ind1 ind)
6843 (and (= ind1 ind)
6844 (not (org-at-item-p)))
6845 (bobp))
6846 (throw 'exit t)
6847 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6848 (goto-char pos)))
6851 (defun org-end-of-item-list ()
6852 "Go to the end of the current item list.
6853 I.e. to the text after the last item."
6854 (interactive)
6855 (org-beginning-of-item)
6856 (let ((pos (point-at-bol))
6857 (ind (org-get-indentation))
6858 ind1)
6859 ;; find where this list begins
6860 (catch 'exit
6861 (while t
6862 (catch 'next
6863 (beginning-of-line 2)
6864 (if (looking-at "[ \t]*$")
6865 (throw (if (eobp) 'exit 'next) t))
6866 (skip-chars-forward " \t") (setq ind1 (current-column))
6867 (if (or (< ind1 ind)
6868 (and (= ind1 ind)
6869 (not (org-at-item-p)))
6870 (eobp))
6871 (progn
6872 (setq pos (point-at-bol))
6873 (throw 'exit t))))))
6874 (goto-char pos)))
6877 (defvar org-last-indent-begin-marker (make-marker))
6878 (defvar org-last-indent-end-marker (make-marker))
6880 (defun org-outdent-item (arg)
6881 "Outdent a local list item."
6882 (interactive "p")
6883 (org-indent-item (- arg)))
6885 (defun org-indent-item (arg)
6886 "Indent a local list item."
6887 (interactive "p")
6888 (unless (org-at-item-p)
6889 (error "Not on an item"))
6890 (save-excursion
6891 (let (beg end ind ind1 tmp delta ind-down ind-up)
6892 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6893 (setq beg org-last-indent-begin-marker
6894 end org-last-indent-end-marker)
6895 (org-beginning-of-item)
6896 (setq beg (move-marker org-last-indent-begin-marker (point)))
6897 (org-end-of-item)
6898 (setq end (move-marker org-last-indent-end-marker (point))))
6899 (goto-char beg)
6900 (setq tmp (org-item-indent-positions)
6901 ind (car tmp)
6902 ind-down (nth 2 tmp)
6903 ind-up (nth 1 tmp)
6904 delta (if (> arg 0)
6905 (if ind-down (- ind-down ind) 2)
6906 (if ind-up (- ind-up ind) -2)))
6907 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6908 (while (< (point) end)
6909 (beginning-of-line 1)
6910 (skip-chars-forward " \t") (setq ind1 (current-column))
6911 (delete-region (point-at-bol) (point))
6912 (or (eolp) (indent-to-column (+ ind1 delta)))
6913 (beginning-of-line 2))))
6914 (org-fix-bullet-type)
6915 (org-maybe-renumber-ordered-list-safe)
6916 (save-excursion
6917 (beginning-of-line 0)
6918 (condition-case nil (org-beginning-of-item) (error nil))
6919 (org-maybe-renumber-ordered-list-safe)))
6921 (defun org-item-indent-positions ()
6922 "Return indentation for plain list items.
6923 This returns a list with three values: The current indentation, the
6924 parent indentation and the indentation a child should habe.
6925 Assumes cursor in item line."
6926 (let* ((bolpos (point-at-bol))
6927 (ind (org-get-indentation))
6928 ind-down ind-up pos)
6929 (save-excursion
6930 (org-beginning-of-item-list)
6931 (skip-chars-backward "\n\r \t")
6932 (when (org-in-item-p)
6933 (org-beginning-of-item)
6934 (setq ind-up (org-get-indentation))))
6935 (setq pos (point))
6936 (save-excursion
6937 (cond
6938 ((and (condition-case nil (progn (org-previous-item) t)
6939 (error nil))
6940 (or (forward-char 1) t)
6941 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6942 (setq ind-down (org-get-indentation)))
6943 ((and (goto-char pos)
6944 (org-at-item-p))
6945 (goto-char (match-end 0))
6946 (skip-chars-forward " \t")
6947 (setq ind-down (current-column)))))
6948 (list ind ind-up ind-down)))
6950 ;;; The orgstruct minor mode
6952 ;; Define a minor mode which can be used in other modes in order to
6953 ;; integrate the org-mode structure editing commands.
6955 ;; This is really a hack, because the org-mode structure commands use
6956 ;; keys which normally belong to the major mode. Here is how it
6957 ;; works: The minor mode defines all the keys necessary to operate the
6958 ;; structure commands, but wraps the commands into a function which
6959 ;; tests if the cursor is currently at a headline or a plain list
6960 ;; item. If that is the case, the structure command is used,
6961 ;; temporarily setting many Org-mode variables like regular
6962 ;; expressions for filling etc. However, when any of those keys is
6963 ;; used at a different location, function uses `key-binding' to look
6964 ;; up if the key has an associated command in another currently active
6965 ;; keymap (minor modes, major mode, global), and executes that
6966 ;; command. There might be problems if any of the keys is otherwise
6967 ;; used as a prefix key.
6969 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6970 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6971 ;; addresses this by checking explicitly for both bindings.
6973 (defvar orgstruct-mode-map (make-sparse-keymap)
6974 "Keymap for the minor `orgstruct-mode'.")
6976 (defvar org-local-vars nil
6977 "List of local variables, for use by `orgstruct-mode'")
6979 ;;;###autoload
6980 (define-minor-mode orgstruct-mode
6981 "Toggle the minor more `orgstruct-mode'.
6982 This mode is for using Org-mode structure commands in other modes.
6983 The following key behave as if Org-mode was active, if the cursor
6984 is on a headline, or on a plain list item (both in the definition
6985 of Org-mode).
6987 M-up Move entry/item up
6988 M-down Move entry/item down
6989 M-left Promote
6990 M-right Demote
6991 M-S-up Move entry/item up
6992 M-S-down Move entry/item down
6993 M-S-left Promote subtree
6994 M-S-right Demote subtree
6995 M-q Fill paragraph and items like in Org-mode
6996 C-c ^ Sort entries
6997 C-c - Cycle list bullet
6998 TAB Cycle item visibility
6999 M-RET Insert new heading/item
7000 S-M-RET Insert new TODO heading / Chekbox item
7001 C-c C-c Set tags / toggle checkbox"
7002 nil " OrgStruct" nil
7003 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7005 ;;;###autoload
7006 (defun turn-on-orgstruct ()
7007 "Unconditionally turn on `orgstruct-mode'."
7008 (orgstruct-mode 1))
7010 ;;;###autoload
7011 (defun turn-on-orgstruct++ ()
7012 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7013 In addition to setting orgstruct-mode, this also exports all indentation and
7014 autofilling variables from org-mode into the buffer. Note that turning
7015 off orgstruct-mode will *not* remove these additonal settings."
7016 (orgstruct-mode 1)
7017 (let (var val)
7018 (mapc
7019 (lambda (x)
7020 (when (string-match
7021 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7022 (symbol-name (car x)))
7023 (setq var (car x) val (nth 1 x))
7024 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7025 org-local-vars)))
7027 (defun orgstruct-error ()
7028 "Error when there is no default binding for a structure key."
7029 (interactive)
7030 (error "This key is has no function outside structure elements"))
7032 (defun orgstruct-setup ()
7033 "Setup orgstruct keymaps."
7034 (let ((nfunc 0)
7035 (bindings
7036 (list
7037 '([(meta up)] org-metaup)
7038 '([(meta down)] org-metadown)
7039 '([(meta left)] org-metaleft)
7040 '([(meta right)] org-metaright)
7041 '([(meta shift up)] org-shiftmetaup)
7042 '([(meta shift down)] org-shiftmetadown)
7043 '([(meta shift left)] org-shiftmetaleft)
7044 '([(meta shift right)] org-shiftmetaright)
7045 '([(shift up)] org-shiftup)
7046 '([(shift down)] org-shiftdown)
7047 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7048 '("\M-q" fill-paragraph)
7049 '("\C-c^" org-sort)
7050 '("\C-c-" org-cycle-list-bullet)))
7051 elt key fun cmd)
7052 (while (setq elt (pop bindings))
7053 (setq nfunc (1+ nfunc))
7054 (setq key (org-key (car elt))
7055 fun (nth 1 elt)
7056 cmd (orgstruct-make-binding fun nfunc key))
7057 (org-defkey orgstruct-mode-map key cmd))
7059 ;; Special treatment needed for TAB and RET
7060 (org-defkey orgstruct-mode-map [(tab)]
7061 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7062 (org-defkey orgstruct-mode-map "\C-i"
7063 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7065 (org-defkey orgstruct-mode-map "\M-\C-m"
7066 (orgstruct-make-binding 'org-insert-heading 105
7067 "\M-\C-m" [(meta return)]))
7068 (org-defkey orgstruct-mode-map [(meta return)]
7069 (orgstruct-make-binding 'org-insert-heading 106
7070 [(meta return)] "\M-\C-m"))
7072 (org-defkey orgstruct-mode-map [(shift meta return)]
7073 (orgstruct-make-binding 'org-insert-todo-heading 107
7074 [(meta return)] "\M-\C-m"))
7076 (unless org-local-vars
7077 (setq org-local-vars (org-get-local-variables)))
7081 (defun orgstruct-make-binding (fun n &rest keys)
7082 "Create a function for binding in the structure minor mode.
7083 FUN is the command to call inside a table. N is used to create a unique
7084 command name. KEYS are keys that should be checked in for a command
7085 to execute outside of tables."
7086 (eval
7087 (list 'defun
7088 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7089 '(arg)
7090 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7091 "Outside of structure, run the binding of `"
7092 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7093 "'.")
7094 '(interactive "p")
7095 (list 'if
7096 '(org-context-p 'headline 'item)
7097 (list 'org-run-like-in-org-mode (list 'quote fun))
7098 (list 'let '(orgstruct-mode)
7099 (list 'call-interactively
7100 (append '(or)
7101 (mapcar (lambda (k)
7102 (list 'key-binding k))
7103 keys)
7104 '('orgstruct-error))))))))
7106 (defun org-context-p (&rest contexts)
7107 "Check if local context is and of CONTEXTS.
7108 Possible values in the list of contexts are `table', `headline', and `item'."
7109 (let ((pos (point)))
7110 (goto-char (point-at-bol))
7111 (prog1 (or (and (memq 'table contexts)
7112 (looking-at "[ \t]*|"))
7113 (and (memq 'headline contexts)
7114 (looking-at "\\*+"))
7115 (and (memq 'item contexts)
7116 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7117 (goto-char pos))))
7119 (defun org-get-local-variables ()
7120 "Return a list of all local variables in an org-mode buffer."
7121 (let (varlist)
7122 (with-current-buffer (get-buffer-create "*Org tmp*")
7123 (erase-buffer)
7124 (org-mode)
7125 (setq varlist (buffer-local-variables)))
7126 (kill-buffer "*Org tmp*")
7127 (delq nil
7128 (mapcar
7129 (lambda (x)
7130 (setq x
7131 (if (symbolp x)
7132 (list x)
7133 (list (car x) (list 'quote (cdr x)))))
7134 (if (string-match
7135 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7136 (symbol-name (car x)))
7137 x nil))
7138 varlist))))
7140 ;;;###autoload
7141 (defun org-run-like-in-org-mode (cmd)
7142 (unless org-local-vars
7143 (setq org-local-vars (org-get-local-variables)))
7144 (eval (list 'let org-local-vars
7145 (list 'call-interactively (list 'quote cmd)))))
7147 ;;;; Archiving
7149 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7151 (defun org-archive-subtree (&optional find-done)
7152 "Move the current subtree to the archive.
7153 The archive can be a certain top-level heading in the current file, or in
7154 a different file. The tree will be moved to that location, the subtree
7155 heading be marked DONE, and the current time will be added.
7157 When called with prefix argument FIND-DONE, find whole trees without any
7158 open TODO items and archive them (after getting confirmation from the user).
7159 If the cursor is not at a headline when this comand is called, try all level
7160 1 trees. If the cursor is on a headline, only try the direct children of
7161 this heading."
7162 (interactive "P")
7163 (if find-done
7164 (org-archive-all-done)
7165 ;; Save all relevant TODO keyword-relatex variables
7167 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7168 (tr-org-todo-keywords-1 org-todo-keywords-1)
7169 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7170 (tr-org-done-keywords org-done-keywords)
7171 (tr-org-todo-regexp org-todo-regexp)
7172 (tr-org-todo-line-regexp org-todo-line-regexp)
7173 (tr-org-odd-levels-only org-odd-levels-only)
7174 (this-buffer (current-buffer))
7175 (org-archive-location org-archive-location)
7176 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7177 ;; start of variables that will be used for savind context
7178 (file (abbreviate-file-name (buffer-file-name)))
7179 (time (format-time-string
7180 (substring (cdr org-time-stamp-formats) 1 -1)
7181 (current-time)))
7182 afile heading buffer level newfile-p
7183 category todo priority
7184 ;; start of variables that will be used for savind context
7185 ltags itags prop)
7187 ;; Try to find a local archive location
7188 (save-excursion
7189 (save-restriction
7190 (widen)
7191 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7192 (if (and prop (string-match "\\S-" prop))
7193 (setq org-archive-location prop)
7194 (if (or (re-search-backward re nil t)
7195 (re-search-forward re nil t))
7196 (setq org-archive-location (match-string 1))))))
7198 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7199 (progn
7200 (setq afile (format (match-string 1 org-archive-location)
7201 (file-name-nondirectory buffer-file-name))
7202 heading (match-string 2 org-archive-location)))
7203 (error "Invalid `org-archive-location'"))
7204 (if (> (length afile) 0)
7205 (setq newfile-p (not (file-exists-p afile))
7206 buffer (find-file-noselect afile))
7207 (setq buffer (current-buffer)))
7208 (unless buffer
7209 (error "Cannot access file \"%s\"" afile))
7210 (if (and (> (length heading) 0)
7211 (string-match "^\\*+" heading))
7212 (setq level (match-end 0))
7213 (setq heading nil level 0))
7214 (save-excursion
7215 (org-back-to-heading t)
7216 ;; Get context information that will be lost by moving the tree
7217 (org-refresh-category-properties)
7218 (setq category (org-get-category)
7219 todo (and (looking-at org-todo-line-regexp)
7220 (match-string 2))
7221 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7222 ltags (org-get-tags)
7223 itags (org-delete-all ltags (org-get-tags-at)))
7224 (setq ltags (mapconcat 'identity ltags " ")
7225 itags (mapconcat 'identity itags " "))
7226 ;; We first only copy, in case something goes wrong
7227 ;; we need to protect this-command, to avoid kill-region sets it,
7228 ;; which would lead to duplication of subtrees
7229 (let (this-command) (org-copy-subtree))
7230 (set-buffer buffer)
7231 ;; Enforce org-mode for the archive buffer
7232 (if (not (org-mode-p))
7233 ;; Force the mode for future visits.
7234 (let ((org-insert-mode-line-in-empty-file t)
7235 (org-inhibit-startup t))
7236 (call-interactively 'org-mode)))
7237 (when newfile-p
7238 (goto-char (point-max))
7239 (insert (format "\nArchived entries from file %s\n\n"
7240 (buffer-file-name this-buffer))))
7241 ;; Force the TODO keywords of the original buffer
7242 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7243 (org-todo-keywords-1 tr-org-todo-keywords-1)
7244 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7245 (org-done-keywords tr-org-done-keywords)
7246 (org-todo-regexp tr-org-todo-regexp)
7247 (org-todo-line-regexp tr-org-todo-line-regexp)
7248 (org-odd-levels-only
7249 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7250 org-odd-levels-only
7251 tr-org-odd-levels-only)))
7252 (goto-char (point-min))
7253 (if heading
7254 (progn
7255 (if (re-search-forward
7256 (concat "^" (regexp-quote heading)
7257 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7258 nil t)
7259 (goto-char (match-end 0))
7260 ;; Heading not found, just insert it at the end
7261 (goto-char (point-max))
7262 (or (bolp) (insert "\n"))
7263 (insert "\n" heading "\n")
7264 (end-of-line 0))
7265 ;; Make the subtree visible
7266 (show-subtree)
7267 (org-end-of-subtree t)
7268 (skip-chars-backward " \t\r\n")
7269 (and (looking-at "[ \t\r\n]*")
7270 (replace-match "\n\n")))
7271 ;; No specific heading, just go to end of file.
7272 (goto-char (point-max)) (insert "\n"))
7273 ;; Paste
7274 (org-paste-subtree (org-get-legal-level level 1))
7276 ;; Mark the entry as done
7277 (when (and org-archive-mark-done
7278 (looking-at org-todo-line-regexp)
7279 (or (not (match-end 2))
7280 (not (member (match-string 2) org-done-keywords))))
7281 (let (org-log-done)
7282 (org-todo
7283 (car (or (member org-archive-mark-done org-done-keywords)
7284 org-done-keywords)))))
7286 ;; Add the context info
7287 (when org-archive-save-context-info
7288 (let ((l org-archive-save-context-info) e n v)
7289 (while (setq e (pop l))
7290 (when (and (setq v (symbol-value e))
7291 (stringp v) (string-match "\\S-" v))
7292 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7293 (org-entry-put (point) n v)))))
7295 ;; Save the buffer, if it is not the same buffer.
7296 (if (not (eq this-buffer buffer)) (save-buffer))))
7297 ;; Here we are back in the original buffer. Everything seems to have
7298 ;; worked. So now cut the tree and finish up.
7299 (let (this-command) (org-cut-subtree))
7300 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7301 (message "Subtree archived %s"
7302 (if (eq this-buffer buffer)
7303 (concat "under heading: " heading)
7304 (concat "in file: " (abbreviate-file-name afile)))))))
7306 (defun org-refresh-category-properties ()
7307 "Refresh category text properties in teh buffer."
7308 (let ((def-cat (cond
7309 ((null org-category)
7310 (if buffer-file-name
7311 (file-name-sans-extension
7312 (file-name-nondirectory buffer-file-name))
7313 "???"))
7314 ((symbolp org-category) (symbol-name org-category))
7315 (t org-category)))
7316 beg end cat pos optionp)
7317 (org-unmodified
7318 (save-excursion
7319 (save-restriction
7320 (widen)
7321 (goto-char (point-min))
7322 (put-text-property (point) (point-max) 'org-category def-cat)
7323 (while (re-search-forward
7324 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7325 (setq pos (match-end 0)
7326 optionp (equal (char-after (match-beginning 0)) ?#)
7327 cat (org-trim (match-string 2)))
7328 (if optionp
7329 (setq beg (point-at-bol) end (point-max))
7330 (org-back-to-heading t)
7331 (setq beg (point) end (org-end-of-subtree t t)))
7332 (put-text-property beg end 'org-category cat)
7333 (goto-char pos)))))))
7335 (defun org-archive-all-done (&optional tag)
7336 "Archive sublevels of the current tree without open TODO items.
7337 If the cursor is not on a headline, try all level 1 trees. If
7338 it is on a headline, try all direct children.
7339 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7340 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7341 (rea (concat ".*:" org-archive-tag ":"))
7342 (begm (make-marker))
7343 (endm (make-marker))
7344 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7345 "Move subtree to archive (no open TODO items)? "))
7346 beg end (cntarch 0))
7347 (if (org-on-heading-p)
7348 (progn
7349 (setq re1 (concat "^" (regexp-quote
7350 (make-string
7351 (1+ (- (match-end 0) (match-beginning 0)))
7352 ?*))
7353 " "))
7354 (move-marker begm (point))
7355 (move-marker endm (org-end-of-subtree t)))
7356 (setq re1 "^* ")
7357 (move-marker begm (point-min))
7358 (move-marker endm (point-max)))
7359 (save-excursion
7360 (goto-char begm)
7361 (while (re-search-forward re1 endm t)
7362 (setq beg (match-beginning 0)
7363 end (save-excursion (org-end-of-subtree t) (point)))
7364 (goto-char beg)
7365 (if (re-search-forward re end t)
7366 (goto-char end)
7367 (goto-char beg)
7368 (if (and (or (not tag) (not (looking-at rea)))
7369 (y-or-n-p question))
7370 (progn
7371 (if tag
7372 (org-toggle-tag org-archive-tag 'on)
7373 (org-archive-subtree))
7374 (setq cntarch (1+ cntarch)))
7375 (goto-char end)))))
7376 (message "%d trees archived" cntarch)))
7378 (defun org-cycle-hide-drawers (state)
7379 "Re-hide all drawers after a visibility state change."
7380 (when (and (org-mode-p)
7381 (not (memq state '(overview folded))))
7382 (save-excursion
7383 (let* ((globalp (memq state '(contents all)))
7384 (beg (if globalp (point-min) (point)))
7385 (end (if globalp (point-max) (org-end-of-subtree t))))
7386 (goto-char beg)
7387 (while (re-search-forward org-drawer-regexp end t)
7388 (org-flag-drawer t))))))
7390 (defun org-flag-drawer (flag)
7391 (save-excursion
7392 (beginning-of-line 1)
7393 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7394 (let ((b (match-end 0)))
7395 (if (re-search-forward
7396 "^[ \t]*:END:"
7397 (save-excursion (outline-next-heading) (point)) t)
7398 (outline-flag-region b (point-at-eol) flag)
7399 (error ":END: line missing"))))))
7401 (defun org-cycle-hide-archived-subtrees (state)
7402 "Re-hide all archived subtrees after a visibility state change."
7403 (when (and (not org-cycle-open-archived-trees)
7404 (not (memq state '(overview folded))))
7405 (save-excursion
7406 (let* ((globalp (memq state '(contents all)))
7407 (beg (if globalp (point-min) (point)))
7408 (end (if globalp (point-max) (org-end-of-subtree t))))
7409 (org-hide-archived-subtrees beg end)
7410 (goto-char beg)
7411 (if (looking-at (concat ".*:" org-archive-tag ":"))
7412 (message (substitute-command-keys
7413 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7415 (defun org-force-cycle-archived ()
7416 "Cycle subtree even if it is archived."
7417 (interactive)
7418 (setq this-command 'org-cycle)
7419 (let ((org-cycle-open-archived-trees t))
7420 (call-interactively 'org-cycle)))
7422 (defun org-hide-archived-subtrees (beg end)
7423 "Re-hide all archived subtrees after a visibility state change."
7424 (save-excursion
7425 (let* ((re (concat ":" org-archive-tag ":")))
7426 (goto-char beg)
7427 (while (re-search-forward re end t)
7428 (and (org-on-heading-p) (hide-subtree))
7429 (org-end-of-subtree t)))))
7431 (defun org-toggle-tag (tag &optional onoff)
7432 "Toggle the tag TAG for the current line.
7433 If ONOFF is `on' or `off', don't toggle but set to this state."
7434 (unless (org-on-heading-p t) (error "Not on headling"))
7435 (let (res current)
7436 (save-excursion
7437 (beginning-of-line)
7438 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7439 (point-at-eol) t)
7440 (progn
7441 (setq current (match-string 1))
7442 (replace-match ""))
7443 (setq current ""))
7444 (setq current (nreverse (org-split-string current ":")))
7445 (cond
7446 ((eq onoff 'on)
7447 (setq res t)
7448 (or (member tag current) (push tag current)))
7449 ((eq onoff 'off)
7450 (or (not (member tag current)) (setq current (delete tag current))))
7451 (t (if (member tag current)
7452 (setq current (delete tag current))
7453 (setq res t)
7454 (push tag current))))
7455 (end-of-line 1)
7456 (if current
7457 (progn
7458 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7459 (org-set-tags nil t))
7460 (delete-horizontal-space))
7461 (run-hooks 'org-after-tags-change-hook))
7462 res))
7464 (defun org-toggle-archive-tag (&optional arg)
7465 "Toggle the archive tag for the current headline.
7466 With prefix ARG, check all children of current headline and offer tagging
7467 the children that do not contain any open TODO items."
7468 (interactive "P")
7469 (if arg
7470 (org-archive-all-done 'tag)
7471 (let (set)
7472 (save-excursion
7473 (org-back-to-heading t)
7474 (setq set (org-toggle-tag org-archive-tag))
7475 (when set (hide-subtree)))
7476 (and set (beginning-of-line 1))
7477 (message "Subtree %s" (if set "archived" "unarchived")))))
7480 ;;;; Tables
7482 ;;; The table editor
7484 ;; Watch out: Here we are talking about two different kind of tables.
7485 ;; Most of the code is for the tables created with the Org-mode table editor.
7486 ;; Sometimes, we talk about tables created and edited with the table.el
7487 ;; Emacs package. We call the former org-type tables, and the latter
7488 ;; table.el-type tables.
7490 (defun org-before-change-function (beg end)
7491 "Every change indicates that a table might need an update."
7492 (setq org-table-may-need-update t))
7494 (defconst org-table-line-regexp "^[ \t]*|"
7495 "Detects an org-type table line.")
7496 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7497 "Detects an org-type table line.")
7498 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7499 "Detects a table line marked for automatic recalculation.")
7500 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7501 "Detects a table line marked for automatic recalculation.")
7502 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7503 "Detects a table line marked for automatic recalculation.")
7504 (defconst org-table-hline-regexp "^[ \t]*|-"
7505 "Detects an org-type table hline.")
7506 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7507 "Detects a table-type table hline.")
7508 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7509 "Detects an org-type or table-type table.")
7510 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7511 "Searching from within a table (any type) this finds the first line
7512 outside the table.")
7513 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7514 "Searching from within a table (any type) this finds the first line
7515 outside the table.")
7517 (defvar org-table-last-highlighted-reference nil)
7518 (defvar org-table-formula-history nil)
7520 (defvar org-table-column-names nil
7521 "Alist with column names, derived from the `!' line.")
7522 (defvar org-table-column-name-regexp nil
7523 "Regular expression matching the current column names.")
7524 (defvar org-table-local-parameters nil
7525 "Alist with parameter names, derived from the `$' line.")
7526 (defvar org-table-named-field-locations nil
7527 "Alist with locations of named fields.")
7529 (defvar org-table-current-line-types nil
7530 "Table row types, non-nil only for the duration of a comand.")
7531 (defvar org-table-current-begin-line nil
7532 "Table begin line, non-nil only for the duration of a comand.")
7533 (defvar org-table-current-begin-pos nil
7534 "Table begin position, non-nil only for the duration of a comand.")
7535 (defvar org-table-dlines nil
7536 "Vector of data line line numbers in the current table.")
7537 (defvar org-table-hlines nil
7538 "Vector of hline line numbers in the current table.")
7540 (defconst org-table-range-regexp
7541 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7542 ;; 1 2 3 4 5
7543 "Regular expression for matching ranges in formulas.")
7545 (defconst org-table-range-regexp2
7546 (concat
7547 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7548 "\\.\\."
7549 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7550 "Match a range for reference display.")
7552 (defconst org-table-translate-regexp
7553 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7554 "Match a reference that needs translation, for reference display.")
7556 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7558 (defun org-table-create-with-table.el ()
7559 "Use the table.el package to insert a new table.
7560 If there is already a table at point, convert between Org-mode tables
7561 and table.el tables."
7562 (interactive)
7563 (require 'table)
7564 (cond
7565 ((org-at-table.el-p)
7566 (if (y-or-n-p "Convert table to Org-mode table? ")
7567 (org-table-convert)))
7568 ((org-at-table-p)
7569 (if (y-or-n-p "Convert table to table.el table? ")
7570 (org-table-convert)))
7571 (t (call-interactively 'table-insert))))
7573 (defun org-table-create-or-convert-from-region (arg)
7574 "Convert region to table, or create an empty table.
7575 If there is an active region, convert it to a table, using the function
7576 `org-table-convert-region'. See the documentation of that function
7577 to learn how the prefix argument is interpreted to determine the field
7578 separator.
7579 If there is no such region, create an empty table with `org-table-create'."
7580 (interactive "P")
7581 (if (org-region-active-p)
7582 (org-table-convert-region (region-beginning) (region-end) arg)
7583 (org-table-create arg)))
7585 (defun org-table-create (&optional size)
7586 "Query for a size and insert a table skeleton.
7587 SIZE is a string Columns x Rows like for example \"3x2\"."
7588 (interactive "P")
7589 (unless size
7590 (setq size (read-string
7591 (concat "Table size Columns x Rows [e.g. "
7592 org-table-default-size "]: ")
7593 "" nil org-table-default-size)))
7595 (let* ((pos (point))
7596 (indent (make-string (current-column) ?\ ))
7597 (split (org-split-string size " *x *"))
7598 (rows (string-to-number (nth 1 split)))
7599 (columns (string-to-number (car split)))
7600 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7601 "\n")))
7602 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7603 (point-at-bol) (point)))
7604 (beginning-of-line 1)
7605 (newline))
7606 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7607 (dotimes (i rows) (insert line))
7608 (goto-char pos)
7609 (if (> rows 1)
7610 ;; Insert a hline after the first row.
7611 (progn
7612 (end-of-line 1)
7613 (insert "\n|-")
7614 (goto-char pos)))
7615 (org-table-align)))
7617 (defun org-table-convert-region (beg0 end0 &optional separator)
7618 "Convert region to a table.
7619 The region goes from BEG0 to END0, but these borders will be moved
7620 slightly, to make sure a beginning of line in the first line is included.
7622 SEPARATOR specifies the field separator in the lines. It can have the
7623 following values:
7625 '(4) Use the comma as a field separator
7626 '(16) Use a TAB as field separator
7627 integer When a number, use that many spaces as field separator
7628 nil When nil, the command tries to be smart and figure out the
7629 separator in the following way:
7630 - when each line contains a TAB, assume TAB-separated material
7631 - when each line contains a comme, assume CSV material
7632 - else, assume one or more SPACE charcters as separator."
7633 (interactive "rP")
7634 (let* ((beg (min beg0 end0))
7635 (end (max beg0 end0))
7637 (goto-char beg)
7638 (beginning-of-line 1)
7639 (setq beg (move-marker (make-marker) (point)))
7640 (goto-char end)
7641 (if (bolp) (backward-char 1) (end-of-line 1))
7642 (setq end (move-marker (make-marker) (point)))
7643 ;; Get the right field separator
7644 (unless separator
7645 (goto-char beg)
7646 (setq separator
7647 (cond
7648 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7649 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7650 (t 1))))
7651 (setq re (cond
7652 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7653 ((equal separator '(16)) "^\\|\t")
7654 ((integerp separator)
7655 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7656 (t (error "This should not happen"))))
7657 (goto-char beg)
7658 (while (re-search-forward re end t)
7659 (replace-match "| " t t))
7660 (goto-char beg)
7661 (insert " ")
7662 (org-table-align)))
7664 (defun org-table-import (file arg)
7665 "Import FILE as a table.
7666 The file is assumed to be tab-separated. Such files can be produced by most
7667 spreadsheet and database applications. If no tabs (at least one per line)
7668 are found, lines will be split on whitespace into fields."
7669 (interactive "f\nP")
7670 (or (bolp) (newline))
7671 (let ((beg (point))
7672 (pm (point-max)))
7673 (insert-file-contents file)
7674 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7676 (defun org-table-export ()
7677 "Export table as a tab-separated file.
7678 Such a file can be imported into a spreadsheet program like Excel."
7679 (interactive)
7680 (let* ((beg (org-table-begin))
7681 (end (org-table-end))
7682 (table (buffer-substring beg end))
7683 (file (read-file-name "Export table to: "))
7684 buf)
7685 (unless (or (not (file-exists-p file))
7686 (y-or-n-p (format "Overwrite file %s? " file)))
7687 (error "Abort"))
7688 (with-current-buffer (find-file-noselect file)
7689 (setq buf (current-buffer))
7690 (erase-buffer)
7691 (fundamental-mode)
7692 (insert table)
7693 (goto-char (point-min))
7694 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7695 (replace-match "" t t)
7696 (end-of-line 1))
7697 (goto-char (point-min))
7698 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7699 (replace-match "" t t)
7700 (goto-char (min (1+ (point)) (point-max))))
7701 (goto-char (point-min))
7702 (while (re-search-forward "^-[-+]*$" nil t)
7703 (replace-match "")
7704 (if (looking-at "\n")
7705 (delete-char 1)))
7706 (goto-char (point-min))
7707 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7708 (replace-match "\t" t t))
7709 (save-buffer))
7710 (kill-buffer buf)))
7712 (defvar org-table-aligned-begin-marker (make-marker)
7713 "Marker at the beginning of the table last aligned.
7714 Used to check if cursor still is in that table, to minimize realignment.")
7715 (defvar org-table-aligned-end-marker (make-marker)
7716 "Marker at the end of the table last aligned.
7717 Used to check if cursor still is in that table, to minimize realignment.")
7718 (defvar org-table-last-alignment nil
7719 "List of flags for flushright alignment, from the last re-alignment.
7720 This is being used to correctly align a single field after TAB or RET.")
7721 (defvar org-table-last-column-widths nil
7722 "List of max width of fields in each column.
7723 This is being used to correctly align a single field after TAB or RET.")
7724 (defvar org-table-overlay-coordinates nil
7725 "Overlay coordinates after each align of a table.")
7726 (make-variable-buffer-local 'org-table-overlay-coordinates)
7728 (defvar org-last-recalc-line nil)
7729 (defconst org-narrow-column-arrow "=>"
7730 "Used as display property in narrowed table columns.")
7732 (defun org-table-align ()
7733 "Align the table at point by aligning all vertical bars."
7734 (interactive)
7735 (let* (
7736 ;; Limits of table
7737 (beg (org-table-begin))
7738 (end (org-table-end))
7739 ;; Current cursor position
7740 (linepos (org-current-line))
7741 (colpos (org-table-current-column))
7742 (winstart (window-start))
7743 (winstartline (org-current-line (min winstart (1- (point-max)))))
7744 lines (new "") lengths l typenums ty fields maxfields i
7745 column
7746 (indent "") cnt frac
7747 rfmt hfmt
7748 (spaces '(1 . 1))
7749 (sp1 (car spaces))
7750 (sp2 (cdr spaces))
7751 (rfmt1 (concat
7752 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7753 (hfmt1 (concat
7754 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7755 emptystrings links dates narrow fmax f1 len c e)
7756 (untabify beg end)
7757 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7758 ;; Check if we have links or dates
7759 (goto-char beg)
7760 (setq links (re-search-forward org-bracket-link-regexp end t))
7761 (goto-char beg)
7762 (setq dates (and org-display-custom-times
7763 (re-search-forward org-ts-regexp-both end t)))
7764 ;; Make sure the link properties are right
7765 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7766 ;; Make sure the date properties are right
7767 (when dates (goto-char beg) (while (org-activate-dates end)))
7769 ;; Check if we are narrowing any columns
7770 (goto-char beg)
7771 (setq narrow (and org-format-transports-properties-p
7772 (re-search-forward "<[0-9]+>" end t)))
7773 ;; Get the rows
7774 (setq lines (org-split-string
7775 (buffer-substring beg end) "\n"))
7776 ;; Store the indentation of the first line
7777 (if (string-match "^ *" (car lines))
7778 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7779 ;; Mark the hlines by setting the corresponding element to nil
7780 ;; At the same time, we remove trailing space.
7781 (setq lines (mapcar (lambda (l)
7782 (if (string-match "^ *|-" l)
7784 (if (string-match "[ \t]+$" l)
7785 (substring l 0 (match-beginning 0))
7786 l)))
7787 lines))
7788 ;; Get the data fields by splitting the lines.
7789 (setq fields (mapcar
7790 (lambda (l)
7791 (org-split-string l " *| *"))
7792 (delq nil (copy-sequence lines))))
7793 ;; How many fields in the longest line?
7794 (condition-case nil
7795 (setq maxfields (apply 'max (mapcar 'length fields)))
7796 (error
7797 (kill-region beg end)
7798 (org-table-create org-table-default-size)
7799 (error "Empty table - created default table")))
7800 ;; A list of empty strings to fill any short rows on output
7801 (setq emptystrings (make-list maxfields ""))
7802 ;; Check for special formatting.
7803 (setq i -1)
7804 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7805 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7806 ;; Check if there is an explicit width specified
7807 (when narrow
7808 (setq c column fmax nil)
7809 (while c
7810 (setq e (pop c))
7811 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7812 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7813 ;; Find fields that are wider than fmax, and shorten them
7814 (when fmax
7815 (loop for xx in column do
7816 (when (and (stringp xx)
7817 (> (org-string-width xx) fmax))
7818 (org-add-props xx nil
7819 'help-echo
7820 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7821 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7822 (unless (> f1 1)
7823 (error "Cannot narrow field starting with wide link \"%s\""
7824 (match-string 0 xx)))
7825 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7826 (add-text-properties (- f1 2) f1
7827 (list 'display org-narrow-column-arrow)
7828 xx)))))
7829 ;; Get the maximum width for each column
7830 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
7831 ;; Get the fraction of numbers, to decide about alignment of the column
7832 (setq cnt 0 frac 0.0)
7833 (loop for x in column do
7834 (if (equal x "")
7836 (setq frac ( / (+ (* frac cnt)
7837 (if (string-match org-table-number-regexp x) 1 0))
7838 (setq cnt (1+ cnt))))))
7839 (push (>= frac org-table-number-fraction) typenums))
7840 (setq lengths (nreverse lengths) typenums (nreverse typenums))
7842 ;; Store the alignment of this table, for later editing of single fields
7843 (setq org-table-last-alignment typenums
7844 org-table-last-column-widths lengths)
7846 ;; With invisible characters, `format' does not get the field width right
7847 ;; So we need to make these fields wide by hand.
7848 (when links
7849 (loop for i from 0 upto (1- maxfields) do
7850 (setq len (nth i lengths))
7851 (loop for j from 0 upto (1- (length fields)) do
7852 (setq c (nthcdr i (car (nthcdr j fields))))
7853 (if (and (stringp (car c))
7854 (string-match org-bracket-link-regexp (car c))
7855 (< (org-string-width (car c)) len))
7856 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
7858 ;; Compute the formats needed for output of the table
7859 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7860 (while (setq l (pop lengths))
7861 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7862 (setq rfmt (concat rfmt (format rfmt1 ty l))
7863 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7864 (setq rfmt (concat rfmt "\n")
7865 hfmt (concat (substring hfmt 0 -1) "|\n"))
7867 (setq new (mapconcat
7868 (lambda (l)
7869 (if l (apply 'format rfmt
7870 (append (pop fields) emptystrings))
7871 hfmt))
7872 lines ""))
7873 ;; Replace the old one
7874 (delete-region beg end)
7875 (move-marker end nil)
7876 (move-marker org-table-aligned-begin-marker (point))
7877 (insert new)
7878 (move-marker org-table-aligned-end-marker (point))
7879 (when (and orgtbl-mode (not (org-mode-p)))
7880 (goto-char org-table-aligned-begin-marker)
7881 (while (org-hide-wide-columns org-table-aligned-end-marker)))
7882 ;; Try to move to the old location
7883 (goto-line winstartline)
7884 (setq winstart (point-at-bol))
7885 (goto-line linepos)
7886 (set-window-start (selected-window) winstart 'noforce)
7887 (org-table-goto-column colpos)
7888 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
7889 (setq org-table-may-need-update nil)
7892 (defun org-string-width (s)
7893 "Compute width of string, ignoring invisible characters.
7894 This ignores character with invisibility property `org-link', and also
7895 characters with property `org-cwidth', because these will become invisible
7896 upon the next fontification round."
7897 (let (b l)
7898 (when (or (eq t buffer-invisibility-spec)
7899 (assq 'org-link buffer-invisibility-spec))
7900 (while (setq b (text-property-any 0 (length s)
7901 'invisible 'org-link s))
7902 (setq s (concat (substring s 0 b)
7903 (substring s (or (next-single-property-change
7904 b 'invisible s) (length s)))))))
7905 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
7906 (setq s (concat (substring s 0 b)
7907 (substring s (or (next-single-property-change
7908 b 'org-cwidth s) (length s))))))
7909 (setq l (string-width s) b -1)
7910 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
7911 (setq l (- l (get-text-property b 'org-dwidth-n s))))
7914 (defun org-table-begin (&optional table-type)
7915 "Find the beginning of the table and return its position.
7916 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7917 (save-excursion
7918 (if (not (re-search-backward
7919 (if table-type org-table-any-border-regexp
7920 org-table-border-regexp)
7921 nil t))
7922 (progn (goto-char (point-min)) (point))
7923 (goto-char (match-beginning 0))
7924 (beginning-of-line 2)
7925 (point))))
7927 (defun org-table-end (&optional table-type)
7928 "Find the end of the table and return its position.
7929 With argument TABLE-TYPE, go to the end of a table.el-type table."
7930 (save-excursion
7931 (if (not (re-search-forward
7932 (if table-type org-table-any-border-regexp
7933 org-table-border-regexp)
7934 nil t))
7935 (goto-char (point-max))
7936 (goto-char (match-beginning 0)))
7937 (point-marker)))
7939 (defun org-table-justify-field-maybe (&optional new)
7940 "Justify the current field, text to left, number to right.
7941 Optional argument NEW may specify text to replace the current field content."
7942 (cond
7943 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7944 ((org-at-table-hline-p))
7945 ((and (not new)
7946 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7947 (current-buffer)))
7948 (< (point) org-table-aligned-begin-marker)
7949 (>= (point) org-table-aligned-end-marker)))
7950 ;; This is not the same table, force a full re-align
7951 (setq org-table-may-need-update t))
7952 (t ;; realign the current field, based on previous full realign
7953 (let* ((pos (point)) s
7954 (col (org-table-current-column))
7955 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
7956 l f n o e)
7957 (when (> col 0)
7958 (skip-chars-backward "^|\n")
7959 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7960 (progn
7961 (setq s (match-string 1)
7962 o (match-string 0)
7963 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7964 e (not (= (match-beginning 2) (match-end 2))))
7965 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7966 l (if e "|" (setq org-table-may-need-update t) ""))
7967 n (format f s))
7968 (if new
7969 (if (<= (length new) l) ;; FIXME: length -> str-width?
7970 (setq n (format f new))
7971 (setq n (concat new "|") org-table-may-need-update t)))
7972 (or (equal n o)
7973 (let (org-table-may-need-update)
7974 (replace-match n t t))))
7975 (setq org-table-may-need-update t))
7976 (goto-char pos))))))
7978 (defun org-table-next-field ()
7979 "Go to the next field in the current table, creating new lines as needed.
7980 Before doing so, re-align the table if necessary."
7981 (interactive)
7982 (org-table-maybe-eval-formula)
7983 (org-table-maybe-recalculate-line)
7984 (if (and org-table-automatic-realign
7985 org-table-may-need-update)
7986 (org-table-align))
7987 (let ((end (org-table-end)))
7988 (if (org-at-table-hline-p)
7989 (end-of-line 1))
7990 (condition-case nil
7991 (progn
7992 (re-search-forward "|" end)
7993 (if (looking-at "[ \t]*$")
7994 (re-search-forward "|" end))
7995 (if (and (looking-at "-")
7996 org-table-tab-jumps-over-hlines
7997 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7998 (goto-char (match-beginning 1)))
7999 (if (looking-at "-")
8000 (progn
8001 (beginning-of-line 0)
8002 (org-table-insert-row 'below))
8003 (if (looking-at " ") (forward-char 1))))
8004 (error
8005 (org-table-insert-row 'below)))))
8007 (defun org-table-previous-field ()
8008 "Go to the previous field in the table.
8009 Before doing so, re-align the table if necessary."
8010 (interactive)
8011 (org-table-justify-field-maybe)
8012 (org-table-maybe-recalculate-line)
8013 (if (and org-table-automatic-realign
8014 org-table-may-need-update)
8015 (org-table-align))
8016 (if (org-at-table-hline-p)
8017 (end-of-line 1))
8018 (re-search-backward "|" (org-table-begin))
8019 (re-search-backward "|" (org-table-begin))
8020 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8021 (re-search-backward "|" (org-table-begin)))
8022 (if (looking-at "| ?")
8023 (goto-char (match-end 0))))
8025 (defun org-table-next-row ()
8026 "Go to the next row (same column) in the current table.
8027 Before doing so, re-align the table if necessary."
8028 (interactive)
8029 (org-table-maybe-eval-formula)
8030 (org-table-maybe-recalculate-line)
8031 (if (or (looking-at "[ \t]*$")
8032 (save-excursion (skip-chars-backward " \t") (bolp)))
8033 (newline)
8034 (if (and org-table-automatic-realign
8035 org-table-may-need-update)
8036 (org-table-align))
8037 (let ((col (org-table-current-column)))
8038 (beginning-of-line 2)
8039 (if (or (not (org-at-table-p))
8040 (org-at-table-hline-p))
8041 (progn
8042 (beginning-of-line 0)
8043 (org-table-insert-row 'below)))
8044 (org-table-goto-column col)
8045 (skip-chars-backward "^|\n\r")
8046 (if (looking-at " ") (forward-char 1)))))
8048 (defun org-table-copy-down (n)
8049 "Copy a field down in the current column.
8050 If the field at the cursor is empty, copy into it the content of the nearest
8051 non-empty field above. With argument N, use the Nth non-empty field.
8052 If the current field is not empty, it is copied down to the next row, and
8053 the cursor is moved with it. Therefore, repeating this command causes the
8054 column to be filled row-by-row.
8055 If the variable `org-table-copy-increment' is non-nil and the field is an
8056 integer or a timestamp, it will be incremented while copying. In the case of
8057 a timestamp, if the cursor is on the year, change the year. If it is on the
8058 month or the day, change that. Point will stay on the current date field
8059 in order to easily repeat the interval."
8060 (interactive "p")
8061 (let* ((colpos (org-table-current-column))
8062 (col (current-column))
8063 (field (org-table-get-field))
8064 (non-empty (string-match "[^ \t]" field))
8065 (beg (org-table-begin))
8066 txt)
8067 (org-table-check-inside-data-field)
8068 (if non-empty
8069 (progn
8070 (setq txt (org-trim field))
8071 (org-table-next-row)
8072 (org-table-blank-field))
8073 (save-excursion
8074 (setq txt
8075 (catch 'exit
8076 (while (progn (beginning-of-line 1)
8077 (re-search-backward org-table-dataline-regexp
8078 beg t))
8079 (org-table-goto-column colpos t)
8080 (if (and (looking-at
8081 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8082 (= (setq n (1- n)) 0))
8083 (throw 'exit (match-string 1))))))))
8084 (if txt
8085 (progn
8086 (if (and org-table-copy-increment
8087 (string-match "^[0-9]+$" txt))
8088 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8089 (insert txt)
8090 (move-to-column col)
8091 (if (and org-table-copy-increment (org-at-timestamp-p t))
8092 (org-timestamp-up 1)
8093 (org-table-maybe-recalculate-line))
8094 (org-table-align)
8095 (move-to-column col))
8096 (error "No non-empty field found"))))
8098 (defun org-table-check-inside-data-field ()
8099 "Is point inside a table data field?
8100 I.e. not on a hline or before the first or after the last column?
8101 This actually throws an error, so it aborts the current command."
8102 (if (or (not (org-at-table-p))
8103 (= (org-table-current-column) 0)
8104 (org-at-table-hline-p)
8105 (looking-at "[ \t]*$"))
8106 (error "Not in table data field")))
8108 (defvar org-table-clip nil
8109 "Clipboard for table regions.")
8111 (defun org-table-blank-field ()
8112 "Blank the current table field or active region."
8113 (interactive)
8114 (org-table-check-inside-data-field)
8115 (if (and (interactive-p) (org-region-active-p))
8116 (let (org-table-clip)
8117 (org-table-cut-region (region-beginning) (region-end)))
8118 (skip-chars-backward "^|")
8119 (backward-char 1)
8120 (if (looking-at "|[^|\n]+")
8121 (let* ((pos (match-beginning 0))
8122 (match (match-string 0))
8123 (len (org-string-width match)))
8124 (replace-match (concat "|" (make-string (1- len) ?\ )))
8125 (goto-char (+ 2 pos))
8126 (substring match 1)))))
8128 (defun org-table-get-field (&optional n replace)
8129 "Return the value of the field in column N of current row.
8130 N defaults to current field.
8131 If REPLACE is a string, replace field with this value. The return value
8132 is always the old value."
8133 (and n (org-table-goto-column n))
8134 (skip-chars-backward "^|\n")
8135 (backward-char 1)
8136 (if (looking-at "|[^|\r\n]*")
8137 (let* ((pos (match-beginning 0))
8138 (val (buffer-substring (1+ pos) (match-end 0))))
8139 (if replace
8140 (replace-match (concat "|" replace) t t))
8141 (goto-char (min (point-at-eol) (+ 2 pos)))
8142 val)
8143 (forward-char 1) ""))
8145 (defun org-table-field-info (arg)
8146 "Show info about the current field, and highlight any reference at point."
8147 (interactive "P")
8148 (org-table-get-specials)
8149 (save-excursion
8150 (let* ((pos (point))
8151 (col (org-table-current-column))
8152 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8153 (name (car (rassoc (list (org-current-line) col)
8154 org-table-named-field-locations)))
8155 (eql (org-table-get-stored-formulas))
8156 (dline (org-table-current-dline))
8157 (ref (format "@%d$%d" dline col))
8158 (ref1 (org-table-convert-refs-to-an ref))
8159 (fequation (or (assoc name eql) (assoc ref eql)))
8160 (cequation (assoc (int-to-string col) eql))
8161 (eqn (or fequation cequation)))
8162 (goto-char pos)
8163 (condition-case nil
8164 (org-table-show-reference 'local)
8165 (error nil))
8166 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8167 dline col
8168 (if cname (concat " or $" cname) "")
8169 dline col ref1
8170 (if name (concat " or $" name) "")
8171 ;; FIXME: formula info not correct if special table line
8172 (if eqn
8173 (concat ", formula: "
8174 (org-table-formula-to-user
8175 (concat
8176 (if (string-match "^[$@]"(car eqn)) "" "$")
8177 (car eqn) "=" (cdr eqn))))
8178 "")))))
8180 (defun org-table-current-column ()
8181 "Find out which column we are in.
8182 When called interactively, column is also displayed in echo area."
8183 (interactive)
8184 (if (interactive-p) (org-table-check-inside-data-field))
8185 (save-excursion
8186 (let ((cnt 0) (pos (point)))
8187 (beginning-of-line 1)
8188 (while (search-forward "|" pos t)
8189 (setq cnt (1+ cnt)))
8190 (if (interactive-p) (message "This is table column %d" cnt))
8191 cnt)))
8193 (defun org-table-current-dline ()
8194 "Find out what table data line we are in.
8195 Only datalins count for this."
8196 (interactive)
8197 (if (interactive-p) (org-table-check-inside-data-field))
8198 (save-excursion
8199 (let ((cnt 0) (pos (point)))
8200 (goto-char (org-table-begin))
8201 (while (<= (point) pos)
8202 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8203 (beginning-of-line 2))
8204 (if (interactive-p) (message "This is table line %d" cnt))
8205 cnt)))
8207 (defun org-table-goto-column (n &optional on-delim force)
8208 "Move the cursor to the Nth column in the current table line.
8209 With optional argument ON-DELIM, stop with point before the left delimiter
8210 of the field.
8211 If there are less than N fields, just go to after the last delimiter.
8212 However, when FORCE is non-nil, create new columns if necessary."
8213 (interactive "p")
8214 (let ((pos (point-at-eol)))
8215 (beginning-of-line 1)
8216 (when (> n 0)
8217 (while (and (> (setq n (1- n)) -1)
8218 (or (search-forward "|" pos t)
8219 (and force
8220 (progn (end-of-line 1)
8221 (skip-chars-backward "^|")
8222 (insert " | "))))))
8223 ; (backward-char 2) t)))))
8224 (when (and force (not (looking-at ".*|")))
8225 (save-excursion (end-of-line 1) (insert " | ")))
8226 (if on-delim
8227 (backward-char 1)
8228 (if (looking-at " ") (forward-char 1))))))
8230 (defun org-at-table-p (&optional table-type)
8231 "Return t if the cursor is inside an org-type table.
8232 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8233 (if org-enable-table-editor
8234 (save-excursion
8235 (beginning-of-line 1)
8236 (looking-at (if table-type org-table-any-line-regexp
8237 org-table-line-regexp)))
8238 nil))
8240 (defun org-at-table.el-p ()
8241 "Return t if and only if we are at a table.el table."
8242 (and (org-at-table-p 'any)
8243 (save-excursion
8244 (goto-char (org-table-begin 'any))
8245 (looking-at org-table1-hline-regexp))))
8247 (defun org-table-recognize-table.el ()
8248 "If there is a table.el table nearby, recognize it and move into it."
8249 (if org-table-tab-recognizes-table.el
8250 (if (org-at-table.el-p)
8251 (progn
8252 (beginning-of-line 1)
8253 (if (looking-at org-table-dataline-regexp)
8255 (if (looking-at org-table1-hline-regexp)
8256 (progn
8257 (beginning-of-line 2)
8258 (if (looking-at org-table-any-border-regexp)
8259 (beginning-of-line -1)))))
8260 (if (re-search-forward "|" (org-table-end t) t)
8261 (progn
8262 (require 'table)
8263 (if (table--at-cell-p (point))
8265 (message "recognizing table.el table...")
8266 (table-recognize-table)
8267 (message "recognizing table.el table...done")))
8268 (error "This should not happen..."))
8270 nil)
8271 nil))
8273 (defun org-at-table-hline-p ()
8274 "Return t if the cursor is inside a hline in a table."
8275 (if org-enable-table-editor
8276 (save-excursion
8277 (beginning-of-line 1)
8278 (looking-at org-table-hline-regexp))
8279 nil))
8281 (defun org-table-insert-column ()
8282 "Insert a new column into the table."
8283 (interactive)
8284 (if (not (org-at-table-p))
8285 (error "Not at a table"))
8286 (org-table-find-dataline)
8287 (let* ((col (max 1 (org-table-current-column)))
8288 (beg (org-table-begin))
8289 (end (org-table-end))
8290 ;; Current cursor position
8291 (linepos (org-current-line))
8292 (colpos col))
8293 (goto-char beg)
8294 (while (< (point) end)
8295 (if (org-at-table-hline-p)
8297 (org-table-goto-column col t)
8298 (insert "| "))
8299 (beginning-of-line 2))
8300 (move-marker end nil)
8301 (goto-line linepos)
8302 (org-table-goto-column colpos)
8303 (org-table-align)
8304 (org-table-fix-formulas "$" nil (1- col) 1)))
8306 (defun org-table-find-dataline ()
8307 "Find a dataline in the current table, which is needed for column commands."
8308 (if (and (org-at-table-p)
8309 (not (org-at-table-hline-p)))
8311 (let ((col (current-column))
8312 (end (org-table-end)))
8313 (move-to-column col)
8314 (while (and (< (point) end)
8315 (or (not (= (current-column) col))
8316 (org-at-table-hline-p)))
8317 (beginning-of-line 2)
8318 (move-to-column col))
8319 (if (and (org-at-table-p)
8320 (not (org-at-table-hline-p)))
8322 (error
8323 "Please position cursor in a data line for column operations")))))
8325 (defun org-table-delete-column ()
8326 "Delete a column from the table."
8327 (interactive)
8328 (if (not (org-at-table-p))
8329 (error "Not at a table"))
8330 (org-table-find-dataline)
8331 (org-table-check-inside-data-field)
8332 (let* ((col (org-table-current-column))
8333 (beg (org-table-begin))
8334 (end (org-table-end))
8335 ;; Current cursor position
8336 (linepos (org-current-line))
8337 (colpos col))
8338 (goto-char beg)
8339 (while (< (point) end)
8340 (if (org-at-table-hline-p)
8342 (org-table-goto-column col t)
8343 (and (looking-at "|[^|\n]+|")
8344 (replace-match "|")))
8345 (beginning-of-line 2))
8346 (move-marker end nil)
8347 (goto-line linepos)
8348 (org-table-goto-column colpos)
8349 (org-table-align)
8350 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8351 col -1 col)))
8353 (defun org-table-move-column-right ()
8354 "Move column to the right."
8355 (interactive)
8356 (org-table-move-column nil))
8357 (defun org-table-move-column-left ()
8358 "Move column to the left."
8359 (interactive)
8360 (org-table-move-column 'left))
8362 (defun org-table-move-column (&optional left)
8363 "Move the current column to the right. With arg LEFT, move to the left."
8364 (interactive "P")
8365 (if (not (org-at-table-p))
8366 (error "Not at a table"))
8367 (org-table-find-dataline)
8368 (org-table-check-inside-data-field)
8369 (let* ((col (org-table-current-column))
8370 (col1 (if left (1- col) col))
8371 (beg (org-table-begin))
8372 (end (org-table-end))
8373 ;; Current cursor position
8374 (linepos (org-current-line))
8375 (colpos (if left (1- col) (1+ col))))
8376 (if (and left (= col 1))
8377 (error "Cannot move column further left"))
8378 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8379 (error "Cannot move column further right"))
8380 (goto-char beg)
8381 (while (< (point) end)
8382 (if (org-at-table-hline-p)
8384 (org-table-goto-column col1 t)
8385 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8386 (replace-match "|\\2|\\1|")))
8387 (beginning-of-line 2))
8388 (move-marker end nil)
8389 (goto-line linepos)
8390 (org-table-goto-column colpos)
8391 (org-table-align)
8392 (org-table-fix-formulas
8393 "$" (list (cons (number-to-string col) (number-to-string colpos))
8394 (cons (number-to-string colpos) (number-to-string col))))))
8396 (defun org-table-move-row-down ()
8397 "Move table row down."
8398 (interactive)
8399 (org-table-move-row nil))
8400 (defun org-table-move-row-up ()
8401 "Move table row up."
8402 (interactive)
8403 (org-table-move-row 'up))
8405 (defun org-table-move-row (&optional up)
8406 "Move the current table line down. With arg UP, move it up."
8407 (interactive "P")
8408 (let* ((col (current-column))
8409 (pos (point))
8410 (hline1p (save-excursion (beginning-of-line 1)
8411 (looking-at org-table-hline-regexp)))
8412 (dline1 (org-table-current-dline))
8413 (dline2 (+ dline1 (if up -1 1)))
8414 (tonew (if up 0 2))
8415 txt hline2p)
8416 (beginning-of-line tonew)
8417 (unless (org-at-table-p)
8418 (goto-char pos)
8419 (error "Cannot move row further"))
8420 (setq hline2p (looking-at org-table-hline-regexp))
8421 (goto-char pos)
8422 (beginning-of-line 1)
8423 (setq pos (point))
8424 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8425 (delete-region (point) (1+ (point-at-eol)))
8426 (beginning-of-line tonew)
8427 (insert txt)
8428 (beginning-of-line 0)
8429 (move-to-column col)
8430 (unless (or hline1p hline2p)
8431 (org-table-fix-formulas
8432 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8433 (cons (number-to-string dline2) (number-to-string dline1)))))))
8435 (defun org-table-insert-row (&optional arg)
8436 "Insert a new row above the current line into the table.
8437 With prefix ARG, insert below the current line."
8438 (interactive "P")
8439 (if (not (org-at-table-p))
8440 (error "Not at a table"))
8441 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8442 (new (org-table-clean-line line)))
8443 ;; Fix the first field if necessary
8444 (if (string-match "^[ \t]*| *[#$] *|" line)
8445 (setq new (replace-match (match-string 0 line) t t new)))
8446 (beginning-of-line (if arg 2 1))
8447 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8448 (beginning-of-line 0)
8449 (re-search-forward "| ?" (point-at-eol) t)
8450 (and (or org-table-may-need-update org-table-overlay-coordinates)
8451 (org-table-align))
8452 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8454 (defun org-table-insert-hline (&optional above)
8455 "Insert a horizontal-line below the current line into the table.
8456 With prefix ABOVE, insert above the current line."
8457 (interactive "P")
8458 (if (not (org-at-table-p))
8459 (error "Not at a table"))
8460 (let ((line (org-table-clean-line
8461 (buffer-substring (point-at-bol) (point-at-eol))))
8462 (col (current-column)))
8463 (while (string-match "|\\( +\\)|" line)
8464 (setq line (replace-match
8465 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8466 ?-) "|") t t line)))
8467 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8468 (beginning-of-line (if above 1 2))
8469 (insert line "\n")
8470 (beginning-of-line (if above 1 -1))
8471 (move-to-column col)
8472 (and org-table-overlay-coordinates (org-table-align))))
8474 (defun org-table-hline-and-move (&optional same-column)
8475 "Insert a hline and move to the row below that line."
8476 (interactive "P")
8477 (let ((col (org-table-current-column)))
8478 (org-table-maybe-eval-formula)
8479 (org-table-maybe-recalculate-line)
8480 (org-table-insert-hline)
8481 (end-of-line 2)
8482 (if (looking-at "\n[ \t]*|-")
8483 (progn (insert "\n|") (org-table-align))
8484 (org-table-next-field))
8485 (if same-column (org-table-goto-column col))))
8487 (defun org-table-clean-line (s)
8488 "Convert a table line S into a string with only \"|\" and space.
8489 In particular, this does handle wide and invisible characters."
8490 (if (string-match "^[ \t]*|-" s)
8491 ;; It's a hline, just map the characters
8492 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8493 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8494 (setq s (replace-match
8495 (concat "|" (make-string (org-string-width (match-string 1 s))
8496 ?\ ) "|")
8497 t t s)))
8500 (defun org-table-kill-row ()
8501 "Delete the current row or horizontal line from the table."
8502 (interactive)
8503 (if (not (org-at-table-p))
8504 (error "Not at a table"))
8505 (let ((col (current-column))
8506 (dline (org-table-current-dline)))
8507 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8508 (if (not (org-at-table-p)) (beginning-of-line 0))
8509 (move-to-column col)
8510 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8511 dline -1 dline)))
8513 (defun org-table-sort-lines (with-case &optional sorting-type)
8514 "Sort table lines according to the column at point.
8516 The position of point indicates the column to be used for
8517 sorting, and the range of lines is the range between the nearest
8518 horizontal separator lines, or the entire table of no such lines
8519 exist. If point is before the first column, you will be prompted
8520 for the sorting column. If there is an active region, the mark
8521 specifies the first line and the sorting column, while point
8522 should be in the last line to be included into the sorting.
8524 The command then prompts for the sorting type which can be
8525 alphabetically, numerically, or by time (as given in a time stamp
8526 in the field). Sorting in reverse order is also possible.
8528 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8530 If SORTING-TYPE is specified when this function is called from a Lisp
8531 program, no prompting will take place. SORTING-TYPE must be a character,
8532 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8533 should be done in reverse order."
8534 (interactive "P")
8535 (let* ((thisline (org-current-line))
8536 (thiscol (org-table-current-column))
8537 beg end bcol ecol tend tbeg column lns pos)
8538 (when (equal thiscol 0)
8539 (if (interactive-p)
8540 (setq thiscol
8541 (string-to-number
8542 (read-string "Use column N for sorting: ")))
8543 (setq thiscol 1))
8544 (org-table-goto-column thiscol))
8545 (org-table-check-inside-data-field)
8546 (if (org-region-active-p)
8547 (progn
8548 (setq beg (region-beginning) end (region-end))
8549 (goto-char beg)
8550 (setq column (org-table-current-column)
8551 beg (point-at-bol))
8552 (goto-char end)
8553 (setq end (point-at-bol 2)))
8554 (setq column (org-table-current-column)
8555 pos (point)
8556 tbeg (org-table-begin)
8557 tend (org-table-end))
8558 (if (re-search-backward org-table-hline-regexp tbeg t)
8559 (setq beg (point-at-bol 2))
8560 (goto-char tbeg)
8561 (setq beg (point-at-bol 1)))
8562 (goto-char pos)
8563 (if (re-search-forward org-table-hline-regexp tend t)
8564 (setq end (point-at-bol 1))
8565 (goto-char tend)
8566 (setq end (point-at-bol))))
8567 (setq beg (move-marker (make-marker) beg)
8568 end (move-marker (make-marker) end))
8569 (untabify beg end)
8570 (goto-char beg)
8571 (org-table-goto-column column)
8572 (skip-chars-backward "^|")
8573 (setq bcol (current-column))
8574 (org-table-goto-column (1+ column))
8575 (skip-chars-backward "^|")
8576 (setq ecol (1- (current-column)))
8577 (org-table-goto-column column)
8578 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8579 (org-split-string (buffer-substring beg end) "\n")))
8580 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8581 (delete-region beg end)
8582 (move-marker beg nil)
8583 (move-marker end nil)
8584 (insert (mapconcat 'cdr lns "\n") "\n")
8585 (goto-line thisline)
8586 (org-table-goto-column thiscol)
8587 (message "%d lines sorted, based on column %d" (length lns) column)))
8589 (defun org-table-cut-region (beg end)
8590 "Copy region in table to the clipboard and blank all relevant fields."
8591 (interactive "r")
8592 (org-table-copy-region beg end 'cut))
8594 (defun org-table-copy-region (beg end &optional cut)
8595 "Copy rectangular region in table to clipboard.
8596 A special clipboard is used which can only be accessed
8597 with `org-table-paste-rectangle'."
8598 (interactive "rP")
8599 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8600 region cols
8601 (rpl (if cut " " nil)))
8602 (goto-char beg)
8603 (org-table-check-inside-data-field)
8604 (setq l01 (org-current-line)
8605 c01 (org-table-current-column))
8606 (goto-char end)
8607 (org-table-check-inside-data-field)
8608 (setq l02 (org-current-line)
8609 c02 (org-table-current-column))
8610 (setq l1 (min l01 l02) l2 (max l01 l02)
8611 c1 (min c01 c02) c2 (max c01 c02))
8612 (catch 'exit
8613 (while t
8614 (catch 'nextline
8615 (if (> l1 l2) (throw 'exit t))
8616 (goto-line l1)
8617 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8618 (setq cols nil ic1 c1 ic2 c2)
8619 (while (< ic1 (1+ ic2))
8620 (push (org-table-get-field ic1 rpl) cols)
8621 (setq ic1 (1+ ic1)))
8622 (push (nreverse cols) region)
8623 (setq l1 (1+ l1)))))
8624 (setq org-table-clip (nreverse region))
8625 (if cut (org-table-align))
8626 org-table-clip))
8628 (defun org-table-paste-rectangle ()
8629 "Paste a rectangular region into a table.
8630 The upper right corner ends up in the current field. All involved fields
8631 will be overwritten. If the rectangle does not fit into the present table,
8632 the table is enlarged as needed. The process ignores horizontal separator
8633 lines."
8634 (interactive)
8635 (unless (and org-table-clip (listp org-table-clip))
8636 (error "First cut/copy a region to paste!"))
8637 (org-table-check-inside-data-field)
8638 (let* ((clip org-table-clip)
8639 (line (org-current-line))
8640 (col (org-table-current-column))
8641 (org-enable-table-editor t)
8642 (org-table-automatic-realign nil)
8643 c cols field)
8644 (while (setq cols (pop clip))
8645 (while (org-at-table-hline-p) (beginning-of-line 2))
8646 (if (not (org-at-table-p))
8647 (progn (end-of-line 0) (org-table-next-field)))
8648 (setq c col)
8649 (while (setq field (pop cols))
8650 (org-table-goto-column c nil 'force)
8651 (org-table-get-field nil field)
8652 (setq c (1+ c)))
8653 (beginning-of-line 2))
8654 (goto-line line)
8655 (org-table-goto-column col)
8656 (org-table-align)))
8658 (defun org-table-convert ()
8659 "Convert from `org-mode' table to table.el and back.
8660 Obviously, this only works within limits. When an Org-mode table is
8661 converted to table.el, all horizontal separator lines get lost, because
8662 table.el uses these as cell boundaries and has no notion of horizontal lines.
8663 A table.el table can be converted to an Org-mode table only if it does not
8664 do row or column spanning. Multiline cells will become multiple cells.
8665 Beware, Org-mode does not test if the table can be successfully converted - it
8666 blindly applies a recipe that works for simple tables."
8667 (interactive)
8668 (require 'table)
8669 (if (org-at-table.el-p)
8670 ;; convert to Org-mode table
8671 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8672 (end (move-marker (make-marker) (org-table-end t))))
8673 (table-unrecognize-region beg end)
8674 (goto-char beg)
8675 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8676 (replace-match ""))
8677 (goto-char beg))
8678 (if (org-at-table-p)
8679 ;; convert to table.el table
8680 (let ((beg (move-marker (make-marker) (org-table-begin)))
8681 (end (move-marker (make-marker) (org-table-end))))
8682 ;; first, get rid of all horizontal lines
8683 (goto-char beg)
8684 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8685 (replace-match ""))
8686 ;; insert a hline before first
8687 (goto-char beg)
8688 (org-table-insert-hline 'above)
8689 (beginning-of-line -1)
8690 ;; insert a hline after each line
8691 (while (progn (beginning-of-line 3) (< (point) end))
8692 (org-table-insert-hline))
8693 (goto-char beg)
8694 (setq end (move-marker end (org-table-end)))
8695 ;; replace "+" at beginning and ending of hlines
8696 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8697 (replace-match "\\1+-"))
8698 (goto-char beg)
8699 (while (re-search-forward "-|[ \t]*$" end t)
8700 (replace-match "-+"))
8701 (goto-char beg)))))
8703 (defun org-table-wrap-region (arg)
8704 "Wrap several fields in a column like a paragraph.
8705 This is useful if you'd like to spread the contents of a field over several
8706 lines, in order to keep the table compact.
8708 If there is an active region, and both point and mark are in the same column,
8709 the text in the column is wrapped to minimum width for the given number of
8710 lines. Generally, this makes the table more compact. A prefix ARG may be
8711 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8712 formats the selected text to two lines. If the region was longer than two
8713 lines, the remaining lines remain empty. A negative prefix argument reduces
8714 the current number of lines by that amount. The wrapped text is pasted back
8715 into the table. If you formatted it to more lines than it was before, fields
8716 further down in the table get overwritten - so you might need to make space in
8717 the table first.
8719 If there is no region, the current field is split at the cursor position and
8720 the text fragment to the right of the cursor is prepended to the field one
8721 line down.
8723 If there is no region, but you specify a prefix ARG, the current field gets
8724 blank, and the content is appended to the field above."
8725 (interactive "P")
8726 (org-table-check-inside-data-field)
8727 (if (org-region-active-p)
8728 ;; There is a region: fill as a paragraph
8729 (let* ((beg (region-beginning))
8730 (cline (save-excursion (goto-char beg) (org-current-line)))
8731 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8732 nlines)
8733 (org-table-cut-region (region-beginning) (region-end))
8734 (if (> (length (car org-table-clip)) 1)
8735 (error "Region must be limited to single column"))
8736 (setq nlines (if arg
8737 (if (< arg 1)
8738 (+ (length org-table-clip) arg)
8739 arg)
8740 (length org-table-clip)))
8741 (setq org-table-clip
8742 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8743 nil nlines)))
8744 (goto-line cline)
8745 (org-table-goto-column ccol)
8746 (org-table-paste-rectangle))
8747 ;; No region, split the current field at point
8748 (if arg
8749 ;; combine with field above
8750 (let ((s (org-table-blank-field))
8751 (col (org-table-current-column)))
8752 (beginning-of-line 0)
8753 (while (org-at-table-hline-p) (beginning-of-line 0))
8754 (org-table-goto-column col)
8755 (skip-chars-forward "^|")
8756 (skip-chars-backward " ")
8757 (insert " " (org-trim s))
8758 (org-table-align))
8759 ;; split field
8760 (when (looking-at "\\([^|]+\\)+|")
8761 (let ((s (match-string 1)))
8762 (replace-match " |")
8763 (goto-char (match-beginning 0))
8764 (org-table-next-row)
8765 (insert (org-trim s) " ")
8766 (org-table-align))))))
8768 (defvar org-field-marker nil)
8770 (defun org-table-edit-field (arg)
8771 "Edit table field in a different window.
8772 This is mainly useful for fields that contain hidden parts.
8773 When called with a \\[universal-argument] prefix, just make the full field visible so that
8774 it can be edited in place."
8775 (interactive "P")
8776 (if arg
8777 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8778 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8779 (remove-text-properties b e '(org-cwidth t invisible t
8780 display t intangible t))
8781 (if (and (boundp 'font-lock-mode) font-lock-mode)
8782 (font-lock-fontify-block)))
8783 (let ((pos (move-marker (make-marker) (point)))
8784 (field (org-table-get-field))
8785 (cw (current-window-configuration))
8787 (org-switch-to-buffer-other-window "*Org tmp*")
8788 (erase-buffer)
8789 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8790 (let ((org-inhibit-startup t)) (org-mode))
8791 (goto-char (setq p (point-max)))
8792 (insert (org-trim field))
8793 (remove-text-properties p (point-max)
8794 '(invisible t org-cwidth t display t
8795 intangible t))
8796 (goto-char p)
8797 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8798 (org-set-local 'org-window-configuration cw)
8799 (org-set-local 'org-field-marker pos)
8800 (message "Edit and finish with C-c C-c"))))
8802 (defun org-table-finish-edit-field ()
8803 "Finish editing a table data field.
8804 Remove all newline characters, insert the result into the table, realign
8805 the table and kill the editing buffer."
8806 (let ((pos org-field-marker)
8807 (cw org-window-configuration)
8808 (cb (current-buffer))
8809 text)
8810 (goto-char (point-min))
8811 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8812 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8813 (replace-match " "))
8814 (setq text (org-trim (buffer-string)))
8815 (set-window-configuration cw)
8816 (kill-buffer cb)
8817 (select-window (get-buffer-window (marker-buffer pos)))
8818 (goto-char pos)
8819 (move-marker pos nil)
8820 (org-table-check-inside-data-field)
8821 (org-table-get-field nil text)
8822 (org-table-align)
8823 (message "New field value inserted")))
8825 (defun org-trim (s)
8826 "Remove whitespace at beginning and end of string."
8827 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
8828 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
8831 (defun org-wrap (string &optional width lines)
8832 "Wrap string to either a number of lines, or a width in characters.
8833 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8834 that costs. If there is a word longer than WIDTH, the text is actually
8835 wrapped to the length of that word.
8836 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8837 many lines, whatever width that takes.
8838 The return value is a list of lines, without newlines at the end."
8839 (let* ((words (org-split-string string "[ \t\n]+"))
8840 (maxword (apply 'max (mapcar 'org-string-width words)))
8841 w ll)
8842 (cond (width
8843 (org-do-wrap words (max maxword width)))
8844 (lines
8845 (setq w maxword)
8846 (setq ll (org-do-wrap words maxword))
8847 (if (<= (length ll) lines)
8849 (setq ll words)
8850 (while (> (length ll) lines)
8851 (setq w (1+ w))
8852 (setq ll (org-do-wrap words w)))
8853 ll))
8854 (t (error "Cannot wrap this")))))
8857 (defun org-do-wrap (words width)
8858 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8859 (let (lines line)
8860 (while words
8861 (setq line (pop words))
8862 (while (and words (< (+ (length line) (length (car words))) width))
8863 (setq line (concat line " " (pop words))))
8864 (setq lines (push line lines)))
8865 (nreverse lines)))
8867 (defun org-split-string (string &optional separators)
8868 "Splits STRING into substrings at SEPARATORS.
8869 No empty strings are returned if there are matches at the beginning
8870 and end of string."
8871 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8872 (start 0)
8873 notfirst
8874 (list nil))
8875 (while (and (string-match rexp string
8876 (if (and notfirst
8877 (= start (match-beginning 0))
8878 (< start (length string)))
8879 (1+ start) start))
8880 (< (match-beginning 0) (length string)))
8881 (setq notfirst t)
8882 (or (eq (match-beginning 0) 0)
8883 (and (eq (match-beginning 0) (match-end 0))
8884 (eq (match-beginning 0) start))
8885 (setq list
8886 (cons (substring string start (match-beginning 0))
8887 list)))
8888 (setq start (match-end 0)))
8889 (or (eq start (length string))
8890 (setq list
8891 (cons (substring string start)
8892 list)))
8893 (nreverse list)))
8895 (defun org-table-map-tables (function)
8896 "Apply FUNCTION to the start of all tables in the buffer."
8897 (save-excursion
8898 (save-restriction
8899 (widen)
8900 (goto-char (point-min))
8901 (while (re-search-forward org-table-any-line-regexp nil t)
8902 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8903 (beginning-of-line 1)
8904 (if (looking-at org-table-line-regexp)
8905 (save-excursion (funcall function)))
8906 (re-search-forward org-table-any-border-regexp nil 1))))
8907 (message "Mapping tables: done"))
8909 (defvar org-timecnt) ; dynamically scoped parameter
8911 (defun org-table-sum (&optional beg end nlast)
8912 "Sum numbers in region of current table column.
8913 The result will be displayed in the echo area, and will be available
8914 as kill to be inserted with \\[yank].
8916 If there is an active region, it is interpreted as a rectangle and all
8917 numbers in that rectangle will be summed. If there is no active
8918 region and point is located in a table column, sum all numbers in that
8919 column.
8921 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8922 numbers are assumed to be times as well (in decimal hours) and the
8923 numbers are added as such.
8925 If NLAST is a number, only the NLAST fields will actually be summed."
8926 (interactive)
8927 (save-excursion
8928 (let (col (org-timecnt 0) diff h m s org-table-clip)
8929 (cond
8930 ((and beg end)) ; beg and end given explicitly
8931 ((org-region-active-p)
8932 (setq beg (region-beginning) end (region-end)))
8934 (setq col (org-table-current-column))
8935 (goto-char (org-table-begin))
8936 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8937 (error "No table data"))
8938 (org-table-goto-column col)
8939 (setq beg (point))
8940 (goto-char (org-table-end))
8941 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8942 (error "No table data"))
8943 (org-table-goto-column col)
8944 (setq end (point))))
8945 (let* ((items (apply 'append (org-table-copy-region beg end)))
8946 (items1 (cond ((not nlast) items)
8947 ((>= nlast (length items)) items)
8948 (t (setq items (reverse items))
8949 (setcdr (nthcdr (1- nlast) items) nil)
8950 (nreverse items))))
8951 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8952 items1)))
8953 (res (apply '+ numbers))
8954 (sres (if (= org-timecnt 0)
8955 (format "%g" res)
8956 (setq diff (* 3600 res)
8957 h (floor (/ diff 3600)) diff (mod diff 3600)
8958 m (floor (/ diff 60)) diff (mod diff 60)
8959 s diff)
8960 (format "%d:%02d:%02d" h m s))))
8961 (kill-new sres)
8962 (if (interactive-p)
8963 (message "%s"
8964 (substitute-command-keys
8965 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8966 (length numbers) sres))))
8967 sres))))
8969 (defun org-table-get-number-for-summing (s)
8970 (let (n)
8971 (if (string-match "^ *|? *" s)
8972 (setq s (replace-match "" nil nil s)))
8973 (if (string-match " *|? *$" s)
8974 (setq s (replace-match "" nil nil s)))
8975 (setq n (string-to-number s))
8976 (cond
8977 ((and (string-match "0" s)
8978 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8979 ((string-match "\\`[ \t]+\\'" s) nil)
8980 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8981 (let ((h (string-to-number (or (match-string 1 s) "0")))
8982 (m (string-to-number (or (match-string 2 s) "0")))
8983 (s (string-to-number (or (match-string 4 s) "0"))))
8984 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
8985 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8986 ((equal n 0) nil)
8987 (t n))))
8989 (defun org-table-current-field-formula (&optional key noerror)
8990 "Return the formula active for the current field.
8991 Assumes that specials are in place.
8992 If KEY is given, return the key to this formula.
8993 Otherwise return the formula preceeded with \"=\" or \":=\"."
8994 (let* ((name (car (rassoc (list (org-current-line)
8995 (org-table-current-column))
8996 org-table-named-field-locations)))
8997 (col (org-table-current-column))
8998 (scol (int-to-string col))
8999 (ref (format "@%d$%d" (org-table-current-dline) col))
9000 (stored-list (org-table-get-stored-formulas noerror))
9001 (ass (or (assoc name stored-list)
9002 (assoc ref stored-list)
9003 (assoc scol stored-list))))
9004 (if key
9005 (car ass)
9006 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9007 (cdr ass))))))
9009 (defun org-table-get-formula (&optional equation named)
9010 "Read a formula from the minibuffer, offer stored formula as default.
9011 When NAMED is non-nil, look for a named equation."
9012 (let* ((stored-list (org-table-get-stored-formulas))
9013 (name (car (rassoc (list (org-current-line)
9014 (org-table-current-column))
9015 org-table-named-field-locations)))
9016 (ref (format "@%d$%d" (org-table-current-dline)
9017 (org-table-current-column)))
9018 (refass (assoc ref stored-list))
9019 (scol (if named
9020 (if name name ref)
9021 (int-to-string (org-table-current-column))))
9022 (dummy (and (or name refass) (not named)
9023 (not (y-or-n-p "Replace field formula with column formula? " ))
9024 (error "Abort")))
9025 (name (or name ref))
9026 (org-table-may-need-update nil)
9027 (stored (cdr (assoc scol stored-list)))
9028 (eq (cond
9029 ((and stored equation (string-match "^ *=? *$" equation))
9030 stored)
9031 ((stringp equation)
9032 equation)
9033 (t (org-table-formula-from-user
9034 (read-string
9035 (org-table-formula-to-user
9036 (format "%s formula %s%s="
9037 (if named "Field" "Column")
9038 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9039 scol))
9040 (if stored (org-table-formula-to-user stored) "")
9041 'org-table-formula-history
9042 )))))
9043 mustsave)
9044 (when (not (string-match "\\S-" eq))
9045 ;; remove formula
9046 (setq stored-list (delq (assoc scol stored-list) stored-list))
9047 (org-table-store-formulas stored-list)
9048 (error "Formula removed"))
9049 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9050 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9051 (if (and name (not named))
9052 ;; We set the column equation, delete the named one.
9053 (setq stored-list (delq (assoc name stored-list) stored-list)
9054 mustsave t))
9055 (if stored
9056 (setcdr (assoc scol stored-list) eq)
9057 (setq stored-list (cons (cons scol eq) stored-list)))
9058 (if (or mustsave (not (equal stored eq)))
9059 (org-table-store-formulas stored-list))
9060 eq))
9062 (defun org-table-store-formulas (alist)
9063 "Store the list of formulas below the current table."
9064 (setq alist (sort alist 'org-table-formula-less-p))
9065 (save-excursion
9066 (goto-char (org-table-end))
9067 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9068 (progn
9069 ;; don't overwrite TBLFM, we might use text properties to store stuff
9070 (goto-char (match-beginning 2))
9071 (delete-region (match-beginning 2) (match-end 0)))
9072 (insert "#+TBLFM:"))
9073 (insert " "
9074 (mapconcat (lambda (x)
9075 (concat
9076 (if (equal (string-to-char (car x)) ?@) "" "$")
9077 (car x) "=" (cdr x)))
9078 alist "::")
9079 "\n")))
9081 (defsubst org-table-formula-make-cmp-string (a)
9082 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9083 (concat
9084 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9085 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9086 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9088 (defun org-table-formula-less-p (a b)
9089 "Compare two formulas for sorting."
9090 (let ((as (org-table-formula-make-cmp-string (car a)))
9091 (bs (org-table-formula-make-cmp-string (car b))))
9092 (and as bs (string< as bs))))
9094 (defun org-table-get-stored-formulas (&optional noerror)
9095 "Return an alist with the stored formulas directly after current table."
9096 (interactive)
9097 (let (scol eq eq-alist strings string seen)
9098 (save-excursion
9099 (goto-char (org-table-end))
9100 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9101 (setq strings (org-split-string (match-string 2) " *:: *"))
9102 (while (setq string (pop strings))
9103 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9104 (setq scol (if (match-end 2)
9105 (match-string 2 string)
9106 (match-string 1 string))
9107 eq (match-string 3 string)
9108 eq-alist (cons (cons scol eq) eq-alist))
9109 (if (member scol seen)
9110 (if noerror
9111 (progn
9112 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9113 (ding)
9114 (sit-for 2))
9115 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9116 (push scol seen))))))
9117 (nreverse eq-alist)))
9119 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9120 "Modify the equations after the table structure has been edited.
9121 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9122 For all numbers larger than LIMIT, shift them by DELTA."
9123 (save-excursion
9124 (goto-char (org-table-end))
9125 (when (looking-at "#\\+TBLFM:")
9126 (let ((re (concat key "\\([0-9]+\\)"))
9127 (re2
9128 (when remove
9129 (if (equal key "$")
9130 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9131 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9132 s n a)
9133 (when remove
9134 (while (re-search-forward re2 (point-at-eol) t)
9135 (replace-match "")))
9136 (while (re-search-forward re (point-at-eol) t)
9137 (setq s (match-string 1) n (string-to-number s))
9138 (cond
9139 ((setq a (assoc s replace))
9140 (replace-match (concat key (cdr a)) t t))
9141 ((and limit (> n limit))
9142 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9144 (defun org-table-get-specials ()
9145 "Get the column names and local parameters for this table."
9146 (save-excursion
9147 (let ((beg (org-table-begin)) (end (org-table-end))
9148 names name fields fields1 field cnt
9149 c v l line col types dlines hlines)
9150 (setq org-table-column-names nil
9151 org-table-local-parameters nil
9152 org-table-named-field-locations nil
9153 org-table-current-begin-line nil
9154 org-table-current-begin-pos nil
9155 org-table-current-line-types nil)
9156 (goto-char beg)
9157 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9158 (setq names (org-split-string (match-string 1) " *| *")
9159 cnt 1)
9160 (while (setq name (pop names))
9161 (setq cnt (1+ cnt))
9162 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9163 (push (cons name (int-to-string cnt)) org-table-column-names))))
9164 (setq org-table-column-names (nreverse org-table-column-names))
9165 (setq org-table-column-name-regexp
9166 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9167 (goto-char beg)
9168 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9169 (setq fields (org-split-string (match-string 1) " *| *"))
9170 (while (setq field (pop fields))
9171 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9172 (push (cons (match-string 1 field) (match-string 2 field))
9173 org-table-local-parameters))))
9174 (goto-char beg)
9175 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9176 (setq c (match-string 1)
9177 fields (org-split-string (match-string 2) " *| *"))
9178 (save-excursion
9179 (beginning-of-line (if (equal c "_") 2 0))
9180 (setq line (org-current-line) col 1)
9181 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9182 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9183 (while (and fields1 (setq field (pop fields)))
9184 (setq v (pop fields1) col (1+ col))
9185 (when (and (stringp field) (stringp v)
9186 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9187 (push (cons field v) org-table-local-parameters)
9188 (push (list field line col) org-table-named-field-locations))))
9189 ;; Analyse the line types
9190 (goto-char beg)
9191 (setq org-table-current-begin-line (org-current-line)
9192 org-table-current-begin-pos (point)
9193 l org-table-current-begin-line)
9194 (while (looking-at "[ \t]*|\\(-\\)?")
9195 (push (if (match-end 1) 'hline 'dline) types)
9196 (if (match-end 1) (push l hlines) (push l dlines))
9197 (beginning-of-line 2)
9198 (setq l (1+ l)))
9199 (setq org-table-current-line-types (apply 'vector (nreverse types))
9200 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9201 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9203 (defun org-table-maybe-eval-formula ()
9204 "Check if the current field starts with \"=\" or \":=\".
9205 If yes, store the formula and apply it."
9206 ;; We already know we are in a table. Get field will only return a formula
9207 ;; when appropriate. It might return a separator line, but no problem.
9208 (when org-table-formula-evaluate-inline
9209 (let* ((field (org-trim (or (org-table-get-field) "")))
9210 named eq)
9211 (when (string-match "^:?=\\(.*\\)" field)
9212 (setq named (equal (string-to-char field) ?:)
9213 eq (match-string 1 field))
9214 (if (or (fboundp 'calc-eval)
9215 (equal (substring eq 0 (min 2 (length eq))) "'("))
9216 (org-table-eval-formula (if named '(4) nil)
9217 (org-table-formula-from-user eq))
9218 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9220 (defvar org-recalc-commands nil
9221 "List of commands triggering the recalculation of a line.
9222 Will be filled automatically during use.")
9224 (defvar org-recalc-marks
9225 '((" " . "Unmarked: no special line, no automatic recalculation")
9226 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9227 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9228 ("!" . "Column name definition line. Reference in formula as $name.")
9229 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9230 ("_" . "Names for values in row below this one.")
9231 ("^" . "Names for values in row above this one.")))
9233 (defun org-table-rotate-recalc-marks (&optional newchar)
9234 "Rotate the recalculation mark in the first column.
9235 If in any row, the first field is not consistent with a mark,
9236 insert a new column for the markers.
9237 When there is an active region, change all the lines in the region,
9238 after prompting for the marking character.
9239 After each change, a message will be displayed indicating the meaning
9240 of the new mark."
9241 (interactive)
9242 (unless (org-at-table-p) (error "Not at a table"))
9243 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9244 (beg (org-table-begin))
9245 (end (org-table-end))
9246 (l (org-current-line))
9247 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9248 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9249 (have-col
9250 (save-excursion
9251 (goto-char beg)
9252 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9253 (col (org-table-current-column))
9254 (forcenew (car (assoc newchar org-recalc-marks)))
9255 epos new)
9256 (when l1
9257 (message "Change region to what mark? Type # * ! $ or SPC: ")
9258 (setq newchar (char-to-string (read-char-exclusive))
9259 forcenew (car (assoc newchar org-recalc-marks))))
9260 (if (and newchar (not forcenew))
9261 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9262 newchar))
9263 (if l1 (goto-line l1))
9264 (save-excursion
9265 (beginning-of-line 1)
9266 (unless (looking-at org-table-dataline-regexp)
9267 (error "Not at a table data line")))
9268 (unless have-col
9269 (org-table-goto-column 1)
9270 (org-table-insert-column)
9271 (org-table-goto-column (1+ col)))
9272 (setq epos (point-at-eol))
9273 (save-excursion
9274 (beginning-of-line 1)
9275 (org-table-get-field
9276 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9277 (concat " "
9278 (setq new (or forcenew
9279 (cadr (member (match-string 1) marks))))
9280 " ")
9281 " # ")))
9282 (if (and l1 l2)
9283 (progn
9284 (goto-line l1)
9285 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9286 (and (looking-at org-table-dataline-regexp)
9287 (org-table-get-field 1 (concat " " new " "))))
9288 (goto-line l1)))
9289 (if (not (= epos (point-at-eol))) (org-table-align))
9290 (goto-line l)
9291 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9293 (defun org-table-maybe-recalculate-line ()
9294 "Recompute the current line if marked for it, and if we haven't just done it."
9295 (interactive)
9296 (and org-table-allow-automatic-line-recalculation
9297 (not (and (memq last-command org-recalc-commands)
9298 (equal org-last-recalc-line (org-current-line))))
9299 (save-excursion (beginning-of-line 1)
9300 (looking-at org-table-auto-recalculate-regexp))
9301 (org-table-recalculate) t))
9303 (defvar org-table-formula-debug nil
9304 "Non-nil means, debug table formulas.
9305 When nil, simply write \"#ERROR\" in corrupted fields.")
9306 (make-variable-buffer-local 'org-table-formula-debug)
9308 (defvar modes)
9309 (defsubst org-set-calc-mode (var &optional value)
9310 (if (stringp var)
9311 (setq var (assoc var '(("D" calc-angle-mode deg)
9312 ("R" calc-angle-mode rad)
9313 ("F" calc-prefer-frac t)
9314 ("S" calc-symbolic-mode t)))
9315 value (nth 2 var) var (nth 1 var)))
9316 (if (memq var modes)
9317 (setcar (cdr (memq var modes)) value)
9318 (cons var (cons value modes)))
9319 modes)
9321 (defun org-table-eval-formula (&optional arg equation
9322 suppress-align suppress-const
9323 suppress-store suppress-analysis)
9324 "Replace the table field value at the cursor by the result of a calculation.
9326 This function makes use of Dave Gillespie's Calc package, in my view the
9327 most exciting program ever written for GNU Emacs. So you need to have Calc
9328 installed in order to use this function.
9330 In a table, this command replaces the value in the current field with the
9331 result of a formula. It also installs the formula as the \"current\" column
9332 formula, by storing it in a special line below the table. When called
9333 with a `C-u' prefix, the current field must ba a named field, and the
9334 formula is installed as valid in only this specific field.
9336 When called with two `C-u' prefixes, insert the active equation
9337 for the field back into the current field, so that it can be
9338 edited there. This is useful in order to use \\[org-table-show-reference]
9339 to check the referenced fields.
9341 When called, the command first prompts for a formula, which is read in
9342 the minibuffer. Previously entered formulas are available through the
9343 history list, and the last used formula is offered as a default.
9344 These stored formulas are adapted correctly when moving, inserting, or
9345 deleting columns with the corresponding commands.
9347 The formula can be any algebraic expression understood by the Calc package.
9348 For details, see the Org-mode manual.
9350 This function can also be called from Lisp programs and offers
9351 additional arguments: EQUATION can be the formula to apply. If this
9352 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9353 used to speed-up recursive calls by by-passing unnecessary aligns.
9354 SUPPRESS-CONST suppresses the interpretation of constants in the
9355 formula, assuming that this has been done already outside the function.
9356 SUPPRESS-STORE means the formula should not be stored, either because
9357 it is already stored, or because it is a modified equation that should
9358 not overwrite the stored one."
9359 (interactive "P")
9360 (org-table-check-inside-data-field)
9361 (or suppress-analysis (org-table-get-specials))
9362 (if (equal arg '(16))
9363 (let ((eq (org-table-current-field-formula)))
9364 (or eq (error "No equation active for current field"))
9365 (org-table-get-field nil eq)
9366 (org-table-align)
9367 (setq org-table-may-need-update t))
9368 (let* (fields
9369 (ndown (if (integerp arg) arg 1))
9370 (org-table-automatic-realign nil)
9371 (case-fold-search nil)
9372 (down (> ndown 1))
9373 (formula (if (and equation suppress-store)
9374 equation
9375 (org-table-get-formula equation (equal arg '(4)))))
9376 (n0 (org-table-current-column))
9377 (modes (copy-sequence org-calc-default-modes))
9378 (numbers nil) ; was a variable, now fixed default
9379 (keep-empty nil)
9380 n form form0 bw fmt x ev orig c lispp literal)
9381 ;; Parse the format string. Since we have a lot of modes, this is
9382 ;; a lot of work. However, I think calc still uses most of the time.
9383 (if (string-match ";" formula)
9384 (let ((tmp (org-split-string formula ";")))
9385 (setq formula (car tmp)
9386 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9387 (nth 1 tmp)))
9388 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9389 (setq c (string-to-char (match-string 1 fmt))
9390 n (string-to-number (match-string 2 fmt)))
9391 (if (= c ?p)
9392 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9393 (setq modes (org-set-calc-mode
9394 'calc-float-format
9395 (list (cdr (assoc c '((?n . float) (?f . fix)
9396 (?s . sci) (?e . eng))))
9397 n))))
9398 (setq fmt (replace-match "" t t fmt)))
9399 (if (string-match "[NT]" fmt)
9400 (setq numbers (equal (match-string 0 fmt) "N")
9401 fmt (replace-match "" t t fmt)))
9402 (if (string-match "L" fmt)
9403 (setq literal t
9404 fmt (replace-match "" t t fmt)))
9405 (if (string-match "E" fmt)
9406 (setq keep-empty t
9407 fmt (replace-match "" t t fmt)))
9408 (while (string-match "[DRFS]" fmt)
9409 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9410 (setq fmt (replace-match "" t t fmt)))
9411 (unless (string-match "\\S-" fmt)
9412 (setq fmt nil))))
9413 (if (and (not suppress-const) org-table-formula-use-constants)
9414 (setq formula (org-table-formula-substitute-names formula)))
9415 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9416 (while (> ndown 0)
9417 (setq fields (org-split-string
9418 (org-no-properties
9419 (buffer-substring (point-at-bol) (point-at-eol)))
9420 " *| *"))
9421 (if (eq numbers t)
9422 (setq fields (mapcar
9423 (lambda (x) (number-to-string (string-to-number x)))
9424 fields)))
9425 (setq ndown (1- ndown))
9426 (setq form (copy-sequence formula)
9427 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9428 (if (and lispp literal) (setq lispp 'literal))
9429 ;; Check for old vertical references
9430 (setq form (org-rewrite-old-row-references form))
9431 ;; Insert complex ranges
9432 (while (string-match org-table-range-regexp form)
9433 (setq form
9434 (replace-match
9435 (save-match-data
9436 (org-table-make-reference
9437 (org-table-get-range (match-string 0 form) nil n0)
9438 keep-empty numbers lispp))
9439 t t form)))
9440 ;; Insert simple ranges
9441 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9442 (setq form
9443 (replace-match
9444 (save-match-data
9445 (org-table-make-reference
9446 (org-sublist
9447 fields (string-to-number (match-string 1 form))
9448 (string-to-number (match-string 2 form)))
9449 keep-empty numbers lispp))
9450 t t form)))
9451 (setq form0 form)
9452 ;; Insert the references to fields in same row
9453 (while (string-match "\\$\\([0-9]+\\)" form)
9454 (setq n (string-to-number (match-string 1 form))
9455 x (nth (1- (if (= n 0) n0 n)) fields))
9456 (unless x (error "Invalid field specifier \"%s\""
9457 (match-string 0 form)))
9458 (setq form (replace-match
9459 (save-match-data
9460 (org-table-make-reference x nil numbers lispp))
9461 t t form)))
9463 (if lispp
9464 (setq ev (condition-case nil
9465 (eval (eval (read form)))
9466 (error "#ERROR"))
9467 ev (if (numberp ev) (number-to-string ev) ev))
9468 (or (fboundp 'calc-eval)
9469 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9470 (setq ev (calc-eval (cons form modes)
9471 (if numbers 'num))))
9473 (when org-table-formula-debug
9474 (with-output-to-temp-buffer "*Substitution History*"
9475 (princ (format "Substitution history of formula
9476 Orig: %s
9477 $xyz-> %s
9478 @r$c-> %s
9479 $1-> %s\n" orig formula form0 form))
9480 (if (listp ev)
9481 (princ (format " %s^\nError: %s"
9482 (make-string (car ev) ?\-) (nth 1 ev)))
9483 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9484 ev (or fmt "NONE")
9485 (if fmt (format fmt (string-to-number ev)) ev)))))
9486 (setq bw (get-buffer-window "*Substitution History*"))
9487 (shrink-window-if-larger-than-buffer bw)
9488 (unless (and (interactive-p) (not ndown))
9489 (unless (let (inhibit-redisplay)
9490 (y-or-n-p "Debugging Formula. Continue to next? "))
9491 (org-table-align)
9492 (error "Abort"))
9493 (delete-window bw)
9494 (message "")))
9495 (if (listp ev) (setq fmt nil ev "#ERROR"))
9496 (org-table-justify-field-maybe
9497 (if fmt (format fmt (string-to-number ev)) ev))
9498 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9499 (call-interactively 'org-return)
9500 (setq ndown 0)))
9501 (and down (org-table-maybe-recalculate-line))
9502 (or suppress-align (and org-table-may-need-update
9503 (org-table-align))))))
9505 (defun org-table-put-field-property (prop value)
9506 (save-excursion
9507 (put-text-property (progn (skip-chars-backward "^|") (point))
9508 (progn (skip-chars-forward "^|") (point))
9509 prop value)))
9511 (defun org-table-get-range (desc &optional tbeg col highlight)
9512 "Get a calc vector from a column, accorting to descriptor DESC.
9513 Optional arguments TBEG and COL can give the beginning of the table and
9514 the current column, to avoid unnecessary parsing.
9515 HIGHLIGHT means, just highlight the range."
9516 (if (not (equal (string-to-char desc) ?@))
9517 (setq desc (concat "@" desc)))
9518 (save-excursion
9519 (or tbeg (setq tbeg (org-table-begin)))
9520 (or col (setq col (org-table-current-column)))
9521 (let ((thisline (org-current-line))
9522 beg end c1 c2 r1 r2 rangep tmp)
9523 (unless (string-match org-table-range-regexp desc)
9524 (error "Invalid table range specifier `%s'" desc))
9525 (setq rangep (match-end 3)
9526 r1 (and (match-end 1) (match-string 1 desc))
9527 r2 (and (match-end 4) (match-string 4 desc))
9528 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9529 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9531 (and c1 (setq c1 (+ (string-to-number c1)
9532 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9533 (and c2 (setq c2 (+ (string-to-number c2)
9534 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9535 (if (equal r1 "") (setq r1 nil))
9536 (if (equal r2 "") (setq r2 nil))
9537 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9538 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9539 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9540 (if (not r1) (setq r1 thisline))
9541 (if (not r2) (setq r2 thisline))
9542 (if (not c1) (setq c1 col))
9543 (if (not c2) (setq c2 col))
9544 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9545 ;; just one field
9546 (progn
9547 (goto-line r1)
9548 (while (not (looking-at org-table-dataline-regexp))
9549 (beginning-of-line 2))
9550 (prog1 (org-trim (org-table-get-field c1))
9551 (if highlight (org-table-highlight-rectangle (point) (point)))))
9552 ;; A range, return a vector
9553 ;; First sort the numbers to get a regular ractangle
9554 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9555 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9556 (goto-line r1)
9557 (while (not (looking-at org-table-dataline-regexp))
9558 (beginning-of-line 2))
9559 (org-table-goto-column c1)
9560 (setq beg (point))
9561 (goto-line r2)
9562 (while (not (looking-at org-table-dataline-regexp))
9563 (beginning-of-line 0))
9564 (org-table-goto-column c2)
9565 (setq end (point))
9566 (if highlight
9567 (org-table-highlight-rectangle
9568 beg (progn (skip-chars-forward "^|\n") (point))))
9569 ;; return string representation of calc vector
9570 (mapcar 'org-trim
9571 (apply 'append (org-table-copy-region beg end)))))))
9573 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9574 "Analyze descriptor DESC and retrieve the corresponding line number.
9575 The cursor is currently in line CLINE, the table begins in line BLINE,
9576 and TABLE is a vector with line types."
9577 (if (string-match "^[0-9]+$" desc)
9578 (aref org-table-dlines (string-to-number desc))
9579 (setq cline (or cline (org-current-line))
9580 bline (or bline org-table-current-begin-line)
9581 table (or table org-table-current-line-types))
9582 (if (or
9583 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9584 ;; 1 2 3 4 5 6
9585 (and (not (match-end 3)) (not (match-end 6)))
9586 (and (match-end 3) (match-end 6) (not (match-end 5))))
9587 (error "invalid row descriptor `%s'" desc))
9588 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9589 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9590 (odir (and (match-end 5) (match-string 5 desc)))
9591 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9592 (i (- cline bline))
9593 (rel (and (match-end 6)
9594 (or (and (match-end 1) (not (match-end 3)))
9595 (match-end 5)))))
9596 (if (and hn (not hdir))
9597 (progn
9598 (setq i 0 hdir "+")
9599 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9600 (if (and (not hn) on (not odir))
9601 (error "should never happen");;(aref org-table-dlines on)
9602 (if (and hn (> hn 0))
9603 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9604 (if on
9605 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9606 (+ bline i)))))
9608 (defun org-find-row-type (table i type backwards relative n)
9609 (let ((l (length table)))
9610 (while (> n 0)
9611 (while (and (setq i (+ i (if backwards -1 1)))
9612 (>= i 0) (< i l)
9613 (not (eq (aref table i) type))
9614 (if (and relative (eq (aref table i) 'hline))
9615 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9616 t)))
9617 (setq n (1- n)))
9618 (if (or (< i 0) (>= i l))
9619 (error "Row descriptior leads outside table")
9620 i)))
9622 (defun org-rewrite-old-row-references (s)
9623 (if (string-match "&[-+0-9I]" s)
9624 (error "Formula contains old &row reference, please rewrite using @-syntax")
9627 (defun org-table-make-reference (elements keep-empty numbers lispp)
9628 "Convert list ELEMENTS to something appropriate to insert into formula.
9629 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9630 NUMBERS indicates that everything should be converted to numbers.
9631 LISPP means to return something appropriate for a Lisp list."
9632 (if (stringp elements) ; just a single val
9633 (if lispp
9634 (if (eq lispp 'literal)
9635 elements
9636 (prin1-to-string (if numbers (string-to-number elements) elements)))
9637 (if (equal elements "") (setq elements "0"))
9638 (if numbers (number-to-string (string-to-number elements)) elements))
9639 (unless keep-empty
9640 (setq elements
9641 (delq nil
9642 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9643 elements))))
9644 (setq elements (or elements '("0")))
9645 (if lispp
9646 (mapconcat
9647 (lambda (x)
9648 (if (eq lispp 'literal)
9650 (prin1-to-string (if numbers (string-to-number x) x))))
9651 elements " ")
9652 (concat "[" (mapconcat
9653 (lambda (x)
9654 (if numbers (number-to-string (string-to-number x)) x))
9655 elements
9656 ",") "]"))))
9658 (defun org-table-recalculate (&optional all noalign)
9659 "Recalculate the current table line by applying all stored formulas.
9660 With prefix arg ALL, do this for all lines in the table."
9661 (interactive "P")
9662 (or (memq this-command org-recalc-commands)
9663 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9664 (unless (org-at-table-p) (error "Not at a table"))
9665 (if (equal all '(16))
9666 (org-table-iterate)
9667 (org-table-get-specials)
9668 (let* ((eqlist (sort (org-table-get-stored-formulas)
9669 (lambda (a b) (string< (car a) (car b)))))
9670 (inhibit-redisplay (not debug-on-error))
9671 (line-re org-table-dataline-regexp)
9672 (thisline (org-current-line))
9673 (thiscol (org-table-current-column))
9674 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9675 ;; Insert constants in all formulas
9676 (setq eqlist
9677 (mapcar (lambda (x)
9678 (setcdr x (org-table-formula-substitute-names (cdr x)))
9680 eqlist))
9681 ;; Split the equation list
9682 (while (setq eq (pop eqlist))
9683 (if (<= (string-to-char (car eq)) ?9)
9684 (push eq eqlnum)
9685 (push eq eqlname)))
9686 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9687 (if all
9688 (progn
9689 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9690 (goto-char (setq beg (org-table-begin)))
9691 (if (re-search-forward org-table-calculate-mark-regexp end t)
9692 ;; This is a table with marked lines, compute selected lines
9693 (setq line-re org-table-recalculate-regexp)
9694 ;; Move forward to the first non-header line
9695 (if (and (re-search-forward org-table-dataline-regexp end t)
9696 (re-search-forward org-table-hline-regexp end t)
9697 (re-search-forward org-table-dataline-regexp end t))
9698 (setq beg (match-beginning 0))
9699 nil))) ;; just leave beg where it is
9700 (setq beg (point-at-bol)
9701 end (move-marker (make-marker) (1+ (point-at-eol)))))
9702 (goto-char beg)
9703 (and all (message "Re-applying formulas to full table..."))
9705 ;; First find the named fields, and mark them untouchanble
9706 (remove-text-properties beg end '(org-untouchable t))
9707 (while (setq eq (pop eqlname))
9708 (setq name (car eq)
9709 a (assoc name org-table-named-field-locations))
9710 (and (not a)
9711 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9712 (setq a (list name
9713 (aref org-table-dlines
9714 (string-to-number (match-string 1 name)))
9715 (string-to-number (match-string 2 name)))))
9716 (when (and a (or all (equal (nth 1 a) thisline)))
9717 (message "Re-applying formula to field: %s" name)
9718 (goto-line (nth 1 a))
9719 (org-table-goto-column (nth 2 a))
9720 (push (append a (list (cdr eq))) eqlname1)
9721 (org-table-put-field-property :org-untouchable t)))
9723 ;; Now evauluate the column formulas, but skip fields covered by
9724 ;; field formulas
9725 (goto-char beg)
9726 (while (re-search-forward line-re end t)
9727 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9728 ;; Unprotected line, recalculate
9729 (and all (message "Re-applying formulas to full table...(line %d)"
9730 (setq cnt (1+ cnt))))
9731 (setq org-last-recalc-line (org-current-line))
9732 (setq eql eqlnum)
9733 (while (setq entry (pop eql))
9734 (goto-line org-last-recalc-line)
9735 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9736 (unless (get-text-property (point) :org-untouchable)
9737 (org-table-eval-formula nil (cdr entry)
9738 'noalign 'nocst 'nostore 'noanalysis)))))
9740 ;; Now evaluate the field formulas
9741 (while (setq eq (pop eqlname1))
9742 (message "Re-applying formula to field: %s" (car eq))
9743 (goto-line (nth 1 eq))
9744 (org-table-goto-column (nth 2 eq))
9745 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9746 'nostore 'noanalysis))
9748 (goto-line thisline)
9749 (org-table-goto-column thiscol)
9750 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9751 (or noalign (and org-table-may-need-update (org-table-align))
9752 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9754 ;; back to initial position
9755 (message "Re-applying formulas...done")
9756 (goto-line thisline)
9757 (org-table-goto-column thiscol)
9758 (or noalign (and org-table-may-need-update (org-table-align))
9759 (and all (message "Re-applying formulas...done"))))))
9761 (defun org-table-iterate (&optional arg)
9762 "Recalculate the table until it does not change anymore."
9763 (interactive "P")
9764 (let ((imax (if arg (prefix-numeric-value arg) 10))
9765 (i 0)
9766 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9767 thistbl)
9768 (catch 'exit
9769 (while (< i imax)
9770 (setq i (1+ i))
9771 (org-table-recalculate 'all)
9772 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9773 (if (not (string= lasttbl thistbl))
9774 (setq lasttbl thistbl)
9775 (if (> i 1)
9776 (message "Convergence after %d iterations" i)
9777 (message "Table was already stable"))
9778 (throw 'exit t)))
9779 (error "No convergence after %d iterations" i))))
9781 (defun org-table-formula-substitute-names (f)
9782 "Replace $const with values in string F."
9783 (message "form %s" f) (sit-for 1)
9784 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
9785 ;; First, check for column names
9786 (while (setq start (string-match org-table-column-name-regexp f start))
9787 (setq start (1+ start))
9788 (setq a (assoc (match-string 1 f) org-table-column-names))
9789 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9790 ;; Parameters and constants
9791 (setq start 0)
9792 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9793 (setq start (1+ start))
9794 (if (setq a (save-match-data
9795 (org-table-get-constant (match-string 1 f))))
9796 (setq f (replace-match
9797 (concat (if pp "(") a (if pp ")")) t t f))))
9798 (if org-table-formula-debug
9799 (put-text-property 0 (length f) :orig-formula f1 f))
9802 (defun org-table-get-constant (const)
9803 "Find the value for a parameter or constant in a formula.
9804 Parameters get priority."
9805 (or (cdr (assoc const org-table-local-parameters))
9806 (cdr (assoc const org-table-formula-constants-local))
9807 (cdr (assoc const org-table-formula-constants))
9808 (and (fboundp 'constants-get) (constants-get const))
9809 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9810 (org-entry-get nil (substring const 5) 'inherit))
9811 "#UNDEFINED_NAME"))
9813 (defvar org-table-fedit-map
9814 (let ((map (make-sparse-keymap)))
9815 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9816 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9817 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9818 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9819 (org-defkey map "\C-c?" 'org-table-show-reference)
9820 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9821 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9822 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9823 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9824 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9825 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9826 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9827 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9828 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
9829 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
9830 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
9831 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
9832 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
9833 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
9834 map))
9836 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
9837 '("Edit-Formulas"
9838 ["Finish and Install" org-table-fedit-finish t]
9839 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
9840 ["Abort" org-table-fedit-abort t]
9841 "--"
9842 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
9843 ["Complete Lisp Symbol" lisp-complete-symbol t]
9844 "--"
9845 "Shift Reference at Point"
9846 ["Up" org-table-fedit-ref-up t]
9847 ["Down" org-table-fedit-ref-down t]
9848 ["Left" org-table-fedit-ref-left t]
9849 ["Right" org-table-fedit-ref-right t]
9851 "Change Test Row for Column Formulas"
9852 ["Up" org-table-fedit-line-up t]
9853 ["Down" org-table-fedit-line-down t]
9854 "--"
9855 ["Scroll Table Window" org-table-fedit-scroll t]
9856 ["Scroll Table Window down" org-table-fedit-scroll-down t]
9857 ["Show Table Grid" org-table-fedit-toggle-coordinates
9858 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
9859 org-table-overlay-coordinates)]
9860 "--"
9861 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
9862 :style toggle :selected org-table-buffer-is-an]))
9864 (defvar org-pos)
9866 (defun org-table-edit-formulas ()
9867 "Edit the formulas of the current table in a separate buffer."
9868 (interactive)
9869 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
9870 (beginning-of-line 0))
9871 (unless (org-at-table-p) (error "Not at a table"))
9872 (org-table-get-specials)
9873 (let ((key (org-table-current-field-formula 'key 'noerror))
9874 (eql (sort (org-table-get-stored-formulas 'noerror)
9875 'org-table-formula-less-p))
9876 (pos (move-marker (make-marker) (point)))
9877 (startline 1)
9878 (wc (current-window-configuration))
9879 (titles '((column . "# Column Formulas\n")
9880 (field . "# Field Formulas\n")
9881 (named . "# Named Field Formulas\n")))
9882 entry s type title)
9883 (org-switch-to-buffer-other-window "*Edit Formulas*")
9884 (erase-buffer)
9885 ;; Keep global-font-lock-mode from turning on font-lock-mode
9886 (let ((font-lock-global-modes '(not fundamental-mode)))
9887 (fundamental-mode))
9888 (org-set-local 'font-lock-global-modes (list 'not major-mode))
9889 (org-set-local 'org-pos pos)
9890 (org-set-local 'org-window-configuration wc)
9891 (use-local-map org-table-fedit-map)
9892 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
9893 (easy-menu-add org-table-fedit-menu)
9894 (setq startline (org-current-line))
9895 (while (setq entry (pop eql))
9896 (setq type (cond
9897 ((equal (string-to-char (car entry)) ?@) 'field)
9898 ((string-match "^[0-9]" (car entry)) 'column)
9899 (t 'named)))
9900 (when (setq title (assq type titles))
9901 (or (bobp) (insert "\n"))
9902 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
9903 (setq titles (delq title titles)))
9904 (if (equal key (car entry)) (setq startline (org-current-line)))
9905 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
9906 (car entry) " = " (cdr entry) "\n"))
9907 (remove-text-properties 0 (length s) '(face nil) s)
9908 (insert s))
9909 (if (eq org-table-use-standard-references t)
9910 (org-table-fedit-toggle-ref-type))
9911 (goto-line startline)
9912 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
9914 (defun org-table-fedit-post-command ()
9915 (when (not (memq this-command '(lisp-complete-symbol)))
9916 (let ((win (selected-window)))
9917 (save-excursion
9918 (condition-case nil
9919 (org-table-show-reference)
9920 (error nil))
9921 (select-window win)))))
9923 (defun org-table-formula-to-user (s)
9924 "Convert a formula from internal to user representation."
9925 (if (eq org-table-use-standard-references t)
9926 (org-table-convert-refs-to-an s)
9929 (defun org-table-formula-from-user (s)
9930 "Convert a formula from user to internal representation."
9931 (if org-table-use-standard-references
9932 (org-table-convert-refs-to-rc s)
9935 (defun org-table-convert-refs-to-rc (s)
9936 "Convert spreadsheet references from AB7 to @7$28.
9937 Works for single references, but also for entire formulas and even the
9938 full TBLFM line."
9939 (let ((start 0))
9940 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
9941 (cond
9942 ((match-end 3)
9943 ;; format match, just advance
9944 (setq start (match-end 0)))
9945 ((and (> (match-beginning 0) 0)
9946 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
9947 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
9948 ;; 3.e5 or something like this.
9949 (setq start (match-end 0)))
9951 (setq start (match-beginning 0)
9952 s (replace-match
9953 (if (equal (match-string 2 s) "&")
9954 (format "$%d" (org-letters-to-number (match-string 1 s)))
9955 (format "@%d$%d"
9956 (string-to-number (match-string 2 s))
9957 (org-letters-to-number (match-string 1 s))))
9958 t t s)))))
9961 (defun org-table-convert-refs-to-an (s)
9962 "Convert spreadsheet references from to @7$28 to AB7.
9963 Works for single references, but also for entire formulas and even the
9964 full TBLFM line."
9965 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
9966 (setq s (replace-match
9967 (format "%s%d"
9968 (org-number-to-letters
9969 (string-to-number (match-string 2 s)))
9970 (string-to-number (match-string 1 s)))
9971 t t s)))
9972 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
9973 (setq s (replace-match (concat "\\1"
9974 (org-number-to-letters
9975 (string-to-number (match-string 2 s))) "&")
9976 t nil s)))
9979 (defun org-letters-to-number (s)
9980 "Convert a base 26 number represented by letters into an integer.
9981 For example: AB -> 28."
9982 (let ((n 0))
9983 (setq s (upcase s))
9984 (while (> (length s) 0)
9985 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
9986 s (substring s 1)))
9989 (defun org-number-to-letters (n)
9990 "Convert an integer into a base 26 number represented by letters.
9991 For example: 28 -> AB."
9992 (let ((s ""))
9993 (while (> n 0)
9994 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
9995 n (/ (1- n) 26)))
9998 (defun org-table-fedit-convert-buffer (function)
9999 "Convert all references in this buffer, using FUNTION."
10000 (let ((line (org-current-line)))
10001 (goto-char (point-min))
10002 (while (not (eobp))
10003 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10004 (delete-region (point) (point-at-eol))
10005 (or (eobp) (forward-char 1)))
10006 (goto-line line)))
10008 (defun org-table-fedit-toggle-ref-type ()
10009 "Convert all references in the buffer from B3 to @3$2 and back."
10010 (interactive)
10011 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10012 (org-table-fedit-convert-buffer
10013 (if org-table-buffer-is-an
10014 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10015 (message "Reference type switched to %s"
10016 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10018 (defun org-table-fedit-ref-up ()
10019 "Shift the reference at point one row/hline up."
10020 (interactive)
10021 (org-table-fedit-shift-reference 'up))
10022 (defun org-table-fedit-ref-down ()
10023 "Shift the reference at point one row/hline down."
10024 (interactive)
10025 (org-table-fedit-shift-reference 'down))
10026 (defun org-table-fedit-ref-left ()
10027 "Shift the reference at point one field to the left."
10028 (interactive)
10029 (org-table-fedit-shift-reference 'left))
10030 (defun org-table-fedit-ref-right ()
10031 "Shift the reference at point one field to the right."
10032 (interactive)
10033 (org-table-fedit-shift-reference 'right))
10035 (defun org-table-fedit-shift-reference (dir)
10036 (cond
10037 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10038 (if (memq dir '(left right))
10039 (org-rematch-and-replace 1 (eq dir 'left))
10040 (error "Cannot shift reference in this direction")))
10041 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10042 ;; A B3-like reference
10043 (if (memq dir '(up down))
10044 (org-rematch-and-replace 2 (eq dir 'up))
10045 (org-rematch-and-replace 1 (eq dir 'left))))
10046 ((org-at-regexp-p
10047 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10048 ;; An internal reference
10049 (if (memq dir '(up down))
10050 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10051 (org-rematch-and-replace 5 (eq dir 'left))))))
10053 (defun org-rematch-and-replace (n &optional decr hline)
10054 "Re-match the group N, and replace it with the shifted refrence."
10055 (or (match-end n) (error "Cannot shift reference in this direction"))
10056 (goto-char (match-beginning n))
10057 (and (looking-at (regexp-quote (match-string n)))
10058 (replace-match (org-shift-refpart (match-string 0) decr hline)
10059 t t)))
10061 (defun org-shift-refpart (ref &optional decr hline)
10062 "Shift a refrence part REF.
10063 If DECR is set, decrease the references row/column, else increase.
10064 If HLINE is set, this may be a hline reference, it certainly is not
10065 a translation reference."
10066 (save-match-data
10067 (let* ((sign (string-match "^[-+]" ref)) n)
10069 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10070 (cond
10071 ((and hline (string-match "^I+" ref))
10072 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10073 (setq n (+ n (if decr -1 1)))
10074 (if (= n 0) (setq n (+ n (if decr -1 1))))
10075 (if sign
10076 (setq sign (if (< n 0) "-" "+") n (abs n))
10077 (setq n (max 1 n)))
10078 (concat sign (make-string n ?I)))
10080 ((string-match "^[0-9]+" ref)
10081 (setq n (string-to-number (concat sign ref)))
10082 (setq n (+ n (if decr -1 1)))
10083 (if sign
10084 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10085 (number-to-string (max 1 n))))
10087 ((string-match "^[a-zA-Z]+" ref)
10088 (org-number-to-letters
10089 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10091 (t (error "Cannot shift reference"))))))
10093 (defun org-table-fedit-toggle-coordinates ()
10094 "Toggle the display of coordinates in the refrenced table."
10095 (interactive)
10096 (let ((pos (marker-position org-pos)))
10097 (with-current-buffer (marker-buffer org-pos)
10098 (save-excursion
10099 (goto-char pos)
10100 (org-table-toggle-coordinate-overlays)))))
10102 (defun org-table-fedit-finish (&optional arg)
10103 "Parse the buffer for formula definitions and install them.
10104 With prefix ARG, apply the new formulas to the table."
10105 (interactive "P")
10106 (org-table-remove-rectangle-highlight)
10107 (if org-table-use-standard-references
10108 (progn
10109 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10110 (setq org-table-buffer-is-an nil)))
10111 (let ((pos org-pos) eql var form)
10112 (goto-char (point-min))
10113 (while (re-search-forward
10114 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10115 nil t)
10116 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10117 form (match-string 3))
10118 (setq form (org-trim form))
10119 (when (not (equal form ""))
10120 (while (string-match "[ \t]*\n[ \t]*" form)
10121 (setq form (replace-match " " t t form)))
10122 (when (assoc var eql)
10123 (error "Double formulas for %s" var))
10124 (push (cons var form) eql)))
10125 (setq org-pos nil)
10126 (set-window-configuration org-window-configuration)
10127 (select-window (get-buffer-window (marker-buffer pos)))
10128 (goto-char pos)
10129 (unless (org-at-table-p)
10130 (error "Lost table position - cannot install formulae"))
10131 (org-table-store-formulas eql)
10132 (move-marker pos nil)
10133 (kill-buffer "*Edit Formulas*")
10134 (if arg
10135 (org-table-recalculate 'all)
10136 (message "New formulas installed - press C-u C-c C-c to apply."))))
10138 (defun org-table-fedit-abort ()
10139 "Abort editing formulas, without installing the changes."
10140 (interactive)
10141 (org-table-remove-rectangle-highlight)
10142 (let ((pos org-pos))
10143 (set-window-configuration org-window-configuration)
10144 (select-window (get-buffer-window (marker-buffer pos)))
10145 (goto-char pos)
10146 (move-marker pos nil)
10147 (message "Formula editing aborted without installing changes")))
10149 (defun org-table-fedit-lisp-indent ()
10150 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10151 (interactive)
10152 (let ((pos (point)) beg end ind)
10153 (beginning-of-line 1)
10154 (cond
10155 ((looking-at "[ \t]")
10156 (goto-char pos)
10157 (call-interactively 'lisp-indent-line))
10158 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10159 ((not (fboundp 'pp-buffer))
10160 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10161 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10162 (goto-char (- (match-end 0) 2))
10163 (setq beg (point))
10164 (setq ind (make-string (current-column) ?\ ))
10165 (condition-case nil (forward-sexp 1)
10166 (error
10167 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10168 (setq end (point))
10169 (save-restriction
10170 (narrow-to-region beg end)
10171 (if (eq last-command this-command)
10172 (progn
10173 (goto-char (point-min))
10174 (setq this-command nil)
10175 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10176 (replace-match " ")))
10177 (pp-buffer)
10178 (untabify (point-min) (point-max))
10179 (goto-char (1+ (point-min)))
10180 (while (re-search-forward "^." nil t)
10181 (beginning-of-line 1)
10182 (insert ind))
10183 (goto-char (point-max))
10184 (backward-delete-char 1)))
10185 (goto-char beg))
10186 (t nil))))
10188 (defvar org-show-positions nil)
10190 (defun org-table-show-reference (&optional local)
10191 "Show the location/value of the $ expression at point."
10192 (interactive)
10193 (org-table-remove-rectangle-highlight)
10194 (catch 'exit
10195 (let ((pos (if local (point) org-pos))
10196 (face2 'highlight)
10197 (org-inhibit-highlight-removal t)
10198 (win (selected-window))
10199 (org-show-positions nil)
10200 var name e what match dest)
10201 (if local (org-table-get-specials))
10202 (setq what (cond
10203 ((or (org-at-regexp-p org-table-range-regexp2)
10204 (org-at-regexp-p org-table-translate-regexp)
10205 (org-at-regexp-p org-table-range-regexp))
10206 (setq match
10207 (save-match-data
10208 (org-table-convert-refs-to-rc (match-string 0))))
10209 'range)
10210 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10211 ((org-at-regexp-p "\\$[0-9]+") 'column)
10212 ((not local) nil)
10213 (t (error "No reference at point")))
10214 match (and what (or match (match-string 0))))
10215 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10216 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10217 'secondary-selection))
10218 (org-add-hook 'before-change-functions
10219 'org-table-remove-rectangle-highlight)
10220 (if (eq what 'name) (setq var (substring match 1)))
10221 (when (eq what 'range)
10222 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10223 (setq match (org-table-formula-substitute-names match)))
10224 (unless local
10225 (save-excursion
10226 (end-of-line 1)
10227 (re-search-backward "^\\S-" nil t)
10228 (beginning-of-line 1)
10229 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10230 (setq dest
10231 (save-match-data
10232 (org-table-convert-refs-to-rc (match-string 1))))
10233 (org-table-add-rectangle-overlay
10234 (match-beginning 1) (match-end 1) face2))))
10235 (if (and (markerp pos) (marker-buffer pos))
10236 (if (get-buffer-window (marker-buffer pos))
10237 (select-window (get-buffer-window (marker-buffer pos)))
10238 (org-switch-to-buffer-other-window (get-buffer-window
10239 (marker-buffer pos)))))
10240 (goto-char pos)
10241 (org-table-force-dataline)
10242 (when dest
10243 (setq name (substring dest 1))
10244 (cond
10245 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10246 (setq e (assoc name org-table-named-field-locations))
10247 (goto-line (nth 1 e))
10248 (org-table-goto-column (nth 2 e)))
10249 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10250 (let ((l (string-to-number (match-string 1 dest)))
10251 (c (string-to-number (match-string 2 dest))))
10252 (goto-line (aref org-table-dlines l))
10253 (org-table-goto-column c)))
10254 (t (org-table-goto-column (string-to-number name))))
10255 (move-marker pos (point))
10256 (org-table-highlight-rectangle nil nil face2))
10257 (cond
10258 ((equal dest match))
10259 ((not match))
10260 ((eq what 'range)
10261 (condition-case nil
10262 (save-excursion
10263 (org-table-get-range match nil nil 'highlight))
10264 (error nil)))
10265 ((setq e (assoc var org-table-named-field-locations))
10266 (goto-line (nth 1 e))
10267 (org-table-goto-column (nth 2 e))
10268 (org-table-highlight-rectangle (point) (point))
10269 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10270 ((setq e (assoc var org-table-column-names))
10271 (org-table-goto-column (string-to-number (cdr e)))
10272 (org-table-highlight-rectangle (point) (point))
10273 (goto-char (org-table-begin))
10274 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10275 (org-table-end) t)
10276 (progn
10277 (goto-char (match-beginning 1))
10278 (org-table-highlight-rectangle)
10279 (message "Named column (column %s)" (cdr e)))
10280 (error "Column name not found")))
10281 ((eq what 'column)
10282 ;; column number
10283 (org-table-goto-column (string-to-number (substring match 1)))
10284 (org-table-highlight-rectangle (point) (point))
10285 (message "Column %s" (substring match 1)))
10286 ((setq e (assoc var org-table-local-parameters))
10287 (goto-char (org-table-begin))
10288 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10289 (progn
10290 (goto-char (match-beginning 1))
10291 (org-table-highlight-rectangle)
10292 (message "Local parameter."))
10293 (error "Parameter not found")))
10295 (cond
10296 ((not var) (error "No reference at point"))
10297 ((setq e (assoc var org-table-formula-constants-local))
10298 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10299 var (cdr e)))
10300 ((setq e (assoc var org-table-formula-constants))
10301 (message "Constant: $%s=%s in `org-table-formula-constants'."
10302 var (cdr e)))
10303 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10304 (message "Constant: $%s=%s, from `constants.el'%s."
10305 var e (format " (%s units)" constants-unit-system)))
10306 (t (error "Undefined name $%s" var)))))
10307 (goto-char pos)
10308 (when (and org-show-positions
10309 (not (memq this-command '(org-table-fedit-scroll
10310 org-table-fedit-scroll-down))))
10311 (push pos org-show-positions)
10312 (push org-table-current-begin-pos org-show-positions)
10313 (let ((min (apply 'min org-show-positions))
10314 (max (apply 'max org-show-positions)))
10315 (goto-char min) (recenter 0)
10316 (goto-char max)
10317 (or (pos-visible-in-window-p max) (recenter -1))))
10318 (select-window win))))
10320 (defun org-table-force-dataline ()
10321 "Make sure the cursor is in a dataline in a table."
10322 (unless (save-excursion
10323 (beginning-of-line 1)
10324 (looking-at org-table-dataline-regexp))
10325 (let* ((re org-table-dataline-regexp)
10326 (p1 (save-excursion (re-search-forward re nil 'move)))
10327 (p2 (save-excursion (re-search-backward re nil 'move))))
10328 (cond ((and p1 p2)
10329 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10330 p1 p2)))
10331 ((or p1 p2) (goto-char (or p1 p2)))
10332 (t (error "No table dataline around here"))))))
10334 (defun org-table-fedit-line-up ()
10335 "Move cursor one line up in the window showing the table."
10336 (interactive)
10337 (org-table-fedit-move 'previous-line))
10339 (defun org-table-fedit-line-down ()
10340 "Move cursor one line down in the window showing the table."
10341 (interactive)
10342 (org-table-fedit-move 'next-line))
10344 (defun org-table-fedit-move (command)
10345 "Move the cursor in the window shoinw the table.
10346 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10347 (let ((org-table-allow-automatic-line-recalculation nil)
10348 (pos org-pos) (win (selected-window)) p)
10349 (select-window (get-buffer-window (marker-buffer org-pos)))
10350 (setq p (point))
10351 (call-interactively command)
10352 (while (and (org-at-table-p)
10353 (org-at-table-hline-p))
10354 (call-interactively command))
10355 (or (org-at-table-p) (goto-char p))
10356 (move-marker pos (point))
10357 (select-window win)))
10359 (defun org-table-fedit-scroll (N)
10360 (interactive "p")
10361 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10362 (scroll-other-window N)))
10364 (defun org-table-fedit-scroll-down (N)
10365 (interactive "p")
10366 (org-table-fedit-scroll (- N)))
10368 (defvar org-table-rectangle-overlays nil)
10370 (defun org-table-add-rectangle-overlay (beg end &optional face)
10371 "Add a new overlay."
10372 (let ((ov (org-make-overlay beg end)))
10373 (org-overlay-put ov 'face (or face 'secondary-selection))
10374 (push ov org-table-rectangle-overlays)))
10376 (defun org-table-highlight-rectangle (&optional beg end face)
10377 "Highlight rectangular region in a table."
10378 (setq beg (or beg (point)) end (or end (point)))
10379 (let ((b (min beg end))
10380 (e (max beg end))
10381 l1 c1 l2 c2 tmp)
10382 (and (boundp 'org-show-positions)
10383 (setq org-show-positions (cons b (cons e org-show-positions))))
10384 (goto-char (min beg end))
10385 (setq l1 (org-current-line)
10386 c1 (org-table-current-column))
10387 (goto-char (max beg end))
10388 (setq l2 (org-current-line)
10389 c2 (org-table-current-column))
10390 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10391 (goto-line l1)
10392 (beginning-of-line 1)
10393 (loop for line from l1 to l2 do
10394 (when (looking-at org-table-dataline-regexp)
10395 (org-table-goto-column c1)
10396 (skip-chars-backward "^|\n") (setq beg (point))
10397 (org-table-goto-column c2)
10398 (skip-chars-forward "^|\n") (setq end (point))
10399 (org-table-add-rectangle-overlay beg end face))
10400 (beginning-of-line 2))
10401 (goto-char b))
10402 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10404 (defun org-table-remove-rectangle-highlight (&rest ignore)
10405 "Remove the rectangle overlays."
10406 (unless org-inhibit-highlight-removal
10407 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10408 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10409 (setq org-table-rectangle-overlays nil)))
10411 (defvar org-table-coordinate-overlays nil
10412 "Collects the cooordinate grid overlays, so that they can be removed.")
10413 (make-variable-buffer-local 'org-table-coordinate-overlays)
10415 (defun org-table-overlay-coordinates ()
10416 "Add overlays to the table at point, to show row/column coordinates."
10417 (interactive)
10418 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10419 (setq org-table-coordinate-overlays nil)
10420 (save-excursion
10421 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10422 (goto-char (org-table-begin))
10423 (while (org-at-table-p)
10424 (setq eol (point-at-eol))
10425 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10426 (push ov org-table-coordinate-overlays)
10427 (setq hline (looking-at org-table-hline-regexp))
10428 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10429 (format "%4d" (setq id (1+ id)))))
10430 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10431 (when hline
10432 (setq ic 0)
10433 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10434 (setq beg (1+ (match-beginning 0))
10435 ic (1+ ic)
10436 s1 (concat "$" (int-to-string ic))
10437 s2 (org-number-to-letters ic)
10438 str (if (eq org-table-use-standard-references t) s2 s1))
10439 (setq ov (org-make-overlay beg (+ beg (length str))))
10440 (push ov org-table-coordinate-overlays)
10441 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10442 (beginning-of-line 2)))))
10444 (defun org-table-toggle-coordinate-overlays ()
10445 "Toggle the display of Row/Column numbers in tables."
10446 (interactive)
10447 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10448 (message "Row/Column number display turned %s"
10449 (if org-table-overlay-coordinates "on" "off"))
10450 (if (and (org-at-table-p) org-table-overlay-coordinates)
10451 (org-table-align))
10452 (unless org-table-overlay-coordinates
10453 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10454 (setq org-table-coordinate-overlays nil)))
10456 (defun org-table-toggle-formula-debugger ()
10457 "Toggle the formula debugger in tables."
10458 (interactive)
10459 (setq org-table-formula-debug (not org-table-formula-debug))
10460 (message "Formula debugging has been turned %s"
10461 (if org-table-formula-debug "on" "off")))
10463 ;;; The orgtbl minor mode
10465 ;; Define a minor mode which can be used in other modes in order to
10466 ;; integrate the org-mode table editor.
10468 ;; This is really a hack, because the org-mode table editor uses several
10469 ;; keys which normally belong to the major mode, for example the TAB and
10470 ;; RET keys. Here is how it works: The minor mode defines all the keys
10471 ;; necessary to operate the table editor, but wraps the commands into a
10472 ;; function which tests if the cursor is currently inside a table. If that
10473 ;; is the case, the table editor command is executed. However, when any of
10474 ;; those keys is used outside a table, the function uses `key-binding' to
10475 ;; look up if the key has an associated command in another currently active
10476 ;; keymap (minor modes, major mode, global), and executes that command.
10477 ;; There might be problems if any of the keys used by the table editor is
10478 ;; otherwise used as a prefix key.
10480 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10481 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10482 ;; addresses this by checking explicitly for both bindings.
10484 ;; The optimized version (see variable `orgtbl-optimized') takes over
10485 ;; all keys which are bound to `self-insert-command' in the *global map*.
10486 ;; Some modes bind other commands to simple characters, for example
10487 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10488 ;; active, this binding is ignored inside tables and replaced with a
10489 ;; modified self-insert.
10491 (defvar orgtbl-mode nil
10492 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10493 table editor in arbitrary modes.")
10494 (make-variable-buffer-local 'orgtbl-mode)
10496 (defvar orgtbl-mode-map (make-keymap)
10497 "Keymap for `orgtbl-mode'.")
10499 ;;;###autoload
10500 (defun turn-on-orgtbl ()
10501 "Unconditionally turn on `orgtbl-mode'."
10502 (orgtbl-mode 1))
10504 (defvar org-old-auto-fill-inhibit-regexp nil
10505 "Local variable used by `orgtbl-mode'")
10507 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10508 "Matches a line belonging to an orgtbl.")
10510 (defconst orgtbl-extra-font-lock-keywords
10511 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10512 0 (quote 'org-table) 'prepend))
10513 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10515 ;;;###autoload
10516 (defun orgtbl-mode (&optional arg)
10517 "The `org-mode' table editor as a minor mode for use in other modes."
10518 (interactive)
10519 (if (org-mode-p)
10520 ;; Exit without error, in case some hook functions calls this
10521 ;; by accident in org-mode.
10522 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10523 (setq orgtbl-mode
10524 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10525 (if orgtbl-mode
10526 (progn
10527 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10528 ;; Make sure we are first in minor-mode-map-alist
10529 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10530 (and c (setq minor-mode-map-alist
10531 (cons c (delq c minor-mode-map-alist)))))
10532 (org-set-local (quote org-table-may-need-update) t)
10533 (org-add-hook 'before-change-functions 'org-before-change-function
10534 nil 'local)
10535 (org-set-local 'org-old-auto-fill-inhibit-regexp
10536 auto-fill-inhibit-regexp)
10537 (org-set-local 'auto-fill-inhibit-regexp
10538 (if auto-fill-inhibit-regexp
10539 (concat orgtbl-line-start-regexp "\\|"
10540 auto-fill-inhibit-regexp)
10541 orgtbl-line-start-regexp))
10542 (org-add-to-invisibility-spec '(org-cwidth))
10543 (when (fboundp 'font-lock-add-keywords)
10544 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10545 (org-restart-font-lock))
10546 (easy-menu-add orgtbl-mode-menu)
10547 (run-hooks 'orgtbl-mode-hook))
10548 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10549 (org-cleanup-narrow-column-properties)
10550 (org-remove-from-invisibility-spec '(org-cwidth))
10551 (remove-hook 'before-change-functions 'org-before-change-function t)
10552 (when (fboundp 'font-lock-remove-keywords)
10553 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10554 (org-restart-font-lock))
10555 (easy-menu-remove orgtbl-mode-menu)
10556 (force-mode-line-update 'all))))
10558 (defun org-cleanup-narrow-column-properties ()
10559 "Remove all properties related to narrow-column invisibility."
10560 (let ((s 1))
10561 (while (setq s (text-property-any s (point-max)
10562 'display org-narrow-column-arrow))
10563 (remove-text-properties s (1+ s) '(display t)))
10564 (setq s 1)
10565 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10566 (remove-text-properties s (1+ s) '(org-cwidth t)))
10567 (setq s 1)
10568 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10569 (remove-text-properties s (1+ s) '(invisible t)))))
10571 ;; Install it as a minor mode.
10572 (put 'orgtbl-mode :included t)
10573 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10574 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10576 (defun orgtbl-make-binding (fun n &rest keys)
10577 "Create a function for binding in the table minor mode.
10578 FUN is the command to call inside a table. N is used to create a unique
10579 command name. KEYS are keys that should be checked in for a command
10580 to execute outside of tables."
10581 (eval
10582 (list 'defun
10583 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10584 '(arg)
10585 (concat "In tables, run `" (symbol-name fun) "'.\n"
10586 "Outside of tables, run the binding of `"
10587 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10588 "'.")
10589 '(interactive "p")
10590 (list 'if
10591 '(org-at-table-p)
10592 (list 'call-interactively (list 'quote fun))
10593 (list 'let '(orgtbl-mode)
10594 (list 'call-interactively
10595 (append '(or)
10596 (mapcar (lambda (k)
10597 (list 'key-binding k))
10598 keys)
10599 '('orgtbl-error))))))))
10601 (defun orgtbl-error ()
10602 "Error when there is no default binding for a table key."
10603 (interactive)
10604 (error "This key is has no function outside tables"))
10606 (defun orgtbl-setup ()
10607 "Setup orgtbl keymaps."
10608 (let ((nfunc 0)
10609 (bindings
10610 (list
10611 '([(meta shift left)] org-table-delete-column)
10612 '([(meta left)] org-table-move-column-left)
10613 '([(meta right)] org-table-move-column-right)
10614 '([(meta shift right)] org-table-insert-column)
10615 '([(meta shift up)] org-table-kill-row)
10616 '([(meta shift down)] org-table-insert-row)
10617 '([(meta up)] org-table-move-row-up)
10618 '([(meta down)] org-table-move-row-down)
10619 '("\C-c\C-w" org-table-cut-region)
10620 '("\C-c\M-w" org-table-copy-region)
10621 '("\C-c\C-y" org-table-paste-rectangle)
10622 '("\C-c-" org-table-insert-hline)
10623 '("\C-c}" org-table-toggle-coordinate-overlays)
10624 '("\C-c{" org-table-toggle-formula-debugger)
10625 '("\C-m" org-table-next-row)
10626 '([(shift return)] org-table-copy-down)
10627 '("\C-c\C-q" org-table-wrap-region)
10628 '("\C-c?" org-table-field-info)
10629 '("\C-c " org-table-blank-field)
10630 '("\C-c+" org-table-sum)
10631 '("\C-c=" org-table-eval-formula)
10632 '("\C-c'" org-table-edit-formulas)
10633 '("\C-c`" org-table-edit-field)
10634 '("\C-c*" org-table-recalculate)
10635 '("\C-c|" org-table-create-or-convert-from-region)
10636 '("\C-c^" org-table-sort-lines)
10637 '([(control ?#)] org-table-rotate-recalc-marks)))
10638 elt key fun cmd)
10639 (while (setq elt (pop bindings))
10640 (setq nfunc (1+ nfunc))
10641 (setq key (org-key (car elt))
10642 fun (nth 1 elt)
10643 cmd (orgtbl-make-binding fun nfunc key))
10644 (org-defkey orgtbl-mode-map key cmd))
10646 ;; Special treatment needed for TAB and RET
10647 (org-defkey orgtbl-mode-map [(return)]
10648 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10649 (org-defkey orgtbl-mode-map "\C-m"
10650 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10652 (org-defkey orgtbl-mode-map [(tab)]
10653 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10654 (org-defkey orgtbl-mode-map "\C-i"
10655 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10657 (org-defkey orgtbl-mode-map [(shift tab)]
10658 (orgtbl-make-binding 'org-table-previous-field 104
10659 [(shift tab)] [(tab)] "\C-i"))
10661 (org-defkey orgtbl-mode-map "\M-\C-m"
10662 (orgtbl-make-binding 'org-table-wrap-region 105
10663 "\M-\C-m" [(meta return)]))
10664 (org-defkey orgtbl-mode-map [(meta return)]
10665 (orgtbl-make-binding 'org-table-wrap-region 106
10666 [(meta return)] "\M-\C-m"))
10668 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10669 (when orgtbl-optimized
10670 ;; If the user wants maximum table support, we need to hijack
10671 ;; some standard editing functions
10672 (org-remap orgtbl-mode-map
10673 'self-insert-command 'orgtbl-self-insert-command
10674 'delete-char 'org-delete-char
10675 'delete-backward-char 'org-delete-backward-char)
10676 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10677 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10678 '("OrgTbl"
10679 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10680 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10681 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10682 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10683 "--"
10684 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10685 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10686 ["Copy Field from Above"
10687 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10688 "--"
10689 ("Column"
10690 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10691 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10692 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10693 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10694 ("Row"
10695 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10696 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10697 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10698 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10699 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10700 "--"
10701 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10702 ("Rectangle"
10703 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10704 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10705 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10706 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10707 "--"
10708 ("Radio tables"
10709 ["Insert table template" orgtbl-insert-radio-table
10710 (assq major-mode orgtbl-radio-table-templates)]
10711 ["Comment/uncomment table" orgtbl-toggle-comment t])
10712 "--"
10713 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10714 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10715 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10716 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10717 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10718 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10719 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10720 ["Sum Column/Rectangle" org-table-sum
10721 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10722 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10723 ["Debug Formulas"
10724 org-table-toggle-formula-debugger :active (org-at-table-p)
10725 :keys "C-c {"
10726 :style toggle :selected org-table-formula-debug]
10727 ["Show Col/Row Numbers"
10728 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10729 :keys "C-c }"
10730 :style toggle :selected org-table-overlay-coordinates]
10734 (defun orgtbl-ctrl-c-ctrl-c (arg)
10735 "If the cursor is inside a table, realign the table.
10736 It it is a table to be sent away to a receiver, do it.
10737 With prefix arg, also recompute table."
10738 (interactive "P")
10739 (let ((pos (point)) action)
10740 (save-excursion
10741 (beginning-of-line 1)
10742 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10743 ((looking-at "[ \t]*|") pos)
10744 ((looking-at "#\\+TBLFM:") 'recalc))))
10745 (cond
10746 ((integerp action)
10747 (goto-char action)
10748 (org-table-maybe-eval-formula)
10749 (if arg
10750 (call-interactively 'org-table-recalculate)
10751 (org-table-maybe-recalculate-line))
10752 (call-interactively 'org-table-align)
10753 (orgtbl-send-table 'maybe))
10754 ((eq action 'recalc)
10755 (save-excursion
10756 (beginning-of-line 1)
10757 (skip-chars-backward " \r\n\t")
10758 (if (org-at-table-p)
10759 (org-call-with-arg 'org-table-recalculate t))))
10760 (t (let (orgtbl-mode)
10761 (call-interactively (key-binding "\C-c\C-c")))))))
10763 (defun orgtbl-tab (arg)
10764 "Justification and field motion for `orgtbl-mode'."
10765 (interactive "P")
10766 (if arg (org-table-edit-field t)
10767 (org-table-justify-field-maybe)
10768 (org-table-next-field)))
10770 (defun orgtbl-ret ()
10771 "Justification and field motion for `orgtbl-mode'."
10772 (interactive)
10773 (org-table-justify-field-maybe)
10774 (org-table-next-row))
10776 (defun orgtbl-self-insert-command (N)
10777 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10778 If the cursor is in a table looking at whitespace, the whitespace is
10779 overwritten, and the table is not marked as requiring realignment."
10780 (interactive "p")
10781 (if (and (org-at-table-p)
10783 (and org-table-auto-blank-field
10784 (member last-command
10785 '(orgtbl-hijacker-command-100
10786 orgtbl-hijacker-command-101
10787 orgtbl-hijacker-command-102
10788 orgtbl-hijacker-command-103
10789 orgtbl-hijacker-command-104
10790 orgtbl-hijacker-command-105))
10791 (org-table-blank-field))
10793 (eq N 1)
10794 (looking-at "[^|\n]* +|"))
10795 (let (org-table-may-need-update)
10796 (goto-char (1- (match-end 0)))
10797 (delete-backward-char 1)
10798 (goto-char (match-beginning 0))
10799 (self-insert-command N))
10800 (setq org-table-may-need-update t)
10801 (let (orgtbl-mode)
10802 (call-interactively (key-binding (vector last-input-event))))))
10804 (defun org-force-self-insert (N)
10805 "Needed to enforce self-insert under remapping."
10806 (interactive "p")
10807 (self-insert-command N))
10809 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10810 "Regula expression matching exponentials as produced by calc.")
10812 (defvar org-table-clean-did-remove-column nil)
10814 (defun orgtbl-export (table target)
10815 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10816 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10817 org-table-last-alignment org-table-last-column-widths
10818 maxcol column)
10819 (if (not (fboundp func))
10820 (error "Cannot export orgtbl table to %s" target))
10821 (setq lines (org-table-clean-before-export lines))
10822 (setq table
10823 (mapcar
10824 (lambda (x)
10825 (if (string-match org-table-hline-regexp x)
10826 'hline
10827 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10828 lines))
10829 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
10830 table)))
10831 (loop for i from (1- maxcol) downto 0 do
10832 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
10833 (setq column (delq nil column))
10834 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
10835 (push (> (/ (apply '+ (mapcar (lambda (x) (if (string-match org-table-number-regexp x) 1 0)) column)) maxcol) org-table-number-fraction) org-table-last-alignment))
10836 (funcall func table nil)))
10838 (defun orgtbl-send-table (&optional maybe)
10839 "Send a tranformed version of this table to the receiver position.
10840 With argument MAYBE, fail quietly if no transformation is defined for
10841 this table."
10842 (interactive)
10843 (catch 'exit
10844 (unless (org-at-table-p) (error "Not at a table"))
10845 ;; when non-interactive, we assume align has just happened.
10846 (when (interactive-p) (org-table-align))
10847 (save-excursion
10848 (goto-char (org-table-begin))
10849 (beginning-of-line 0)
10850 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
10851 (if maybe
10852 (throw 'exit nil)
10853 (error "Don't know how to transform this table."))))
10854 (let* ((name (match-string 1))
10856 (transform (intern (match-string 2)))
10857 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
10858 (skip (plist-get params :skip))
10859 (skipcols (plist-get params :skipcols))
10860 (txt (buffer-substring-no-properties
10861 (org-table-begin) (org-table-end)))
10862 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
10863 (lines (org-table-clean-before-export lines))
10864 (i0 (if org-table-clean-did-remove-column 2 1))
10865 (table (mapcar
10866 (lambda (x)
10867 (if (string-match org-table-hline-regexp x)
10868 'hline
10869 (org-remove-by-index
10870 (org-split-string (org-trim x) "\\s-*|\\s-*")
10871 skipcols i0)))
10872 lines))
10873 (fun (if (= i0 2) 'cdr 'identity))
10874 (org-table-last-alignment
10875 (org-remove-by-index (funcall fun org-table-last-alignment)
10876 skipcols i0))
10877 (org-table-last-column-widths
10878 (org-remove-by-index (funcall fun org-table-last-column-widths)
10879 skipcols i0)))
10881 (unless (fboundp transform)
10882 (error "No such transformation function %s" transform))
10883 (setq txt (funcall transform table params))
10884 ;; Find the insertion place
10885 (save-excursion
10886 (goto-char (point-min))
10887 (unless (re-search-forward
10888 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
10889 (error "Don't know where to insert translated table"))
10890 (goto-char (match-beginning 0))
10891 (beginning-of-line 2)
10892 (setq beg (point))
10893 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
10894 (error "Cannot find end of insertion region"))
10895 (beginning-of-line 1)
10896 (delete-region beg (point))
10897 (goto-char beg)
10898 (insert txt "\n"))
10899 (message "Table converted and installed at receiver location"))))
10901 (defun org-remove-by-index (list indices &optional i0)
10902 "Remove the elements in LIST with indices in INDICES.
10903 First element has index 0, or I0 if given."
10904 (if (not indices)
10905 list
10906 (if (integerp indices) (setq indices (list indices)))
10907 (setq i0 (1- (or i0 0)))
10908 (delq :rm (mapcar (lambda (x)
10909 (setq i0 (1+ i0))
10910 (if (memq i0 indices) :rm x))
10911 list))))
10913 (defun orgtbl-toggle-comment ()
10914 "Comment or uncomment the orgtbl at point."
10915 (interactive)
10916 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
10917 (re2 (concat "^" orgtbl-line-start-regexp))
10918 (commented (save-excursion (beginning-of-line 1)
10919 (cond ((looking-at re1) t)
10920 ((looking-at re2) nil)
10921 (t (error "Not at an org table")))))
10922 (re (if commented re1 re2))
10923 beg end)
10924 (save-excursion
10925 (beginning-of-line 1)
10926 (while (looking-at re) (beginning-of-line 0))
10927 (beginning-of-line 2)
10928 (setq beg (point))
10929 (while (looking-at re) (beginning-of-line 2))
10930 (setq end (point)))
10931 (comment-region beg end (if commented '(4) nil))))
10933 (defun orgtbl-insert-radio-table ()
10934 "Insert a radio table template appropriate for this major mode."
10935 (interactive)
10936 (let* ((e (assq major-mode orgtbl-radio-table-templates))
10937 (txt (nth 1 e))
10938 name pos)
10939 (unless e (error "No radio table setup defined for %s" major-mode))
10940 (setq name (read-string "Table name: "))
10941 (while (string-match "%n" txt)
10942 (setq txt (replace-match name t t txt)))
10943 (or (bolp) (insert "\n"))
10944 (setq pos (point))
10945 (insert txt)
10946 (goto-char pos)))
10948 (defun org-get-param (params header i sym &optional hsym)
10949 "Get parameter value for symbol SYM.
10950 If this is a header line, actually get the value for the symbol with an
10951 additional \"h\" inserted after the colon.
10952 If the value is a protperty list, get the element for the current column.
10953 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
10954 (let ((val (plist-get params sym)))
10955 (and hsym header (setq val (or (plist-get params hsym) val)))
10956 (if (consp val) (plist-get val i) val)))
10958 (defun orgtbl-to-generic (table params)
10959 "Convert the orgtbl-mode TABLE to some other format.
10960 This generic routine can be used for many standard cases.
10961 TABLE is a list, each entry either the symbol `hline' for a horizontal
10962 separator line, or a list of fields for that line.
10963 PARAMS is a property list of parameters that can influence the conversion.
10964 For the generic converter, some parameters are obligatory: You need to
10965 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
10966 :splice, you must have :tstart and :tend.
10968 Valid parameters are
10970 :tstart String to start the table. Ignored when :splice is t.
10971 :tend String to end the table. Ignored when :splice is t.
10973 :splice When set to t, return only table body lines, don't wrap
10974 them into :tstart and :tend. Default is nil.
10976 :hline String to be inserted on horizontal separation lines.
10977 May be nil to ignore hlines.
10979 :lstart String to start a new table line.
10980 :lend String to end a table line
10981 :sep Separator between two fields
10982 :lfmt Format for entire line, with enough %s to capture all fields.
10983 If this is present, :lstart, :lend, and :sep are ignored.
10984 :fmt A format to be used to wrap the field, should contain
10985 %s for the original field value. For example, to wrap
10986 everything in dollars, you could use :fmt \"$%s$\".
10987 This may also be a property list with column numbers and
10988 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
10990 :hlstart :hlend :hlsep :hlfmt :hfmt
10991 Same as above, specific for the header lines in the table.
10992 All lines before the first hline are treated as header.
10993 If any of these is not present, the data line value is used.
10995 :efmt Use this format to print numbers with exponentials.
10996 The format should have %s twice for inserting mantissa
10997 and exponent, for example \"%s\\\\times10^{%s}\". This
10998 may also be a property list with column numbers and
10999 formats. :fmt will still be applied after :efmt.
11001 In addition to this, the parameters :skip and :skipcols are always handled
11002 directly by `orgtbl-send-table'. See manual."
11003 (interactive)
11004 (let* ((p params)
11005 (splicep (plist-get p :splice))
11006 (hline (plist-get p :hline))
11007 rtn line i fm efm lfmt h)
11009 ;; Do we have a header?
11010 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11011 (setq h t))
11013 ;; Put header
11014 (unless splicep
11015 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11017 ;; Now loop over all lines
11018 (while (setq line (pop table))
11019 (if (eq line 'hline)
11020 ;; A horizontal separator line
11021 (progn (if hline (push hline rtn))
11022 (setq h nil)) ; no longer in header
11023 ;; A normal line. Convert the fields, push line onto the result list
11024 (setq i 0)
11025 (setq line
11026 (mapcar
11027 (lambda (f)
11028 (setq i (1+ i)
11029 fm (org-get-param p h i :fmt :hfmt)
11030 efm (org-get-param p h i :efmt))
11031 (if (and efm (string-match orgtbl-exp-regexp f))
11032 (setq f (format
11033 efm (match-string 1 f) (match-string 2 f))))
11034 (if fm (setq f (format fm f)))
11036 line))
11037 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11038 (push (apply 'format lfmt line) rtn)
11039 (push (concat
11040 (org-get-param p h i :lstart :hlstart)
11041 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11042 (org-get-param p h i :lend :hlend))
11043 rtn))))
11045 (unless splicep
11046 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11048 (mapconcat 'identity (nreverse rtn) "\n")))
11050 (defun orgtbl-to-latex (table params)
11051 "Convert the orgtbl-mode TABLE to LaTeX.
11052 TABLE is a list, each entry either the symbol `hline' for a horizontal
11053 separator line, or a list of fields for that line.
11054 PARAMS is a property list of parameters that can influence the conversion.
11055 Supports all parameters from `orgtbl-to-generic'. Most important for
11056 LaTeX are:
11058 :splice When set to t, return only table body lines, don't wrap
11059 them into a tabular environment. Default is nil.
11061 :fmt A format to be used to wrap the field, should contain %s for the
11062 original field value. For example, to wrap everything in dollars,
11063 use :fmt \"$%s$\". This may also be a property list with column
11064 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11066 :efmt Format for transforming numbers with exponentials. The format
11067 should have %s twice for inserting mantissa and exponent, for
11068 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11069 This may also be a property list with column numbers and formats.
11071 The general parameters :skip and :skipcols have already been applied when
11072 this function is called."
11073 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11074 org-table-last-alignment ""))
11075 (params2
11076 (list
11077 :tstart (concat "\\begin{tabular}{" alignment "}")
11078 :tend "\\end{tabular}"
11079 :lstart "" :lend " \\\\" :sep " & "
11080 :efmt "%s\\,(%s)" :hline "\\hline")))
11081 (orgtbl-to-generic table (org-combine-plists params2 params))))
11083 (defun orgtbl-to-html (table params)
11084 "Convert the orgtbl-mode TABLE to LaTeX.
11085 TABLE is a list, each entry either the symbol `hline' for a horizontal
11086 separator line, or a list of fields for that line.
11087 PARAMS is a property list of parameters that can influence the conversion.
11088 Currently this function recognizes the following parameters:
11090 :splice When set to t, return only table body lines, don't wrap
11091 them into a <table> environment. Default is nil.
11093 The general parameters :skip and :skipcols have already been applied when
11094 this function is called. The function does *not* use `orgtbl-to-generic',
11095 so you cannot specify parameters for it."
11096 (let* ((splicep (plist-get params :splice))
11097 html)
11098 ;; Just call the formatter we already have
11099 ;; We need to make text lines for it, so put the fields back together.
11100 (setq html (org-format-org-table-html
11101 (mapcar
11102 (lambda (x)
11103 (if (eq x 'hline)
11104 "|----+----|"
11105 (concat "| " (mapconcat 'identity x " | ") " |")))
11106 table)
11107 splicep))
11108 (if (string-match "\n+\\'" html)
11109 (setq html (replace-match "" t t html)))
11110 html))
11112 (defun orgtbl-to-texinfo (table params)
11113 "Convert the orgtbl-mode TABLE to TeXInfo.
11114 TABLE is a list, each entry either the symbol `hline' for a horizontal
11115 separator line, or a list of fields for that line.
11116 PARAMS is a property list of parameters that can influence the conversion.
11117 Supports all parameters from `orgtbl-to-generic'. Most important for
11118 TeXInfo are:
11120 :splice nil/t When set to t, return only table body lines, don't wrap
11121 them into a multitable environment. Default is nil.
11123 :fmt fmt A format to be used to wrap the field, should contain
11124 %s for the original field value. For example, to wrap
11125 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11126 This may also be a property list with column numbers and
11127 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11129 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11130 are computed automatically from the width of the columns
11131 under org-mode.
11133 The general parameters :skip and :skipcols have already been applied when
11134 this function is called."
11135 (let* ((total (float (apply '+ org-table-last-column-widths)))
11136 (colfrac (or (plist-get params :cf)
11137 (mapconcat
11138 (lambda (x) (format "%.3f" (/ (float x) total)))
11139 org-table-last-column-widths " ")))
11140 (params2
11141 (list
11142 :tstart (concat "@multitable @columnfractions " colfrac)
11143 :tend "@end multitable"
11144 :lstart "@item " :lend "" :sep " @tab "
11145 :hlstart "@headitem ")))
11146 (orgtbl-to-generic table (org-combine-plists params2 params))))
11148 ;;;; Link Stuff
11150 ;;; Link abbreviations
11152 (defun org-link-expand-abbrev (link)
11153 "Apply replacements as defined in `org-link-abbrev-alist."
11154 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11155 (let* ((key (match-string 1 link))
11156 (as (or (assoc key org-link-abbrev-alist-local)
11157 (assoc key org-link-abbrev-alist)))
11158 (tag (and (match-end 2) (match-string 3 link)))
11159 rpl)
11160 (if (not as)
11161 link
11162 (setq rpl (cdr as))
11163 (cond
11164 ((symbolp rpl) (funcall rpl tag))
11165 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11166 (t (concat rpl tag)))))
11167 link))
11169 ;;; Storing and inserting links
11171 (defvar org-insert-link-history nil
11172 "Minibuffer history for links inserted with `org-insert-link'.")
11174 (defvar org-stored-links nil
11175 "Contains the links stored with `org-store-link'.")
11177 (defvar org-store-link-plist nil
11178 "Plist with info about the most recently link created with `org-store-link'.")
11180 (defvar org-link-protocols nil
11181 "Link protocols added to Org-mode using `org-add-link-type'.")
11183 (defvar org-store-link-functions nil
11184 "List of functions that are called to create and store a link.
11185 Each function will be called in turn until one returns a non-nil
11186 value. Each function should check if it is responsible for creating
11187 this link (for example by looking at the major mode).
11188 If not, it must exit and return nil.
11189 If yes, it should return a non-nil value after a calling
11190 `org-store-link-properties' with a list of properties and values.
11191 Special properties are:
11193 :type The link prefix. like \"http\". This must be given.
11194 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11195 This is obligatory as well.
11196 :description Optional default description for the second pair
11197 of brackets in an Org-mode link. The user can still change
11198 this when inserting this link into an Org-mode buffer.
11200 In addition to these, any additional properties can be specified
11201 and then used in remember templates.")
11203 (defun org-add-link-type (type &optional follow publish)
11204 "Add TYPE to the list of `org-link-types'.
11205 Re-compute all regular expressions depending on `org-link-types'
11206 FOLLOW and PUBLISH are two functions. Both take the link path as
11207 an argument.
11208 FOLLOW should do whatever is necessary to follow the link, for example
11209 to find a file or display a mail message.
11210 PUBLISH takes the path and retuns the string that should be used when
11211 this document is published."
11212 (add-to-list 'org-link-types type t)
11213 (org-make-link-regexps)
11214 (add-to-list 'org-link-protocols
11215 (list type follow publish)))
11217 (defun org-add-agenda-custom-command (entry)
11218 "Replace or add a command in `org-agenda-custom-commands'.
11219 This is mostly for hacking and trying a new command - once the command
11220 works you probably want to add it to `org-agenda-custom-commands' for good."
11221 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11222 (if ass
11223 (setcdr ass (cdr entry))
11224 (push entry org-agenda-custom-commands))))
11226 ;;;###autoload
11227 (defun org-store-link (arg)
11228 "\\<org-mode-map>Store an org-link to the current location.
11229 This link can later be inserted into an org-buffer with
11230 \\[org-insert-link].
11231 For some link types, a prefix arg is interpreted:
11232 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11233 For file links, arg negates `org-context-in-file-links'."
11234 (interactive "P")
11235 (setq org-store-link-plist nil) ; reset
11236 (let (link cpltxt desc description search txt)
11237 (cond
11239 ((run-hook-with-args-until-success 'org-store-link-functions)
11240 (setq link (plist-get org-store-link-plist :link)
11241 desc (or (plist-get org-store-link-plist :description) link)))
11243 ((eq major-mode 'bbdb-mode)
11244 (let ((name (bbdb-record-name (bbdb-current-record)))
11245 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11246 (setq cpltxt (concat "bbdb:" (or name company))
11247 link (org-make-link cpltxt))
11248 (org-store-link-props :type "bbdb" :name name :company company)))
11250 ((eq major-mode 'Info-mode)
11251 (setq link (org-make-link "info:"
11252 (file-name-nondirectory Info-current-file)
11253 ":" Info-current-node))
11254 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11255 ":" Info-current-node))
11256 (org-store-link-props :type "info" :file Info-current-file
11257 :node Info-current-node))
11259 ((eq major-mode 'calendar-mode)
11260 (let ((cd (calendar-cursor-to-date)))
11261 (setq link
11262 (format-time-string
11263 (car org-time-stamp-formats)
11264 (apply 'encode-time
11265 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11266 nil nil nil))))
11267 (org-store-link-props :type "calendar" :date cd)))
11269 ((or (eq major-mode 'vm-summary-mode)
11270 (eq major-mode 'vm-presentation-mode))
11271 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11272 (vm-follow-summary-cursor)
11273 (save-excursion
11274 (vm-select-folder-buffer)
11275 (let* ((message (car vm-message-pointer))
11276 (folder buffer-file-name)
11277 (subject (vm-su-subject message))
11278 (to (vm-get-header-contents message "To"))
11279 (from (vm-get-header-contents message "From"))
11280 (message-id (vm-su-message-id message)))
11281 (org-store-link-props :type "vm" :from from :to to :subject subject
11282 :message-id message-id)
11283 (setq message-id (org-remove-angle-brackets message-id))
11284 (setq folder (abbreviate-file-name folder))
11285 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11286 folder)
11287 (setq folder (replace-match "" t t folder)))
11288 (setq cpltxt (org-email-link-description))
11289 (setq link (org-make-link "vm:" folder "#" message-id)))))
11291 ((eq major-mode 'wl-summary-mode)
11292 (let* ((msgnum (wl-summary-message-number))
11293 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11294 msgnum 'message-id))
11295 (wl-message-entity
11296 (if (fboundp 'elmo-message-entity)
11297 (elmo-message-entity
11298 wl-summary-buffer-elmo-folder msgnum)
11299 (elmo-msgdb-overview-get-entity
11300 msgnum (wl-summary-buffer-msgdb))))
11301 (from (wl-summary-line-from))
11302 (to (elmo-message-entity-field wl-message-entity 'to))
11303 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11304 (wl-summary-line-subject))))
11305 (org-store-link-props :type "wl" :from from :to to
11306 :subject subject :message-id message-id)
11307 (setq message-id (org-remove-angle-brackets message-id))
11308 (setq cpltxt (org-email-link-description))
11309 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11310 "#" message-id))))
11312 ((or (equal major-mode 'mh-folder-mode)
11313 (equal major-mode 'mh-show-mode))
11314 (let ((from (org-mhe-get-header "From:"))
11315 (to (org-mhe-get-header "To:"))
11316 (message-id (org-mhe-get-header "Message-Id:"))
11317 (subject (org-mhe-get-header "Subject:")))
11318 (org-store-link-props :type "mh" :from from :to to
11319 :subject subject :message-id message-id)
11320 (setq cpltxt (org-email-link-description))
11321 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11322 (org-remove-angle-brackets message-id)))))
11324 ((eq major-mode 'rmail-mode)
11325 (save-excursion
11326 (save-restriction
11327 (rmail-narrow-to-non-pruned-header)
11328 (let ((folder buffer-file-name)
11329 (message-id (mail-fetch-field "message-id"))
11330 (from (mail-fetch-field "from"))
11331 (to (mail-fetch-field "to"))
11332 (subject (mail-fetch-field "subject")))
11333 (org-store-link-props
11334 :type "rmail" :from from :to to
11335 :subject subject :message-id message-id)
11336 (setq message-id (org-remove-angle-brackets message-id))
11337 (setq cpltxt (org-email-link-description))
11338 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11340 ((eq major-mode 'gnus-group-mode)
11341 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11342 (gnus-group-group-name)) ; version
11343 ((fboundp 'gnus-group-name)
11344 (gnus-group-name))
11345 (t "???"))))
11346 (unless group (error "Not on a group"))
11347 (org-store-link-props :type "gnus" :group group)
11348 (setq cpltxt (concat
11349 (if (org-xor arg org-usenet-links-prefer-google)
11350 "http://groups.google.com/groups?group="
11351 "gnus:")
11352 group)
11353 link (org-make-link cpltxt))))
11355 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11356 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11357 (let* ((group gnus-newsgroup-name)
11358 (article (gnus-summary-article-number))
11359 (header (gnus-summary-article-header article))
11360 (from (mail-header-from header))
11361 (message-id (mail-header-id header))
11362 (date (mail-header-date header))
11363 (subject (gnus-summary-subject-string)))
11364 (org-store-link-props :type "gnus" :from from :subject subject
11365 :message-id message-id :group group)
11366 (setq cpltxt (org-email-link-description))
11367 (if (org-xor arg org-usenet-links-prefer-google)
11368 (setq link
11369 (concat
11370 cpltxt "\n "
11371 (format "http://groups.google.com/groups?as_umsgid=%s"
11372 (org-fixup-message-id-for-http message-id))))
11373 (setq link (org-make-link "gnus:" group
11374 "#" (number-to-string article))))))
11376 ((eq major-mode 'w3-mode)
11377 (setq cpltxt (url-view-url t)
11378 link (org-make-link cpltxt))
11379 (org-store-link-props :type "w3" :url (url-view-url t)))
11381 ((eq major-mode 'w3m-mode)
11382 (setq cpltxt (or w3m-current-title w3m-current-url)
11383 link (org-make-link w3m-current-url))
11384 (org-store-link-props :type "w3m" :url (url-view-url t)))
11386 ((setq search (run-hook-with-args-until-success
11387 'org-create-file-search-functions))
11388 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11389 "::" search))
11390 (setq cpltxt (or description link)))
11392 ((eq major-mode 'image-mode)
11393 (setq cpltxt (concat "file:"
11394 (abbreviate-file-name buffer-file-name))
11395 link (org-make-link cpltxt))
11396 (org-store-link-props :type "image" :file buffer-file-name))
11398 ((eq major-mode 'dired-mode)
11399 ;; link to the file in the current line
11400 (setq cpltxt (concat "file:"
11401 (abbreviate-file-name
11402 (expand-file-name
11403 (dired-get-filename nil t))))
11404 link (org-make-link cpltxt)))
11406 ((and buffer-file-name (org-mode-p))
11407 ;; Just link to current headline
11408 (setq cpltxt (concat "file:"
11409 (abbreviate-file-name buffer-file-name)))
11410 ;; Add a context search string
11411 (when (org-xor org-context-in-file-links arg)
11412 ;; Check if we are on a target
11413 (if (org-in-regexp "<<\\(.*?\\)>>")
11414 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11415 (setq txt (cond
11416 ((org-on-heading-p) nil)
11417 ((org-region-active-p)
11418 (buffer-substring (region-beginning) (region-end)))
11419 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11420 (when (or (null txt) (string-match "\\S-" txt))
11421 (setq cpltxt
11422 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11423 desc "NONE"))))
11424 (if (string-match "::\\'" cpltxt)
11425 (setq cpltxt (substring cpltxt 0 -2)))
11426 (setq link (org-make-link cpltxt)))
11428 ((buffer-file-name (buffer-base-buffer))
11429 ;; Just link to this file here.
11430 (setq cpltxt (concat "file:"
11431 (abbreviate-file-name
11432 (buffer-file-name (buffer-base-buffer)))))
11433 ;; Add a context string
11434 (when (org-xor org-context-in-file-links arg)
11435 (setq txt (if (org-region-active-p)
11436 (buffer-substring (region-beginning) (region-end))
11437 (buffer-substring (point-at-bol) (point-at-eol))))
11438 ;; Only use search option if there is some text.
11439 (when (string-match "\\S-" txt)
11440 (setq cpltxt
11441 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11442 desc "NONE")))
11443 (setq link (org-make-link cpltxt)))
11445 ((interactive-p)
11446 (error "Cannot link to a buffer which is not visiting a file"))
11448 (t (setq link nil)))
11450 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11451 (setq link (or link cpltxt)
11452 desc (or desc cpltxt))
11453 (if (equal desc "NONE") (setq desc nil))
11455 (if (and (interactive-p) link)
11456 (progn
11457 (setq org-stored-links
11458 (cons (list link desc) org-stored-links))
11459 (message "Stored: %s" (or desc link)))
11460 (and link (org-make-link-string link desc)))))
11462 (defun org-store-link-props (&rest plist)
11463 "Store link properties, extract names and addresses."
11464 (let (x adr)
11465 (when (setq x (plist-get plist :from))
11466 (setq adr (mail-extract-address-components x))
11467 (plist-put plist :fromname (car adr))
11468 (plist-put plist :fromaddress (nth 1 adr)))
11469 (when (setq x (plist-get plist :to))
11470 (setq adr (mail-extract-address-components x))
11471 (plist-put plist :toname (car adr))
11472 (plist-put plist :toaddress (nth 1 adr))))
11473 (let ((from (plist-get plist :from))
11474 (to (plist-get plist :to)))
11475 (when (and from to org-from-is-user-regexp)
11476 (plist-put plist :fromto
11477 (if (string-match org-from-is-user-regexp from)
11478 (concat "to %t")
11479 (concat "from %f")))))
11480 (setq org-store-link-plist plist))
11482 (defun org-email-link-description (&optional fmt)
11483 "Return the description part of an email link.
11484 This takes information from `org-store-link-plist' and formats it
11485 according to FMT (default from `org-email-link-description-format')."
11486 (setq fmt (or fmt org-email-link-description-format))
11487 (let* ((p org-store-link-plist)
11488 (to (plist-get p :toaddress))
11489 (from (plist-get p :fromaddress))
11490 (table
11491 (list
11492 (cons "%c" (plist-get p :fromto))
11493 (cons "%F" (plist-get p :from))
11494 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11495 (cons "%T" (plist-get p :to))
11496 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11497 (cons "%s" (plist-get p :subject))
11498 (cons "%m" (plist-get p :message-id)))))
11499 (when (string-match "%c" fmt)
11500 ;; Check if the user wrote this message
11501 (if (and org-from-is-user-regexp from to
11502 (save-match-data (string-match org-from-is-user-regexp from)))
11503 (setq fmt (replace-match "to %t" t t fmt))
11504 (setq fmt (replace-match "from %f" t t fmt))))
11505 (org-replace-escapes fmt table)))
11507 (defun org-make-org-heading-search-string (&optional string heading)
11508 "Make search string for STRING or current headline."
11509 (interactive)
11510 (let ((s (or string (org-get-heading))))
11511 (unless (and string (not heading))
11512 ;; We are using a headline, clean up garbage in there.
11513 (if (string-match org-todo-regexp s)
11514 (setq s (replace-match "" t t s)))
11515 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11516 (setq s (replace-match "" t t s)))
11517 (setq s (org-trim s))
11518 (if (string-match (concat "^\\(" org-quote-string "\\|"
11519 org-comment-string "\\)") s)
11520 (setq s (replace-match "" t t s)))
11521 (while (string-match org-ts-regexp s)
11522 (setq s (replace-match "" t t s))))
11523 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11524 (setq s (replace-match " " t t s)))
11525 (or string (setq s (concat "*" s))) ; Add * for headlines
11526 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11528 (defun org-make-link (&rest strings)
11529 "Concatenate STRINGS."
11530 (apply 'concat strings))
11532 (defun org-make-link-string (link &optional description)
11533 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11534 (unless (string-match "\\S-" link)
11535 (error "Empty link"))
11536 (when (stringp description)
11537 ;; Remove brackets from the description, they are fatal.
11538 (while (string-match "\\[\\|\\]" description)
11539 (setq description (replace-match "" t t description))))
11540 (when (equal (org-link-escape link) description)
11541 ;; No description needed, it is identical
11542 (setq description nil))
11543 (when (and (not description)
11544 (not (equal link (org-link-escape link))))
11545 (setq description link))
11546 (concat "[[" (org-link-escape link) "]"
11547 (if description (concat "[" description "]") "")
11548 "]"))
11550 (defconst org-link-escape-chars
11551 '((" " . "%20")
11552 ("[" . "%5B")
11553 ("]" . "%5d")
11554 ("\340" . "%E0") ; `a
11555 ("\342" . "%E2") ; ^a
11556 ("\347" . "%E7") ; ,c
11557 ("\350" . "%E8") ; `e
11558 ("\351" . "%E9") ; 'e
11559 ("\352" . "%EA") ; ^e
11560 ("\356" . "%EE") ; ^i
11561 ("\364" . "%F4") ; ^o
11562 ("\371" . "%F9") ; `u
11563 ("\373" . "%FB") ; ^u
11564 (";" . "%3B")
11565 ("?" . "%3F")
11566 ("=" . "%3D")
11567 ("+" . "%2B")
11569 "Association list of escapes for some characters problematic in links.
11570 This is the list that is used for internal purposes.")
11572 (defconst org-link-escape-chars-browser
11573 '((" " . "%20"))
11574 "Association list of escapes for some characters problematic in links.
11575 This is the list that is used before handing over to the browser.")
11577 (defun org-link-escape (text &optional table)
11578 "Escape charaters in TEXT that are problematic for links."
11579 (setq table (or table org-link-escape-chars))
11580 (when text
11581 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
11582 table "\\|")))
11583 (while (string-match re text)
11584 (setq text
11585 (replace-match
11586 (cdr (assoc (match-string 0 text) table))
11587 t t text)))
11588 text)))
11590 (defun org-link-unescape (text &optional table)
11591 "Reverse the action of `org-link-escape'."
11592 (setq table (or table org-link-escape-chars))
11593 (when text
11594 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11595 table "\\|")))
11596 (while (string-match re text)
11597 (setq text
11598 (replace-match
11599 (car (rassoc (match-string 0 text) table))
11600 t t text)))
11601 text)))
11603 (defun org-xor (a b)
11604 "Exclusive or."
11605 (if a (not b) b))
11607 (defun org-get-header (header)
11608 "Find a header field in the current buffer."
11609 (save-excursion
11610 (goto-char (point-min))
11611 (let ((case-fold-search t) s)
11612 (cond
11613 ((eq header 'from)
11614 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11615 (setq s (match-string 1)))
11616 (while (string-match "\"" s)
11617 (setq s (replace-match "" t t s)))
11618 (if (string-match "[<(].*" s)
11619 (setq s (replace-match "" t t s))))
11620 ((eq header 'message-id)
11621 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11622 (setq s (match-string 1))))
11623 ((eq header 'subject)
11624 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11625 (setq s (match-string 1)))))
11626 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11627 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11628 s)))
11631 (defun org-fixup-message-id-for-http (s)
11632 "Replace special characters in a message id, so it can be used in an http query."
11633 (while (string-match "<" s)
11634 (setq s (replace-match "%3C" t t s)))
11635 (while (string-match ">" s)
11636 (setq s (replace-match "%3E" t t s)))
11637 (while (string-match "@" s)
11638 (setq s (replace-match "%40" t t s)))
11641 ;;;###autoload
11642 (defun org-insert-link-global ()
11643 "Insert a link like Org-mode does.
11644 This command can be called in any mode to insert a link in Org-mode syntax."
11645 (interactive)
11646 (org-run-like-in-org-mode 'org-insert-link))
11648 (defun org-insert-link (&optional complete-file)
11649 "Insert a link. At the prompt, enter the link.
11651 Completion can be used to select a link previously stored with
11652 `org-store-link'. When the empty string is entered (i.e. if you just
11653 press RET at the prompt), the link defaults to the most recently
11654 stored link. As SPC triggers completion in the minibuffer, you need to
11655 use M-SPC or C-q SPC to force the insertion of a space character.
11657 You will also be prompted for a description, and if one is given, it will
11658 be displayed in the buffer instead of the link.
11660 If there is already a link at point, this command will allow you to edit link
11661 and description parts.
11663 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11664 selected using completion. The path to the file will be relative to
11665 the current directory if the file is in the current directory or a
11666 subdirectory. Otherwise, the link will be the absolute path as
11667 completed in the minibuffer (i.e. normally ~/path/to/file).
11669 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11670 is in the current directory or below.
11671 With three \\[universal-argument] prefixes, negate the meaning of
11672 `org-keep-stored-link-after-insertion'."
11673 (interactive "P")
11674 (let* ((wcf (current-window-configuration))
11675 (region (if (org-region-active-p)
11676 (buffer-substring (region-beginning) (region-end))))
11677 (remove (and region (list (region-beginning) (region-end))))
11678 (desc region)
11679 tmphist ; byte-compile incorrectly complains about this
11680 link entry file)
11681 (cond
11682 ((org-in-regexp org-bracket-link-regexp 1)
11683 ;; We do have a link at point, and we are going to edit it.
11684 (setq remove (list (match-beginning 0) (match-end 0)))
11685 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11686 (setq link (read-string "Link: "
11687 (org-link-unescape
11688 (org-match-string-no-properties 1)))))
11689 ((or (org-in-regexp org-angle-link-re)
11690 (org-in-regexp org-plain-link-re))
11691 ;; Convert to bracket link
11692 (setq remove (list (match-beginning 0) (match-end 0))
11693 link (read-string "Link: "
11694 (org-remove-angle-brackets (match-string 0)))))
11695 ((equal complete-file '(4))
11696 ;; Completing read for file names.
11697 (setq file (read-file-name "File: "))
11698 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11699 (pwd1 (file-name-as-directory (abbreviate-file-name
11700 (expand-file-name ".")))))
11701 (cond
11702 ((equal complete-file '(16))
11703 (setq link (org-make-link
11704 "file:"
11705 (abbreviate-file-name (expand-file-name file)))))
11706 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11707 (setq link (org-make-link "file:" (match-string 1 file))))
11708 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11709 (expand-file-name file))
11710 (setq link (org-make-link
11711 "file:" (match-string 1 (expand-file-name file)))))
11712 (t (setq link (org-make-link "file:" file))))))
11714 ;; Read link, with completion for stored links.
11715 (with-output-to-temp-buffer "*Org Links*"
11716 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11717 (when org-stored-links
11718 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11719 (princ (mapconcat
11720 (lambda (x)
11721 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11722 (reverse org-stored-links) "\n"))))
11723 (let ((cw (selected-window)))
11724 (select-window (get-buffer-window "*Org Links*"))
11725 (shrink-window-if-larger-than-buffer)
11726 (setq truncate-lines t)
11727 (select-window cw))
11728 ;; Fake a link history, containing the stored links.
11729 (setq tmphist (append (mapcar 'car org-stored-links)
11730 org-insert-link-history))
11731 (unwind-protect
11732 (setq link (org-completing-read
11733 "Link: "
11734 (append
11735 (mapcar (lambda (x) (list (concat (car x) ":")))
11736 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11737 (mapcar (lambda (x) (list (concat x ":")))
11738 org-link-types))
11739 nil nil nil
11740 'tmphist
11741 (or (car (car org-stored-links)))))
11742 (set-window-configuration wcf)
11743 (kill-buffer "*Org Links*"))
11744 (setq entry (assoc link org-stored-links))
11745 (or entry (push link org-insert-link-history))
11746 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11747 (not org-keep-stored-link-after-insertion))
11748 (setq org-stored-links (delq (assoc link org-stored-links)
11749 org-stored-links)))
11750 (setq desc (or desc (nth 1 entry)))))
11752 (if (string-match org-plain-link-re link)
11753 ;; URL-like link, normalize the use of angular brackets.
11754 (setq link (org-make-link (org-remove-angle-brackets link))))
11756 ;; Check if we are linking to the current file with a search option
11757 ;; If yes, simplify the link by using only the search option.
11758 (when (and buffer-file-name
11759 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11760 (let* ((path (match-string 1 link))
11761 (case-fold-search nil)
11762 (search (match-string 2 link)))
11763 (save-match-data
11764 (if (equal (file-truename buffer-file-name) (file-truename path))
11765 ;; We are linking to this same file, with a search option
11766 (setq link search)))))
11768 ;; Check if we can/should use a relative path. If yes, simplify the link
11769 (when (string-match "\\<file:\\(.*\\)" link)
11770 (let* ((path (match-string 1 link))
11771 (origpath path)
11772 (desc-is-link (equal link desc))
11773 (case-fold-search nil))
11774 (cond
11775 ((eq org-link-file-path-type 'absolute)
11776 (setq path (abbreviate-file-name (expand-file-name path))))
11777 ((eq org-link-file-path-type 'noabbrev)
11778 (setq path (expand-file-name path)))
11779 ((eq org-link-file-path-type 'relative)
11780 (setq path (file-relative-name path)))
11782 (save-match-data
11783 (if (string-match (concat "^" (regexp-quote
11784 (file-name-as-directory
11785 (expand-file-name "."))))
11786 (expand-file-name path))
11787 ;; We are linking a file with relative path name.
11788 (setq path (substring (expand-file-name path)
11789 (match-end 0)))))))
11790 (setq link (concat "file:" path))
11791 (if (equal desc origpath)
11792 (setq desc path))))
11794 (setq desc (read-string "Description: " desc))
11795 (unless (string-match "\\S-" desc) (setq desc nil))
11796 (if remove (apply 'delete-region remove))
11797 (insert (org-make-link-string link desc))))
11799 (defun org-completing-read (&rest args)
11800 (let ((minibuffer-local-completion-map
11801 (copy-keymap minibuffer-local-completion-map)))
11802 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11803 (apply 'completing-read args)))
11805 ;;; Opening/following a link
11806 (defvar org-link-search-failed nil)
11808 (defun org-next-link ()
11809 "Move forward to the next link.
11810 If the link is in hidden text, expose it."
11811 (interactive)
11812 (when (and org-link-search-failed (eq this-command last-command))
11813 (goto-char (point-min))
11814 (message "Link search wrapped back to beginning of buffer"))
11815 (setq org-link-search-failed nil)
11816 (let* ((pos (point))
11817 (ct (org-context))
11818 (a (assoc :link ct)))
11819 (if a (goto-char (nth 2 a)))
11820 (if (re-search-forward org-any-link-re nil t)
11821 (progn
11822 (goto-char (match-beginning 0))
11823 (if (org-invisible-p) (org-show-context)))
11824 (goto-char pos)
11825 (setq org-link-search-failed t)
11826 (error "No further link found"))))
11828 (defun org-previous-link ()
11829 "Move backward to the previous link.
11830 If the link is in hidden text, expose it."
11831 (interactive)
11832 (when (and org-link-search-failed (eq this-command last-command))
11833 (goto-char (point-max))
11834 (message "Link search wrapped back to end of buffer"))
11835 (setq org-link-search-failed nil)
11836 (let* ((pos (point))
11837 (ct (org-context))
11838 (a (assoc :link ct)))
11839 (if a (goto-char (nth 1 a)))
11840 (if (re-search-backward org-any-link-re nil t)
11841 (progn
11842 (goto-char (match-beginning 0))
11843 (if (org-invisible-p) (org-show-context)))
11844 (goto-char pos)
11845 (setq org-link-search-failed t)
11846 (error "No further link found"))))
11848 (defun org-find-file-at-mouse (ev)
11849 "Open file link or URL at mouse."
11850 (interactive "e")
11851 (mouse-set-point ev)
11852 (org-open-at-point 'in-emacs))
11854 (defun org-open-at-mouse (ev)
11855 "Open file link or URL at mouse."
11856 (interactive "e")
11857 (mouse-set-point ev)
11858 (org-open-at-point))
11860 (defvar org-window-config-before-follow-link nil
11861 "The window configuration before following a link.
11862 This is saved in case the need arises to restore it.")
11864 (defvar org-open-link-marker (make-marker)
11865 "Marker pointing to the location where `org-open-at-point; was called.")
11867 ;;;###autoload
11868 (defun org-open-at-point-global ()
11869 "Follow a link like Org-mode does.
11870 This command can be called in any mode to follow a link that has
11871 Org-mode syntax."
11872 (interactive)
11873 (org-run-like-in-org-mode 'org-open-at-point))
11875 (defun org-open-at-point (&optional in-emacs)
11876 "Open link at or after point.
11877 If there is no link at point, this function will search forward up to
11878 the end of the current subtree.
11879 Normally, files will be opened by an appropriate application. If the
11880 optional argument IN-EMACS is non-nil, Emacs will visit the file."
11881 (interactive "P")
11882 (move-marker org-open-link-marker (point))
11883 (setq org-window-config-before-follow-link (current-window-configuration))
11884 (org-remove-occur-highlights nil nil t)
11885 (if (org-at-timestamp-p t)
11886 (org-follow-timestamp-link)
11887 (let (type path link line search (pos (point)))
11888 (catch 'match
11889 (save-excursion
11890 (skip-chars-forward "^]\n\r")
11891 (when (org-in-regexp org-bracket-link-regexp)
11892 (setq link (org-link-unescape (org-match-string-no-properties 1)))
11893 (while (string-match " *\n *" link)
11894 (setq link (replace-match " " t t link)))
11895 (setq link (org-link-expand-abbrev link))
11896 (if (string-match org-link-re-with-space2 link)
11897 (setq type (match-string 1 link) path (match-string 2 link))
11898 (setq type "thisfile" path link))
11899 (throw 'match t)))
11901 (when (get-text-property (point) 'org-linked-text)
11902 (setq type "thisfile"
11903 pos (if (get-text-property (1+ (point)) 'org-linked-text)
11904 (1+ (point)) (point))
11905 path (buffer-substring
11906 (previous-single-property-change pos 'org-linked-text)
11907 (next-single-property-change pos 'org-linked-text)))
11908 (throw 'match t))
11910 (save-excursion
11911 (when (or (org-in-regexp org-angle-link-re)
11912 (org-in-regexp org-plain-link-re))
11913 (setq type (match-string 1) path (match-string 2))
11914 (throw 'match t)))
11915 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
11916 (setq type "tree-match"
11917 path (match-string 1))
11918 (throw 'match t))
11919 (save-excursion
11920 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
11921 (setq type "tags"
11922 path (match-string 1))
11923 (while (string-match ":" path)
11924 (setq path (replace-match "+" t t path)))
11925 (throw 'match t))))
11926 (unless path
11927 (error "No link found"))
11928 ;; Remove any trailing spaces in path
11929 (if (string-match " +\\'" path)
11930 (setq path (replace-match "" t t path)))
11932 (cond
11934 ((assoc type org-link-protocols)
11935 (funcall (nth 1 (assoc type org-link-protocols)) path))
11937 ((equal type "mailto")
11938 (let ((cmd (car org-link-mailto-program))
11939 (args (cdr org-link-mailto-program)) args1
11940 (address path) (subject "") a)
11941 (if (string-match "\\(.*\\)::\\(.*\\)" path)
11942 (setq address (match-string 1 path)
11943 subject (org-link-escape (match-string 2 path))))
11944 (while args
11945 (cond
11946 ((not (stringp (car args))) (push (pop args) args1))
11947 (t (setq a (pop args))
11948 (if (string-match "%a" a)
11949 (setq a (replace-match address t t a)))
11950 (if (string-match "%s" a)
11951 (setq a (replace-match subject t t a)))
11952 (push a args1))))
11953 (apply cmd (nreverse args1))))
11955 ((member type '("http" "https" "ftp" "news"))
11956 (browse-url (concat type ":" (org-link-escape
11957 path org-link-escape-chars-browser))))
11959 ((string= type "tags")
11960 (org-tags-view in-emacs path))
11961 ((string= type "thisfile")
11962 (if in-emacs
11963 (switch-to-buffer-other-window
11964 (org-get-buffer-for-internal-link (current-buffer)))
11965 (org-mark-ring-push))
11966 (let ((cmd `(org-link-search
11967 ,path
11968 ,(cond ((equal in-emacs '(4)) 'occur)
11969 ((equal in-emacs '(16)) 'org-occur)
11970 (t nil))
11971 ,pos)))
11972 (condition-case nil (eval cmd)
11973 (error (progn (widen) (eval cmd))))))
11975 ((string= type "tree-match")
11976 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
11978 ((string= type "file")
11979 (if (string-match "::\\([0-9]+\\)\\'" path)
11980 (setq line (string-to-number (match-string 1 path))
11981 path (substring path 0 (match-beginning 0)))
11982 (if (string-match "::\\(.+\\)\\'" path)
11983 (setq search (match-string 1 path)
11984 path (substring path 0 (match-beginning 0)))))
11985 (org-open-file path in-emacs line search))
11987 ((string= type "news")
11988 (org-follow-gnus-link path))
11990 ((string= type "bbdb")
11991 (org-follow-bbdb-link path))
11993 ((string= type "info")
11994 (org-follow-info-link path))
11996 ((string= type "gnus")
11997 (let (group article)
11998 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
11999 (error "Error in Gnus link"))
12000 (setq group (match-string 1 path)
12001 article (match-string 3 path))
12002 (org-follow-gnus-link group article)))
12004 ((string= type "vm")
12005 (let (folder article)
12006 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12007 (error "Error in VM link"))
12008 (setq folder (match-string 1 path)
12009 article (match-string 3 path))
12010 ;; in-emacs is the prefix arg, will be interpreted as read-only
12011 (org-follow-vm-link folder article in-emacs)))
12013 ((string= type "wl")
12014 (let (folder article)
12015 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12016 (error "Error in Wanderlust link"))
12017 (setq folder (match-string 1 path)
12018 article (match-string 3 path))
12019 (org-follow-wl-link folder article)))
12021 ((string= type "mhe")
12022 (let (folder article)
12023 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12024 (error "Error in MHE link"))
12025 (setq folder (match-string 1 path)
12026 article (match-string 3 path))
12027 (org-follow-mhe-link folder article)))
12029 ((string= type "rmail")
12030 (let (folder article)
12031 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12032 (error "Error in RMAIL link"))
12033 (setq folder (match-string 1 path)
12034 article (match-string 3 path))
12035 (org-follow-rmail-link folder article)))
12037 ((string= type "shell")
12038 (let ((cmd path))
12039 ;; The following is only for backward compatibility
12040 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
12041 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
12042 (if (or (not org-confirm-shell-link-function)
12043 (funcall org-confirm-shell-link-function
12044 (format "Execute \"%s\" in shell? "
12045 (org-add-props cmd nil
12046 'face 'org-warning))))
12047 (progn
12048 (message "Executing %s" cmd)
12049 (shell-command cmd))
12050 (error "Abort"))))
12052 ((string= type "elisp")
12053 (let ((cmd path))
12054 (if (or (not org-confirm-elisp-link-function)
12055 (funcall org-confirm-elisp-link-function
12056 (format "Execute \"%s\" as elisp? "
12057 (org-add-props cmd nil
12058 'face 'org-warning))))
12059 (message "%s => %s" cmd (eval (read cmd)))
12060 (error "Abort"))))
12063 (browse-url-at-point)))))
12064 (move-marker org-open-link-marker nil))
12066 ;;; File search
12068 (defvar org-create-file-search-functions nil
12069 "List of functions to construct the right search string for a file link.
12070 These functions are called in turn with point at the location to
12071 which the link should point.
12073 A function in the hook should first test if it would like to
12074 handle this file type, for example by checking the major-mode or
12075 the file extension. If it decides not to handle this file, it
12076 should just return nil to give other functions a chance. If it
12077 does handle the file, it must return the search string to be used
12078 when following the link. The search string will be part of the
12079 file link, given after a double colon, and `org-open-at-point'
12080 will automatically search for it. If special measures must be
12081 taken to make the search successful, another function should be
12082 added to the companion hook `org-execute-file-search-functions',
12083 which see.
12085 A function in this hook may also use `setq' to set the variable
12086 `description' to provide a suggestion for the descriptive text to
12087 be used for this link when it gets inserted into an Org-mode
12088 buffer with \\[org-insert-link].")
12090 (defvar org-execute-file-search-functions nil
12091 "List of functions to execute a file search triggered by a link.
12093 Functions added to this hook must accept a single argument, the
12094 search string that was part of the file link, the part after the
12095 double colon. The function must first check if it would like to
12096 handle this search, for example by checking the major-mode or the
12097 file extension. If it decides not to handle this search, it
12098 should just return nil to give other functions a chance. If it
12099 does handle the search, it must return a non-nil value to keep
12100 other functions from trying.
12102 Each function can access the current prefix argument through the
12103 variable `current-prefix-argument'. Note that a single prefix is
12104 used to force opening a link in Emacs, so it may be good to only
12105 use a numeric or double prefix to guide the search function.
12107 In case this is needed, a function in this hook can also restore
12108 the window configuration before `org-open-at-point' was called using:
12110 (set-window-configuration org-window-config-before-follow-link)")
12112 (defun org-link-search (s &optional type avoid-pos)
12113 "Search for a link search option.
12114 If S is surrounded by forward slashes, it is interpreted as a
12115 regular expression. In org-mode files, this will create an `org-occur'
12116 sparse tree. In ordinary files, `occur' will be used to list matches.
12117 If the current buffer is in `dired-mode', grep will be used to search
12118 in all files. If AVOID-POS is given, ignore matches near that position."
12119 (let ((case-fold-search t)
12120 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12121 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12122 (append '(("") (" ") ("\t") ("\n"))
12123 org-emphasis-alist)
12124 "\\|") "\\)"))
12125 (pos (point))
12126 (pre "") (post "")
12127 words re0 re1 re2 re3 re4 re5 re2a reall)
12128 (cond
12129 ;; First check if there are any special
12130 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12131 ;; Now try the builtin stuff
12132 ((save-excursion
12133 (goto-char (point-min))
12134 (and
12135 (re-search-forward
12136 (concat "<<" (regexp-quote s0) ">>") nil t)
12137 (setq pos (match-beginning 0))))
12138 ;; There is an exact target for this
12139 (goto-char pos))
12140 ((string-match "^/\\(.*\\)/$" s)
12141 ;; A regular expression
12142 (cond
12143 ((org-mode-p)
12144 (org-occur (match-string 1 s)))
12145 ;;((eq major-mode 'dired-mode)
12146 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12147 (t (org-do-occur (match-string 1 s)))))
12149 ;; A normal search strings
12150 (when (equal (string-to-char s) ?*)
12151 ;; Anchor on headlines, post may include tags.
12152 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12153 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12154 s (substring s 1)))
12155 (remove-text-properties
12156 0 (length s)
12157 '(face nil mouse-face nil keymap nil fontified nil) s)
12158 ;; Make a series of regular expressions to find a match
12159 (setq words (org-split-string s "[ \n\r\t]+")
12160 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12161 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12162 "\\)" markers)
12163 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12164 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12165 re1 (concat pre re2 post)
12166 re3 (concat pre re4 post)
12167 re5 (concat pre ".*" re4)
12168 re2 (concat pre re2)
12169 re2a (concat pre re2a)
12170 re4 (concat pre re4)
12171 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12172 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12173 re5 "\\)"
12175 (cond
12176 ((eq type 'org-occur) (org-occur reall))
12177 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12178 (t (goto-char (point-min))
12179 (if (or (org-search-not-self 1 re0 nil t)
12180 (org-search-not-self 1 re1 nil t)
12181 (org-search-not-self 1 re2 nil t)
12182 (org-search-not-self 1 re2a nil t)
12183 (org-search-not-self 1 re3 nil t)
12184 (org-search-not-self 1 re4 nil t)
12185 (org-search-not-self 1 re5 nil t)
12187 (goto-char (match-beginning 1))
12188 (goto-char pos)
12189 (error "No match")))))
12191 ;; Normal string-search
12192 (goto-char (point-min))
12193 (if (search-forward s nil t)
12194 (goto-char (match-beginning 0))
12195 (error "No match"))))
12196 (and (org-mode-p) (org-show-context 'link-search))))
12198 (defun org-search-not-self (group &rest args)
12199 "Execute `re-search-forward', but only accept matches that do not
12200 enclose the position of `org-open-link-marker'."
12201 (let ((m org-open-link-marker))
12202 (catch 'exit
12203 (while (apply 're-search-forward args)
12204 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12205 (goto-char (match-end group))
12206 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12207 (> (match-beginning 0) (marker-position m))
12208 (< (match-end 0) (marker-position m)))
12209 (save-match-data
12210 (or (not (org-in-regexp
12211 org-bracket-link-analytic-regexp 1))
12212 (not (match-end 4)) ; no description
12213 (and (<= (match-beginning 4) (point))
12214 (>= (match-end 4) (point))))))
12215 (throw 'exit (point))))))))
12217 (defun org-get-buffer-for-internal-link (buffer)
12218 "Return a buffer to be used for displaying the link target of internal links."
12219 (cond
12220 ((not org-display-internal-link-with-indirect-buffer)
12221 buffer)
12222 ((string-match "(Clone)$" (buffer-name buffer))
12223 (message "Buffer is already a clone, not making another one")
12224 ;; we also do not modify visibility in this case
12225 buffer)
12226 (t ; make a new indirect buffer for displaying the link
12227 (let* ((bn (buffer-name buffer))
12228 (ibn (concat bn "(Clone)"))
12229 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12230 (with-current-buffer ib (org-overview))
12231 ib))))
12233 (defun org-do-occur (regexp &optional cleanup)
12234 "Call the Emacs command `occur'.
12235 If CLEANUP is non-nil, remove the printout of the regular expression
12236 in the *Occur* buffer. This is useful if the regex is long and not useful
12237 to read."
12238 (occur regexp)
12239 (when cleanup
12240 (let ((cwin (selected-window)) win beg end)
12241 (when (setq win (get-buffer-window "*Occur*"))
12242 (select-window win))
12243 (goto-char (point-min))
12244 (when (re-search-forward "match[a-z]+" nil t)
12245 (setq beg (match-end 0))
12246 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12247 (setq end (1- (match-beginning 0)))))
12248 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12249 (goto-char (point-min))
12250 (select-window cwin))))
12252 ;;; The mark ring for links jumps
12254 (defvar org-mark-ring nil
12255 "Mark ring for positions before jumps in Org-mode.")
12256 (defvar org-mark-ring-last-goto nil
12257 "Last position in the mark ring used to go back.")
12258 ;; Fill and close the ring
12259 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12260 (loop for i from 1 to org-mark-ring-length do
12261 (push (make-marker) org-mark-ring))
12262 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12263 org-mark-ring)
12265 (defun org-mark-ring-push (&optional pos buffer)
12266 "Put the current position or POS into the mark ring and rotate it."
12267 (interactive)
12268 (setq pos (or pos (point)))
12269 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12270 (move-marker (car org-mark-ring)
12271 (or pos (point))
12272 (or buffer (current-buffer)))
12273 (message
12274 (substitute-command-keys
12275 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12277 (defun org-mark-ring-goto (&optional n)
12278 "Jump to the previous position in the mark ring.
12279 With prefix arg N, jump back that many stored positions. When
12280 called several times in succession, walk through the entire ring.
12281 Org-mode commands jumping to a different position in the current file,
12282 or to another Org-mode file, automatically push the old position
12283 onto the ring."
12284 (interactive "p")
12285 (let (p m)
12286 (if (eq last-command this-command)
12287 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12288 (setq p org-mark-ring))
12289 (setq org-mark-ring-last-goto p)
12290 (setq m (car p))
12291 (switch-to-buffer (marker-buffer m))
12292 (goto-char m)
12293 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12295 (defun org-remove-angle-brackets (s)
12296 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12297 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12299 (defun org-add-angle-brackets (s)
12300 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12301 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12304 ;;; Following specific links
12306 (defun org-follow-timestamp-link ()
12307 (cond
12308 ((org-at-date-range-p t)
12309 (let ((org-agenda-start-on-weekday)
12310 (t1 (match-string 1))
12311 (t2 (match-string 2)))
12312 (setq t1 (time-to-days (org-time-string-to-time t1))
12313 t2 (time-to-days (org-time-string-to-time t2)))
12314 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12315 ((org-at-timestamp-p t)
12316 (org-agenda-list nil (time-to-days (org-time-string-to-time
12317 (substring (match-string 1) 0 10)))
12319 (t (error "This should not happen"))))
12322 (defun org-follow-bbdb-link (name)
12323 "Follow a BBDB link to NAME."
12324 (require 'bbdb)
12325 (let ((inhibit-redisplay (not debug-on-error))
12326 (bbdb-electric-p nil))
12327 (catch 'exit
12328 ;; Exact match on name
12329 (bbdb-name (concat "\\`" name "\\'") nil)
12330 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12331 ;; Exact match on name
12332 (bbdb-company (concat "\\`" name "\\'") nil)
12333 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12334 ;; Partial match on name
12335 (bbdb-name name nil)
12336 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12337 ;; Partial match on company
12338 (bbdb-company name nil)
12339 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12340 ;; General match including network address and notes
12341 (bbdb name nil)
12342 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12343 (delete-window (get-buffer-window "*BBDB*"))
12344 (error "No matching BBDB record")))))
12346 (defun org-follow-info-link (name)
12347 "Follow an info file & node link to NAME."
12348 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12349 (string-match "\\(.*\\)" name))
12350 (progn
12351 (require 'info)
12352 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12353 (Info-find-node (match-string 1 name) (match-string 2 name))
12354 (Info-find-node (match-string 1 name) "Top")))
12355 (message (concat "Could not open: " name))))
12357 (defun org-follow-gnus-link (&optional group article)
12358 "Follow a Gnus link to GROUP and ARTICLE."
12359 (require 'gnus)
12360 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12361 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12362 (cond ((and group article)
12363 (gnus-group-read-group 1 nil group)
12364 (gnus-summary-goto-article (string-to-number article) nil t))
12365 (group (gnus-group-jump-to-group group))))
12367 (defun org-follow-vm-link (&optional folder article readonly)
12368 "Follow a VM link to FOLDER and ARTICLE."
12369 (require 'vm)
12370 (setq article (org-add-angle-brackets article))
12371 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12372 ;; ange-ftp or efs or tramp access
12373 (let ((user (or (match-string 1 folder) (user-login-name)))
12374 (host (match-string 2 folder))
12375 (file (match-string 3 folder)))
12376 (cond
12377 ((featurep 'tramp)
12378 ;; use tramp to access the file
12379 (if (featurep 'xemacs)
12380 (setq folder (format "[%s@%s]%s" user host file))
12381 (setq folder (format "/%s@%s:%s" user host file))))
12383 ;; use ange-ftp or efs
12384 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12385 (setq folder (format "/%s@%s:%s" user host file))))))
12386 (when folder
12387 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12388 (sit-for 0.1)
12389 (when article
12390 (vm-select-folder-buffer)
12391 (widen)
12392 (let ((case-fold-search t))
12393 (goto-char (point-min))
12394 (if (not (re-search-forward
12395 (concat "^" "message-id: *" (regexp-quote article))))
12396 (error "Could not find the specified message in this folder"))
12397 (vm-isearch-update)
12398 (vm-isearch-narrow)
12399 (vm-beginning-of-message)
12400 (vm-summarize)))))
12402 (defun org-follow-wl-link (folder article)
12403 "Follow a Wanderlust link to FOLDER and ARTICLE."
12404 (if (and (string= folder "%")
12405 article
12406 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12407 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12408 ;; Thus, we recompose folder and article ids.
12409 (setq folder (format "%s#%s" folder (match-string 1 article))
12410 article (match-string 3 article)))
12411 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12412 (error "No such folder: %s" folder))
12413 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12414 (and article
12415 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12416 (wl-summary-redisplay)))
12418 (defun org-follow-rmail-link (folder article)
12419 "Follow an RMAIL link to FOLDER and ARTICLE."
12420 (setq article (org-add-angle-brackets article))
12421 (let (message-number)
12422 (save-excursion
12423 (save-window-excursion
12424 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12425 (setq message-number
12426 (save-restriction
12427 (widen)
12428 (goto-char (point-max))
12429 (if (re-search-backward
12430 (concat "^Message-ID:\\s-+" (regexp-quote
12431 (or article "")))
12432 nil t)
12433 (rmail-what-message))))))
12434 (if message-number
12435 (progn
12436 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12437 (rmail-show-message message-number)
12438 message-number)
12439 (error "Message not found"))))
12441 ;;; mh-e integration based on planner-mode
12442 (defun org-mhe-get-message-real-folder ()
12443 "Return the name of the current message real folder, so if you use
12444 sequences, it will now work."
12445 (save-excursion
12446 (let* ((folder
12447 (if (equal major-mode 'mh-folder-mode)
12448 mh-current-folder
12449 ;; Refer to the show buffer
12450 mh-show-folder-buffer))
12451 (end-index
12452 (if (boundp 'mh-index-folder)
12453 (min (length mh-index-folder) (length folder))))
12455 ;; a simple test on mh-index-data does not work, because
12456 ;; mh-index-data is always nil in a show buffer.
12457 (if (and (boundp 'mh-index-folder)
12458 (string= mh-index-folder (substring folder 0 end-index)))
12459 (if (equal major-mode 'mh-show-mode)
12460 (save-window-excursion
12461 (let (pop-up-frames)
12462 (when (buffer-live-p (get-buffer folder))
12463 (progn
12464 (pop-to-buffer folder)
12465 (org-mhe-get-message-folder-from-index)
12468 (org-mhe-get-message-folder-from-index)
12470 folder
12474 (defun org-mhe-get-message-folder-from-index ()
12475 "Returns the name of the message folder in a index folder buffer."
12476 (save-excursion
12477 (mh-index-previous-folder)
12478 (re-search-forward "^\\(+.*\\)$" nil t)
12479 (message (match-string 1))))
12481 (defun org-mhe-get-message-folder ()
12482 "Return the name of the current message folder. Be careful if you
12483 use sequences."
12484 (save-excursion
12485 (if (equal major-mode 'mh-folder-mode)
12486 mh-current-folder
12487 ;; Refer to the show buffer
12488 mh-show-folder-buffer)))
12490 (defun org-mhe-get-message-num ()
12491 "Return the number of the current message. Be careful if you
12492 use sequences."
12493 (save-excursion
12494 (if (equal major-mode 'mh-folder-mode)
12495 (mh-get-msg-num nil)
12496 ;; Refer to the show buffer
12497 (mh-show-buffer-message-number))))
12499 (defun org-mhe-get-header (header)
12500 "Return a header of the message in folder mode. This will create a
12501 show buffer for the corresponding message. If you have a more clever
12502 idea..."
12503 (let* ((folder (org-mhe-get-message-folder))
12504 (num (org-mhe-get-message-num))
12505 (buffer (get-buffer-create (concat "show-" folder)))
12506 (header-field))
12507 (with-current-buffer buffer
12508 (mh-display-msg num folder)
12509 (if (equal major-mode 'mh-folder-mode)
12510 (mh-header-display)
12511 (mh-show-header-display))
12512 (set-buffer buffer)
12513 (setq header-field (mh-get-header-field header))
12514 (if (equal major-mode 'mh-folder-mode)
12515 (mh-show)
12516 (mh-show-show))
12517 header-field)))
12519 (defun org-follow-mhe-link (folder article)
12520 "Follow an MHE link to FOLDER and ARTICLE.
12521 If ARTICLE is nil FOLDER is shown. If the configuration variable
12522 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12523 ARTICLE is searched in all folders. Indexed searches (swish++,
12524 namazu, and others supported by MH-E) will always search in all
12525 folders."
12526 (require 'mh-e)
12527 (require 'mh-search)
12528 (require 'mh-utils)
12529 (mh-find-path)
12530 (if (not article)
12531 (mh-visit-folder (mh-normalize-folder-name folder))
12532 (setq article (org-add-angle-brackets article))
12533 (mh-search-choose)
12534 (if (equal mh-searcher 'pick)
12535 (progn
12536 (mh-search folder (list "--message-id" article))
12537 (when (and org-mhe-search-all-folders
12538 (not (org-mhe-get-message-real-folder)))
12539 (kill-this-buffer)
12540 (mh-search "+" (list "--message-id" article))))
12541 (mh-search "+" article))
12542 (if (org-mhe-get-message-real-folder)
12543 (mh-show-msg 1)
12544 (kill-this-buffer)
12545 (error "Message not found"))))
12547 ;;; BibTeX links
12549 ;; Use the custom search meachnism to construct and use search strings for
12550 ;; file links to BibTeX database entries.
12552 (defun org-create-file-search-in-bibtex ()
12553 "Create the search string and description for a BibTeX database entry."
12554 (when (eq major-mode 'bibtex-mode)
12555 ;; yes, we want to construct this search string.
12556 ;; Make a good description for this entry, using names, year and the title
12557 ;; Put it into the `description' variable which is dynamically scoped.
12558 (let ((bibtex-autokey-names 1)
12559 (bibtex-autokey-names-stretch 1)
12560 (bibtex-autokey-name-case-convert-function 'identity)
12561 (bibtex-autokey-name-separator " & ")
12562 (bibtex-autokey-additional-names " et al.")
12563 (bibtex-autokey-year-length 4)
12564 (bibtex-autokey-name-year-separator " ")
12565 (bibtex-autokey-titlewords 3)
12566 (bibtex-autokey-titleword-separator " ")
12567 (bibtex-autokey-titleword-case-convert-function 'identity)
12568 (bibtex-autokey-titleword-length 'infty)
12569 (bibtex-autokey-year-title-separator ": "))
12570 (setq description (bibtex-generate-autokey)))
12571 ;; Now parse the entry, get the key and return it.
12572 (save-excursion
12573 (bibtex-beginning-of-entry)
12574 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12576 (defun org-execute-file-search-in-bibtex (s)
12577 "Find the link search string S as a key for a database entry."
12578 (when (eq major-mode 'bibtex-mode)
12579 ;; Yes, we want to do the search in this file.
12580 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12581 (goto-char (point-min))
12582 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12583 (regexp-quote s) "[ \t\n]*,") nil t)
12584 (goto-char (match-beginning 0)))
12585 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12586 ;; Use double prefix to indicate that any web link should be browsed
12587 (let ((b (current-buffer)) (p (point)))
12588 ;; Restore the window configuration because we just use the web link
12589 (set-window-configuration org-window-config-before-follow-link)
12590 (save-excursion (set-buffer b) (goto-char p)
12591 (bibtex-url)))
12592 (recenter 0)) ; Move entry start to beginning of window
12593 ;; return t to indicate that the search is done.
12596 ;; Finally add the functions to the right hooks.
12597 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12598 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12600 ;; end of Bibtex link setup
12602 ;;; Following file links
12604 (defun org-open-file (path &optional in-emacs line search)
12605 "Open the file at PATH.
12606 First, this expands any special file name abbreviations. Then the
12607 configuration variable `org-file-apps' is checked if it contains an
12608 entry for this file type, and if yes, the corresponding command is launched.
12609 If no application is found, Emacs simply visits the file.
12610 With optional argument IN-EMACS, Emacs will visit the file.
12611 Optional LINE specifies a line to go to, optional SEARCH a string to
12612 search for. If LINE or SEARCH is given, the file will always be
12613 opened in Emacs.
12614 If the file does not exist, an error is thrown."
12615 (setq in-emacs (or in-emacs line search))
12616 (let* ((file (if (equal path "")
12617 buffer-file-name
12618 (substitute-in-file-name (expand-file-name path))))
12619 (apps (append org-file-apps (org-default-apps)))
12620 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12621 (dirp (if remp nil (file-directory-p file)))
12622 (dfile (downcase file))
12623 (old-buffer (current-buffer))
12624 (old-pos (point))
12625 (old-mode major-mode)
12626 ext cmd)
12627 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12628 (setq ext (match-string 1 dfile))
12629 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12630 (setq ext (match-string 1 dfile))))
12631 (if in-emacs
12632 (setq cmd 'emacs)
12633 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12634 (and dirp (cdr (assoc 'directory apps)))
12635 (cdr (assoc ext apps))
12636 (cdr (assoc t apps)))))
12637 (when (eq cmd 'mailcap)
12638 (require 'mailcap)
12639 (mailcap-parse-mailcaps)
12640 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12641 (command (mailcap-mime-info mime-type)))
12642 (if (stringp command)
12643 (setq cmd command)
12644 (setq cmd 'emacs))))
12645 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12646 (not (file-exists-p file))
12647 (not org-open-non-existing-files))
12648 (error "No such file: %s" file))
12649 (cond
12650 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12651 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12652 (if (string-match "['\"]%s['\"]" cmd)
12653 (setq cmd (replace-match "%s" t t cmd)))
12654 (setq cmd (format cmd (shell-quote-argument file)))
12655 (save-window-excursion
12656 (start-process-shell-command cmd nil cmd)))
12657 ((or (stringp cmd)
12658 (eq cmd 'emacs))
12659 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12660 (widen)
12661 (if line (goto-line line)
12662 (if search (org-link-search search))))
12663 ((consp cmd)
12664 (eval cmd))
12665 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12666 (and (org-mode-p) (eq old-mode 'org-mode)
12667 (or (not (equal old-buffer (current-buffer)))
12668 (not (equal old-pos (point))))
12669 (org-mark-ring-push old-pos old-buffer))))
12671 (defun org-default-apps ()
12672 "Return the default applications for this operating system."
12673 (cond
12674 ((eq system-type 'darwin)
12675 org-file-apps-defaults-macosx)
12676 ((eq system-type 'windows-nt)
12677 org-file-apps-defaults-windowsnt)
12678 (t org-file-apps-defaults-gnu)))
12680 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12681 (defun org-file-remote-p (file)
12682 "Test whether FILE specifies a location on a remote system.
12683 Return non-nil if the location is indeed remote.
12685 For example, the filename \"/user@host:/foo\" specifies a location
12686 on the system \"/user@host:\"."
12687 (cond ((fboundp 'file-remote-p)
12688 (file-remote-p file))
12689 ((fboundp 'tramp-handle-file-remote-p)
12690 (tramp-handle-file-remote-p file))
12691 ((and (boundp 'ange-ftp-name-format)
12692 (string-match (car ange-ftp-name-format) file))
12694 (t nil)))
12697 ;;;; Hooks for remember.el
12699 ;;;###autoload
12700 (defun org-remember-annotation ()
12701 "Return a link to the current location as an annotation for remember.el.
12702 If you are using Org-mode files as target for data storage with
12703 remember.el, then the annotations should include a link compatible with the
12704 conventions in Org-mode. This function returns such a link."
12705 (org-store-link nil))
12707 (defconst org-remember-help
12708 "Select a destination location for the note.
12709 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12710 RET on headline -> Store as sublevel entry to current headline
12711 RET at beg-of-buf -> Append to file as level 2 headline
12712 <left>/<right> -> before/after current headline, same headings level")
12714 (defvar org-remember-previous-location nil)
12715 (defvar org-force-remember-template-char) ;; dynamically scoped
12717 ;;;###autoload
12718 (defun org-remember-apply-template (&optional use-char skip-interactive)
12719 "Initialize *remember* buffer with template, invoke `org-mode'.
12720 This function should be placed into `remember-mode-hook' and in fact requires
12721 to be run from that hook to fucntion properly."
12722 (if org-remember-templates
12723 (let* ((templates (mapcar (lambda (x)
12724 (if (stringp (car x))
12725 (append (list (nth 1 x) (car x)) (cddr x))
12726 (append (list (car x) "") (cdr x))))
12727 org-remember-templates))
12728 (char (or use-char
12729 (cond
12730 ((= (length templates) 1)
12731 (caar templates))
12732 ((and (boundp 'org-force-remember-template-char)
12733 org-force-remember-template-char)
12734 (if (stringp org-force-remember-template-char)
12735 (string-to-char org-force-remember-template-char)
12736 org-force-remember-template-char))
12738 (message "Select template: %s"
12739 (mapconcat
12740 (lambda (x)
12741 (cond
12742 ((not (string-match "\\S-" (nth 1 x)))
12743 (format "[%c]" (car x)))
12744 ((equal (downcase (car x))
12745 (downcase (aref (nth 1 x) 0)))
12746 (format "[%c]%s" (car x) (substring (nth 1 x) 1)))
12747 (t (format "[%c]%s" (car x) (nth 1 x)))))
12748 templates " "))
12749 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
12750 (when (equal char0 ?\C-g)
12751 (jump-to-register remember-register)
12752 (kill-buffer remember-buffer))
12753 char0)))))
12754 (entry (cddr (assoc char templates)))
12755 (tpl (car entry))
12756 (plist-p (if org-store-link-plist t nil))
12757 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12758 (string-match "\\S-" (nth 1 entry)))
12759 (nth 1 entry)
12760 org-default-notes-file))
12761 (headline (nth 2 entry))
12762 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12763 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12764 (v-u (concat "[" (substring v-t 1 -1) "]"))
12765 (v-U (concat "[" (substring v-T 1 -1) "]"))
12766 ;; `initial' and `annotation' are bound in `remember'
12767 (v-i (if (boundp 'initial) initial))
12768 (v-a (if (and (boundp 'annotation) annotation)
12769 (if (equal annotation "[[]]") "" annotation)
12770 ""))
12771 (v-A (if (and v-a
12772 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12773 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12774 v-a))
12775 (v-n user-full-name)
12776 (org-startup-folded nil)
12777 org-time-was-given org-end-time-was-given x prompt char time)
12778 (setq org-store-link-plist
12779 (append (list :annotation v-a :initial v-i)
12780 org-store-link-plist))
12781 (unless tpl (setq tpl "") (message "No template") (ding))
12782 (erase-buffer)
12783 (insert (substitute-command-keys
12784 (format
12785 "## Filing location: Select interactively, default, or last used:
12786 ## %s to select file and header location interactively.
12787 ## %s \"%s\" -> \"* %s\"
12788 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12789 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12790 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12791 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12792 (abbreviate-file-name (or file org-default-notes-file))
12793 (or headline "")
12794 (or (car org-remember-previous-location) "???")
12795 (or (cdr org-remember-previous-location) "???"))))
12796 (insert tpl) (goto-char (point-min))
12797 ;; Simple %-escapes
12798 (while (re-search-forward "%\\([tTuUaiA]\\)" nil t)
12799 (when (and initial (equal (match-string 0) "%i"))
12800 (save-match-data
12801 (let* ((lead (buffer-substring
12802 (point-at-bol) (match-beginning 0))))
12803 (setq v-i (mapconcat 'identity
12804 (org-split-string initial "\n")
12805 (concat "\n" lead))))))
12806 (replace-match
12807 (or (eval (intern (concat "v-" (match-string 1)))) "")
12808 t t))
12809 ;; From the property list
12810 (when plist-p
12811 (goto-char (point-min))
12812 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
12813 (and (setq x (plist-get org-store-link-plist
12814 (intern (match-string 1))))
12815 (replace-match x t t))))
12816 ;; Turn on org-mode in the remember buffer, set local variables
12817 (org-mode)
12818 (org-set-local 'org-finish-function 'remember-buffer)
12819 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
12820 (org-set-local 'org-default-notes-file file))
12821 (if (and headline (stringp headline) (string-match "\\S-" headline))
12822 (org-set-local 'org-remember-default-headline headline))
12823 ;; Interactive template entries
12824 (goto-char (point-min))
12825 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
12826 (setq char (if (match-end 3) (match-string 3))
12827 prompt (if (match-end 2) (match-string 2)))
12828 (goto-char (match-beginning 0))
12829 (replace-match "")
12830 (cond
12831 ((member char '("G" "g"))
12832 (let* ((org-last-tags-completion-table
12833 (org-global-tags-completion-table
12834 (if (equal char "G") (org-agenda-files) (and file (list file)))))
12835 (org-add-colon-after-tag-completion t)
12836 (ins (completing-read
12837 (if prompt (concat prompt ": ") "Tags: ")
12838 'org-tags-completion-function nil nil nil
12839 'org-tags-history)))
12840 (setq ins (mapconcat 'identity
12841 (org-split-string ins (org-re "[^[:alnum:]]+"))
12842 ":"))
12843 (when (string-match "\\S-" ins)
12844 (or (equal (char-before) ?:) (insert ":"))
12845 (insert ins)
12846 (or (equal (char-after) ?:) (insert ":")))))
12847 (char
12848 (setq org-time-was-given (equal (upcase char) char))
12849 (setq time (org-read-date (equal (upcase char) "U") t nil
12850 prompt))
12851 (org-insert-time-stamp time org-time-was-given
12852 (member char '("u" "U"))
12853 nil nil (list org-end-time-was-given)))
12855 (insert (read-string
12856 (if prompt (concat prompt ": ") "Enter string"))))))
12857 (goto-char (point-min))
12858 (if (re-search-forward "%\\?" nil t)
12859 (replace-match "")
12860 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
12861 (org-mode)
12862 (org-set-local 'org-finish-function 'remember-buffer)))
12864 ;;;###autoload
12865 (defun org-remember (&optional org-force-remember-template-char)
12866 "Call `remember'. If this is already a remember buffer, re-apply template.
12867 If there is an active region, make sure remember uses it as initial content
12868 of the remember buffer."
12869 (interactive)
12870 (if (eq org-finish-function 'remember-buffer)
12871 (progn
12872 (when (< (length org-remember-templates) 2)
12873 (error "No other template available"))
12874 (erase-buffer)
12875 (let ((annotation (plist-get org-store-link-plist :annotation))
12876 (initial (plist-get org-store-link-plist :initial)))
12877 (org-remember-apply-template))
12878 (message "Press C-c C-c to remember data"))
12879 (if (org-region-active-p)
12880 (remember (buffer-substring (point) (mark)))
12881 (call-interactively 'remember))))
12883 (defvar org-note-abort nil) ; dynamically scoped
12885 ;;;###autoload
12886 (defun org-remember-handler ()
12887 "Store stuff from remember.el into an org file.
12888 First prompts for an org file. If the user just presses return, the value
12889 of `org-default-notes-file' is used.
12890 Then the command offers the headings tree of the selected file in order to
12891 file the text at a specific location.
12892 You can either immediately press RET to get the note appended to the
12893 file, or you can use vertical cursor motion and visibility cycling (TAB) to
12894 find a better place. Then press RET or <left> or <right> in insert the note.
12896 Key Cursor position Note gets inserted
12897 -----------------------------------------------------------------------------
12898 RET buffer-start as level 1 heading at end of file
12899 RET on headline as sublevel of the heading at cursor
12900 RET no heading at cursor position, level taken from context.
12901 Or use prefix arg to specify level manually.
12902 <left> on headline as same level, before current heading
12903 <right> on headline as same level, after current heading
12905 So the fastest way to store the note is to press RET RET to append it to
12906 the default file. This way your current train of thought is not
12907 interrupted, in accordance with the principles of remember.el.
12908 You can also get the fast execution without prompting by using
12909 C-u C-c C-c to exit the remember buffer. See also the variable
12910 `org-remember-store-without-prompt'.
12912 Before being stored away, the function ensures that the text has a
12913 headline, i.e. a first line that starts with a \"*\". If not, a headline
12914 is constructed from the current date and some additional data.
12916 If the variable `org-adapt-indentation' is non-nil, the entire text is
12917 also indented so that it starts in the same column as the headline
12918 \(i.e. after the stars).
12920 See also the variable `org-reverse-note-order'."
12921 (goto-char (point-min))
12922 (while (looking-at "^[ \t]*\n\\|^##.*\n")
12923 (replace-match ""))
12924 (goto-char (point-max))
12925 (unless (equal (char-before) ?\n) (insert "\n"))
12926 (catch 'quit
12927 (if org-note-abort (throw 'quit nil))
12928 (let* ((txt (buffer-substring (point-min) (point-max)))
12929 (fastp (org-xor (equal current-prefix-arg '(4))
12930 org-remember-store-without-prompt))
12931 (file (if fastp org-default-notes-file (org-get-org-file)))
12932 (heading org-remember-default-headline)
12933 (visiting (org-find-base-buffer-visiting file))
12934 (org-startup-folded nil)
12935 (org-startup-align-all-tables nil)
12936 (org-goto-start-pos 1)
12937 spos exitcmd level indent reversed)
12938 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
12939 (setq file (car org-remember-previous-location)
12940 heading (cdr org-remember-previous-location)))
12941 (setq current-prefix-arg nil)
12942 ;; Modify text so that it becomes a nice subtree which can be inserted
12943 ;; into an org tree.
12944 (let* ((lines (split-string txt "\n"))
12945 first)
12946 (setq first (car lines) lines (cdr lines))
12947 (if (string-match "^\\*+ " first)
12948 ;; Is already a headline
12949 (setq indent nil)
12950 ;; We need to add a headline: Use time and first buffer line
12951 (setq lines (cons first lines)
12952 first (concat "* " (current-time-string)
12953 " (" (remember-buffer-desc) ")")
12954 indent " "))
12955 (if (and org-adapt-indentation indent)
12956 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
12957 (setq txt (concat first "\n"
12958 (mapconcat 'identity lines "\n"))))
12959 ;; Find the file
12960 (if (not visiting) (find-file-noselect file))
12961 (with-current-buffer (or visiting (get-file-buffer file))
12962 (unless (org-mode-p)
12963 (error "Target files for remember notes must be in Org-mode"))
12964 (save-excursion
12965 (save-restriction
12966 (widen)
12967 (and (goto-char (point-min))
12968 (not (re-search-forward "^\\* " nil t))
12969 (insert "\n* " (or heading "Notes") "\n"))
12970 (setq reversed (org-notes-order-reversed-p))
12972 ;; Find the default location
12973 (when (and heading (stringp heading) (string-match "\\S-" heading))
12974 (goto-char (point-min))
12975 (if (re-search-forward
12976 (concat "^\\*+[ \t]+" (regexp-quote heading)
12977 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
12978 nil t)
12979 (setq org-goto-start-pos (match-beginning 0))
12980 (when fastp
12981 (goto-char (point-max))
12982 (unless (bolp) (newline))
12983 (insert "* " heading "\n")
12984 (setq org-goto-start-pos (point-at-bol 0)))))
12986 ;; Ask the User for a location
12987 (if fastp
12988 (setq spos org-goto-start-pos
12989 exitcmd 'return)
12990 (setq spos (org-get-location (current-buffer) org-remember-help)
12991 exitcmd (cdr spos)
12992 spos (car spos)))
12993 (if (not spos) (throw 'quit nil)) ; return nil to show we did
12994 ; not handle this note
12995 (goto-char spos)
12996 (cond ((org-on-heading-p t)
12997 (org-back-to-heading t)
12998 (setq level (funcall outline-level))
12999 (cond
13000 ((eq exitcmd 'return)
13001 ;; sublevel of current
13002 (setq org-remember-previous-location
13003 (cons (abbreviate-file-name file)
13004 (org-get-heading 'notags)))
13005 (if reversed
13006 (outline-next-heading)
13007 (org-end-of-subtree)
13008 (if (not (bolp))
13009 (if (looking-at "[ \t]*\n")
13010 (beginning-of-line 2)
13011 (end-of-line 1)
13012 (insert "\n"))))
13013 (org-paste-subtree (org-get-legal-level level 1) txt))
13014 ((eq exitcmd 'left)
13015 ;; before current
13016 (org-paste-subtree level txt))
13017 ((eq exitcmd 'right)
13018 ;; after current
13019 (org-end-of-subtree t)
13020 (org-paste-subtree level txt))
13021 (t (error "This should not happen"))))
13023 ((and (bobp) (not reversed))
13024 ;; Put it at the end, one level below level 1
13025 (save-restriction
13026 (widen)
13027 (goto-char (point-max))
13028 (if (not (bolp)) (newline))
13029 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13031 ((and (bobp) reversed)
13032 ;; Put it at the start, as level 1
13033 (save-restriction
13034 (widen)
13035 (goto-char (point-min))
13036 (re-search-forward "^\\*+ " nil t)
13037 (beginning-of-line 1)
13038 (org-paste-subtree 1 txt)))
13040 ;; Put it right there, with automatic level determined by
13041 ;; org-paste-subtree or from prefix arg
13042 (org-paste-subtree
13043 (if (numberp current-prefix-arg) current-prefix-arg)
13044 txt)))
13045 (when remember-save-after-remembering
13046 (save-buffer)
13047 (if (not visiting) (kill-buffer (current-buffer)))))))))
13048 t) ;; return t to indicate that we took care of this note.
13050 (defun org-get-org-file ()
13051 "Read a filename, with default directory `org-directory'."
13052 (let ((default (or org-default-notes-file remember-data-file)))
13053 (read-file-name (format "File name [%s]: " default)
13054 (file-name-as-directory org-directory)
13055 default)))
13057 (defun org-notes-order-reversed-p ()
13058 "Check if the current file should receive notes in reversed order."
13059 (cond
13060 ((not org-reverse-note-order) nil)
13061 ((eq t org-reverse-note-order) t)
13062 ((not (listp org-reverse-note-order)) nil)
13063 (t (catch 'exit
13064 (let ((all org-reverse-note-order)
13065 entry)
13066 (while (setq entry (pop all))
13067 (if (string-match (car entry) buffer-file-name)
13068 (throw 'exit (cdr entry))))
13069 nil)))))
13071 ;;;; Dynamic blocks
13073 (defun org-find-dblock (name)
13074 "Find the first dynamic block with name NAME in the buffer.
13075 If not found, stay at current position and return nil."
13076 (let (pos)
13077 (save-excursion
13078 (goto-char (point-min))
13079 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13080 nil t)
13081 (match-beginning 0))))
13082 (if pos (goto-char pos))
13083 pos))
13085 (defconst org-dblock-start-re
13086 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13087 "Matches the startline of a dynamic block, with parameters.")
13089 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13090 "Matches the end of a dyhamic block.")
13092 (defun org-create-dblock (plist)
13093 "Create a dynamic block section, with parameters taken from PLIST.
13094 PLIST must containe a :name entry which is used as name of the block."
13095 (unless (bolp) (newline))
13096 (let ((name (plist-get plist :name)))
13097 (insert "#+BEGIN: " name)
13098 (while plist
13099 (if (eq (car plist) :name)
13100 (setq plist (cddr plist))
13101 (insert " " (prin1-to-string (pop plist)))))
13102 (insert "\n\n#+END:\n")
13103 (beginning-of-line -2)))
13105 (defun org-prepare-dblock ()
13106 "Prepare dynamic block for refresh.
13107 This empties the block, puts the cursor at the insert position and returns
13108 the property list including an extra property :name with the block name."
13109 (unless (looking-at org-dblock-start-re)
13110 (error "Not at a dynamic block"))
13111 (let* ((begdel (1+ (match-end 0)))
13112 (name (org-no-properties (match-string 1)))
13113 (params (append (list :name name)
13114 (read (concat "(" (match-string 3) ")")))))
13115 (unless (re-search-forward org-dblock-end-re nil t)
13116 (error "Dynamic block not terminated"))
13117 (delete-region begdel (match-beginning 0))
13118 (goto-char begdel)
13119 (open-line 1)
13120 params))
13122 (defun org-map-dblocks (&optional command)
13123 "Apply COMMAND to all dynamic blocks in the current buffer.
13124 If COMMAND is not given, use `org-update-dblock'."
13125 (let ((cmd (or command 'org-update-dblock))
13126 pos)
13127 (save-excursion
13128 (goto-char (point-min))
13129 (while (re-search-forward org-dblock-start-re nil t)
13130 (goto-char (setq pos (match-beginning 0)))
13131 (condition-case nil
13132 (funcall cmd)
13133 (error (message "Error during update of dynamic block")))
13134 (goto-char pos)
13135 (unless (re-search-forward org-dblock-end-re nil t)
13136 (error "Dynamic block not terminated"))))))
13138 (defun org-dblock-update (&optional arg)
13139 "User command for updating dynamic blocks.
13140 Update the dynamic block at point. With prefix ARG, update all dynamic
13141 blocks in the buffer."
13142 (interactive "P")
13143 (if arg
13144 (org-update-all-dblocks)
13145 (or (looking-at org-dblock-start-re)
13146 (org-beginning-of-dblock))
13147 (org-update-dblock)))
13149 (defun org-update-dblock ()
13150 "Update the dynamic block at point
13151 This means to empty the block, parse for parameters and then call
13152 the correct writing function."
13153 (save-window-excursion
13154 (let* ((pos (point))
13155 (line (org-current-line))
13156 (params (org-prepare-dblock))
13157 (name (plist-get params :name))
13158 (cmd (intern (concat "org-dblock-write:" name))))
13159 (message "Updating dynamic block `%s' at line %d..." name line)
13160 (funcall cmd params)
13161 (message "Updating dynamic block `%s' at line %d...done" name line)
13162 (goto-char pos))))
13164 (defun org-beginning-of-dblock ()
13165 "Find the beginning of the dynamic block at point.
13166 Error if there is no scuh block at point."
13167 (let ((pos (point))
13168 beg)
13169 (end-of-line 1)
13170 (if (and (re-search-backward org-dblock-start-re nil t)
13171 (setq beg (match-beginning 0))
13172 (re-search-forward org-dblock-end-re nil t)
13173 (> (match-end 0) pos))
13174 (goto-char beg)
13175 (goto-char pos)
13176 (error "Not in a dynamic block"))))
13178 (defun org-update-all-dblocks ()
13179 "Update all dynamic blocks in the buffer.
13180 This function can be used in a hook."
13181 (when (org-mode-p)
13182 (org-map-dblocks 'org-update-dblock)))
13185 ;;;; Completion
13187 (defconst org-additional-option-like-keywords
13188 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13189 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:"))
13191 (defun org-complete (&optional arg)
13192 "Perform completion on word at point.
13193 At the beginning of a headline, this completes TODO keywords as given in
13194 `org-todo-keywords'.
13195 If the current word is preceded by a backslash, completes the TeX symbols
13196 that are supported for HTML support.
13197 If the current word is preceded by \"#+\", completes special words for
13198 setting file options.
13199 In the line after \"#+STARTUP:, complete valid keywords.\"
13200 At all other locations, this simply calls the value of
13201 `org-completion-fallback-command'."
13202 (interactive "P")
13203 (org-without-partial-completion
13204 (catch 'exit
13205 (let* ((end (point))
13206 (beg1 (save-excursion
13207 (skip-chars-backward (org-re "[:alnum:]_@"))
13208 (point)))
13209 (beg (save-excursion
13210 (skip-chars-backward "a-zA-Z0-9_:$")
13211 (point)))
13212 (confirm (lambda (x) (stringp (car x))))
13213 (searchhead (equal (char-before beg) ?*))
13214 (tag (and (equal (char-before beg1) ?:)
13215 (equal (char-after (point-at-bol)) ?*)))
13216 (prop (and (equal (char-before beg1) ?:)
13217 (not (equal (char-after (point-at-bol)) ?*))))
13218 (texp (equal (char-before beg) ?\\))
13219 (link (equal (char-before beg) ?\[))
13220 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13221 beg)
13222 "#+"))
13223 (startup (string-match "^#\\+STARTUP:.*"
13224 (buffer-substring (point-at-bol) (point))))
13225 (completion-ignore-case opt)
13226 (type nil)
13227 (tbl nil)
13228 (table (cond
13229 (opt
13230 (setq type :opt)
13231 (append
13232 (mapcar
13233 (lambda (x)
13234 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13235 (cons (match-string 2 x) (match-string 1 x)))
13236 (org-split-string (org-get-current-options) "\n"))
13237 (mapcar 'list org-additional-option-like-keywords)))
13238 (startup
13239 (setq type :startup)
13240 org-startup-options)
13241 (link (append org-link-abbrev-alist-local
13242 org-link-abbrev-alist))
13243 (texp
13244 (setq type :tex)
13245 org-html-entities)
13246 ((string-match "\\`\\*+[ \t]+\\'"
13247 (buffer-substring (point-at-bol) beg))
13248 (setq type :todo)
13249 (mapcar 'list org-todo-keywords-1))
13250 (searchhead
13251 (setq type :searchhead)
13252 (save-excursion
13253 (goto-char (point-min))
13254 (while (re-search-forward org-todo-line-regexp nil t)
13255 (push (list
13256 (org-make-org-heading-search-string
13257 (match-string 3) t))
13258 tbl)))
13259 tbl)
13260 (tag (setq type :tag beg beg1)
13261 (or org-tag-alist (org-get-buffer-tags)))
13262 (prop (setq type :prop beg beg1)
13263 (mapcar 'list (org-buffer-property-keys)))
13264 (t (progn
13265 (call-interactively org-completion-fallback-command)
13266 (throw 'exit nil)))))
13267 (pattern (buffer-substring-no-properties beg end))
13268 (completion (try-completion pattern table confirm)))
13269 (cond ((eq completion t)
13270 (if (not (assoc (upcase pattern) table))
13271 (message "Already complete")
13272 (if (equal type :opt)
13273 (insert (substring (cdr (assoc (upcase pattern) table))
13274 (length pattern)))
13275 (if (memq type '(:tag :prop)) (insert ":")))))
13276 ((null completion)
13277 (message "Can't find completion for \"%s\"" pattern)
13278 (ding))
13279 ((not (string= pattern completion))
13280 (delete-region beg end)
13281 (if (string-match " +$" completion)
13282 (setq completion (replace-match "" t t completion)))
13283 (insert completion)
13284 (if (get-buffer-window "*Completions*")
13285 (delete-window (get-buffer-window "*Completions*")))
13286 (if (assoc completion table)
13287 (if (eq type :todo) (insert " ")
13288 (if (memq type '(:tag :prop)) (insert ":"))))
13289 (if (and (equal type :opt) (assoc completion table))
13290 (message "%s" (substitute-command-keys
13291 "Press \\[org-complete] again to insert example settings"))))
13293 (message "Making completion list...")
13294 (let ((list (sort (all-completions pattern table confirm)
13295 'string<)))
13296 (with-output-to-temp-buffer "*Completions*"
13297 (condition-case nil
13298 ;; Protection needed for XEmacs and emacs 21
13299 (display-completion-list list pattern)
13300 (error (display-completion-list list)))))
13301 (message "Making completion list...%s" "done")))))))
13303 ;;;; TODO, DEADLINE, Comments
13305 (defun org-toggle-comment ()
13306 "Change the COMMENT state of an entry."
13307 (interactive)
13308 (save-excursion
13309 (org-back-to-heading)
13310 (if (looking-at (concat outline-regexp
13311 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13312 (replace-match "" t t nil 1)
13313 (if (looking-at outline-regexp)
13314 (progn
13315 (goto-char (match-end 0))
13316 (insert org-comment-string " "))))))
13318 (defvar org-last-todo-state-is-todo nil
13319 "This is non-nil when the last TODO state change led to a TODO state.
13320 If the last change removed the TODO tag or switched to DONE, then
13321 this is nil.")
13323 (defvar org-setting-tags nil) ; dynamically skiped
13325 ;; FIXME: better place
13326 (defun org-property-or-variable-value (var &optional inherit)
13327 "Check if there is a property fixing the value of VAR.
13328 If yes, return this value. If not, return the current value of the variable."
13329 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13330 (if (and prop (stringp prop) (string-match "\\S-" prop))
13331 (read prop)
13332 (symbol-value var))))
13334 (defun org-parse-local-options (string var)
13335 "Parse STRING for startup setting relevant for variable VAR."
13336 (let ((rtn (symbol-value var))
13337 e opts)
13338 (save-match-data
13339 (if (or (not string) (not (string-match "\\S-" string)))
13341 (setq opts (delq nil (mapcar (lambda (x)
13342 (setq e (assoc x org-startup-options))
13343 (if (eq (nth 1 e) var) e nil))
13344 (org-split-string string "[ \t]+"))))
13345 (if (not opts)
13347 (setq rtn nil)
13348 (while (setq e (pop opts))
13349 (if (not (nth 3 e))
13350 (setq rtn (nth 2 e))
13351 (if (not (listp rtn)) (setq rtn nil))
13352 (push (nth 2 e) rtn)))
13353 rtn)))))
13355 (defvar org-blocker-hook nil
13356 "Hook for functions that are allowed to block a state change.
13358 Each function gets as its single argument a property list, see
13359 `org-trigger-hook' for more information about this list.
13361 If any of the functions in this hook returns nil, the state change
13362 is blocked.")
13364 (defvar org-trigger-hook nil
13365 "Hook for functions that are triggered by a state change.
13367 Each function gets as its single argument a property list with at least
13368 the following elements:
13370 (:type type-of-change :position pos-at-entry-start
13371 :from old-state :to new-state)
13373 Depending on the type, more properties may be present.
13375 This mechanism is currently implemented for:
13377 TODO state changes
13378 ------------------
13379 :type todo-state-change
13380 :from previous state (keyword as a string), or nil
13381 :to new state (keyword as a string), or nil")
13384 (defun org-todo (&optional arg)
13385 "Change the TODO state of an item.
13386 The state of an item is given by a keyword at the start of the heading,
13387 like
13388 *** TODO Write paper
13389 *** DONE Call mom
13391 The different keywords are specified in the variable `org-todo-keywords'.
13392 By default the available states are \"TODO\" and \"DONE\".
13393 So for this example: when the item starts with TODO, it is changed to DONE.
13394 When it starts with DONE, the DONE is removed. And when neither TODO nor
13395 DONE are present, add TODO at the beginning of the heading.
13397 With C-u prefix arg, use completion to determine the new state.
13398 With numeric prefix arg, switch to that state.
13400 For calling through lisp, arg is also interpreted in the following way:
13401 'none -> empty state
13402 \"\"(empty string) -> switch to empty state
13403 'done -> switch to DONE
13404 'nextset -> switch to the next set of keywords
13405 'previousset -> switch to the previous set of keywords
13406 \"WAITING\" -> switch to the specified keyword, but only if it
13407 really is a member of `org-todo-keywords'."
13408 (interactive "P")
13409 (save-excursion
13410 (catch 'exit
13411 (org-back-to-heading)
13412 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13413 (or (looking-at (concat " +" org-todo-regexp " *"))
13414 (looking-at " *"))
13415 (let* ((match-data (match-data))
13416 (startpos (line-beginning-position))
13417 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13418 (org-log-done (org-parse-local-options logging 'org-log-done))
13419 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13420 (this (match-string 1))
13421 (hl-pos (match-beginning 0))
13422 (head (org-get-todo-sequence-head this))
13423 (ass (assoc head org-todo-kwd-alist))
13424 (interpret (nth 1 ass))
13425 (done-word (nth 3 ass))
13426 (final-done-word (nth 4 ass))
13427 (last-state (or this ""))
13428 (completion-ignore-case t)
13429 (member (member this org-todo-keywords-1))
13430 (tail (cdr member))
13431 (state (cond
13432 ((and org-todo-key-trigger
13433 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13434 (and (not arg) org-use-fast-todo-selection
13435 (not (eq org-use-fast-todo-selection 'prefix)))))
13436 ;; Use fast selection
13437 (org-fast-todo-selection))
13438 ((and (equal arg '(4))
13439 (or (not org-use-fast-todo-selection)
13440 (not org-todo-key-trigger)))
13441 ;; Read a state with completion
13442 (completing-read "State: " (mapcar (lambda(x) (list x))
13443 org-todo-keywords-1)
13444 nil t))
13445 ((eq arg 'right)
13446 (if this
13447 (if tail (car tail) nil)
13448 (car org-todo-keywords-1)))
13449 ((eq arg 'left)
13450 (if (equal member org-todo-keywords-1)
13452 (if this
13453 (nth (- (length org-todo-keywords-1) (length tail) 2)
13454 org-todo-keywords-1)
13455 (org-last org-todo-keywords-1))))
13456 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13457 (setq arg nil))) ; hack to fall back to cycling
13458 (arg
13459 ;; user or caller requests a specific state
13460 (cond
13461 ((equal arg "") nil)
13462 ((eq arg 'none) nil)
13463 ((eq arg 'done) (or done-word (car org-done-keywords)))
13464 ((eq arg 'nextset)
13465 (or (car (cdr (member head org-todo-heads)))
13466 (car org-todo-heads)))
13467 ((eq arg 'previousset)
13468 (let ((org-todo-heads (reverse org-todo-heads)))
13469 (or (car (cdr (member head org-todo-heads)))
13470 (car org-todo-heads))))
13471 ((car (member arg org-todo-keywords-1)))
13472 ((nth (1- (prefix-numeric-value arg))
13473 org-todo-keywords-1))))
13474 ((null member) (or head (car org-todo-keywords-1)))
13475 ((equal this final-done-word) nil) ;; -> make empty
13476 ((null tail) nil) ;; -> first entry
13477 ((eq interpret 'sequence)
13478 (car tail))
13479 ((memq interpret '(type priority))
13480 (if (eq this-command last-command)
13481 (car tail)
13482 (if (> (length tail) 0)
13483 (or done-word (car org-done-keywords))
13484 nil)))
13485 (t nil)))
13486 (next (if state (concat " " state " ") " "))
13487 (change-plist (list :type 'todo-state-change :from this :to state
13488 :position startpos))
13489 dostates)
13490 (when org-blocker-hook
13491 (unless (save-excursion
13492 (save-match-data
13493 (run-hook-with-args-until-failure
13494 'org-blocker-hook change-plist)))
13495 (if (interactive-p)
13496 (error "TODO state change from %s to %s blocked" this state)
13497 ;; fail silently
13498 (message "TODO state change from %s to %s blocked" this state)
13499 (throw 'exit nil))))
13500 (store-match-data match-data)
13501 (replace-match next t t)
13502 (unless (pos-visible-in-window-p hl-pos)
13503 (message "TODO state changed to %s" (org-trim next)))
13504 (unless head
13505 (setq head (org-get-todo-sequence-head state)
13506 ass (assoc head org-todo-kwd-alist)
13507 interpret (nth 1 ass)
13508 done-word (nth 3 ass)
13509 final-done-word (nth 4 ass)))
13510 (when (memq arg '(nextset previousset))
13511 (message "Keyword-Set %d/%d: %s"
13512 (- (length org-todo-sets) -1
13513 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13514 (length org-todo-sets)
13515 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13516 (setq org-last-todo-state-is-todo
13517 (not (member state org-done-keywords)))
13518 (when (and org-log-done (not (memq arg '(nextset previousset))))
13519 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13520 (or (not org-todo-log-states)
13521 (member state org-todo-log-states))))
13523 (cond
13524 ((and state (member state org-not-done-keywords)
13525 (not (member this org-not-done-keywords)))
13526 ;; This is now a todo state and was not one before
13527 ;; Remove any CLOSED timestamp, and possibly log the state change
13528 (org-add-planning-info nil nil 'closed)
13529 (and dostates (org-add-log-maybe 'state state 'findpos)))
13530 ((and state dostates)
13531 ;; This is a non-nil state, and we need to log it
13532 (org-add-log-maybe 'state state 'findpos))
13533 ((and (member state org-done-keywords)
13534 (not (member this org-done-keywords)))
13535 ;; It is now done, and it was not done before
13536 (org-add-planning-info 'closed (org-current-time))
13537 (org-add-log-maybe 'done state 'findpos))))
13538 ;; Fixup tag positioning
13539 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13540 (run-hooks 'org-after-todo-state-change-hook)
13541 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13542 (if (and arg (not (member state org-done-keywords)))
13543 (setq head (org-get-todo-sequence-head state)))
13544 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
13545 ;; Fixup cursor location if close to the keyword
13546 (if (and (outline-on-heading-p)
13547 (not (bolp))
13548 (save-excursion (beginning-of-line 1)
13549 (looking-at org-todo-line-regexp))
13550 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13551 (progn
13552 (goto-char (or (match-end 2) (match-end 1)))
13553 (just-one-space)))
13554 (when org-trigger-hook
13555 (save-excursion
13556 (run-hook-with-args 'org-trigger-hook change-plist)))))))
13558 (defun org-get-todo-sequence-head (kwd)
13559 "Return the head of the TODO sequence to which KWD belongs.
13560 If KWD is not set, check if there is a text property remembering the
13561 right sequence."
13562 (let (p)
13563 (cond
13564 ((not kwd)
13565 (or (get-text-property (point-at-bol) 'org-todo-head)
13566 (progn
13567 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13568 nil (point-at-eol)))
13569 (get-text-property p 'org-todo-head))))
13570 ((not (member kwd org-todo-keywords-1))
13571 (car org-todo-keywords-1))
13572 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13574 (defun org-fast-todo-selection ()
13575 "Fast TODO keyword selection with single keys.
13576 Returns the new TODO keyword, or nil if no state change should occur."
13577 (let* ((fulltable org-todo-key-alist)
13578 (done-keywords org-done-keywords) ;; needed for the faces.
13579 (maxlen (apply 'max (mapcar
13580 (lambda (x)
13581 (if (stringp (car x)) (string-width (car x)) 0))
13582 fulltable)))
13583 (expert nil)
13584 (fwidth (+ maxlen 3 1 3))
13585 (ncol (/ (- (window-width) 4) fwidth))
13586 tg cnt e c tbl
13587 groups ingroup)
13588 (save-window-excursion
13589 (if expert
13590 (set-buffer (get-buffer-create " *Org todo*"))
13591 ; (delete-other-windows)
13592 ; (split-window-vertically)
13593 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13594 (erase-buffer)
13595 (org-set-local 'org-done-keywords done-keywords)
13596 (setq tbl fulltable cnt 0)
13597 (while (setq e (pop tbl))
13598 (cond
13599 ((equal e '(:startgroup))
13600 (push '() groups) (setq ingroup t)
13601 (when (not (= cnt 0))
13602 (setq cnt 0)
13603 (insert "\n"))
13604 (insert "{ "))
13605 ((equal e '(:endgroup))
13606 (setq ingroup nil cnt 0)
13607 (insert "}\n"))
13609 (setq tg (car e) c (cdr e))
13610 (if ingroup (push tg (car groups)))
13611 (setq tg (org-add-props tg nil 'face
13612 (org-get-todo-face tg)))
13613 (if (and (= cnt 0) (not ingroup)) (insert " "))
13614 (insert "[" c "] " tg (make-string
13615 (- fwidth 4 (length tg)) ?\ ))
13616 (when (= (setq cnt (1+ cnt)) ncol)
13617 (insert "\n")
13618 (if ingroup (insert " "))
13619 (setq cnt 0)))))
13620 (insert "\n")
13621 (goto-char (point-min))
13622 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13623 (fit-window-to-buffer))
13624 (message "[a-z..]:Set [SPC]:clear")
13625 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13626 (cond
13627 ((or (= c ?\C-g)
13628 (and (= c ?q) (not (rassoc c fulltable))))
13629 (setq quit-flag t))
13630 ((= c ?\ ) nil)
13631 ((setq e (rassoc c fulltable) tg (car e))
13633 (t (setq quit-flag t))))))
13635 (defun org-get-repeat ()
13636 "Check if tere is a deadline/schedule with repeater in this entry."
13637 (save-match-data
13638 (save-excursion
13639 (org-back-to-heading t)
13640 (if (re-search-forward
13641 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13642 (match-string 1)))))
13644 (defvar org-last-changed-timestamp)
13645 (defvar org-log-post-message)
13646 (defun org-auto-repeat-maybe ()
13647 "Check if the current headline contains a repeated deadline/schedule.
13648 If yes, set TODO state back to what it was and change the base date
13649 of repeating deadline/scheduled time stamps to new date.
13650 This function should be run in the `org-after-todo-state-change-hook'."
13651 ;; last-state is dynamically scoped into this function
13652 (let* ((repeat (org-get-repeat))
13653 (aa (assoc last-state org-todo-kwd-alist))
13654 (interpret (nth 1 aa))
13655 (head (nth 2 aa))
13656 (done-word (nth 3 aa))
13657 (whata '(("d" . day) ("m" . month) ("y" . year)))
13658 (msg "Entry repeats: ")
13659 (org-log-done)
13660 re type n what ts)
13661 (when repeat
13662 (org-todo (if (eq interpret 'type) last-state head))
13663 (when (and org-log-repeat
13664 (not (memq 'org-add-log-note
13665 (default-value 'post-command-hook))))
13666 ;; Make sure a note is taken
13667 (let ((org-log-done '(done)))
13668 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13669 'findpos)))
13670 (org-back-to-heading t)
13671 (org-add-planning-info nil nil 'closed)
13672 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13673 org-deadline-time-regexp "\\)"))
13674 (while (re-search-forward
13675 re (save-excursion (outline-next-heading) (point)) t)
13676 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13677 ts (match-string (if (match-end 2) 2 4)))
13678 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13679 (setq n (string-to-number (match-string 1 ts))
13680 what (match-string 2 ts))
13681 (if (equal what "w") (setq n (* n 7) what "d"))
13682 (org-timestamp-change n (cdr (assoc what whata))))
13683 (setq msg (concat msg type org-last-changed-timestamp " ")))
13684 (setq org-log-post-message msg)
13685 (message msg))))
13687 (defun org-show-todo-tree (arg)
13688 "Make a compact tree which shows all headlines marked with TODO.
13689 The tree will show the lines where the regexp matches, and all higher
13690 headlines above the match.
13691 With \\[universal-argument] prefix, also show the DONE entries.
13692 With a numeric prefix N, construct a sparse tree for the Nth element
13693 of `org-todo-keywords-1'."
13694 (interactive "P")
13695 (let ((case-fold-search nil)
13696 (kwd-re
13697 (cond ((null arg) org-not-done-regexp)
13698 ((equal arg '(4))
13699 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13700 (mapcar 'list org-todo-keywords-1))))
13701 (concat "\\("
13702 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13703 "\\)\\>")))
13704 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13705 (regexp-quote (nth (1- (prefix-numeric-value arg))
13706 org-todo-keywords-1)))
13707 (t (error "Invalid prefix argument: %s" arg)))))
13708 (message "%d TODO entries found"
13709 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13711 (defun org-deadline (&optional remove)
13712 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13713 With argument REMOVE, remove any deadline from the item."
13714 (interactive "P")
13715 (if remove
13716 (progn
13717 (org-add-planning-info nil nil 'deadline)
13718 (message "Item no longer has a deadline."))
13719 (org-add-planning-info 'deadline nil 'closed)))
13721 (defun org-schedule (&optional remove)
13722 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13723 With argument REMOVE, remove any scheduling date from the item."
13724 (interactive "P")
13725 (if remove
13726 (progn
13727 (org-add-planning-info nil nil 'scheduled)
13728 (message "Item is no longer scheduled."))
13729 (org-add-planning-info 'scheduled nil 'closed)))
13731 (defun org-add-planning-info (what &optional time &rest remove)
13732 "Insert new timestamp with keyword in the line directly after the headline.
13733 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13734 If non is given, the user is prompted for a date.
13735 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13736 be removed."
13737 (interactive)
13738 (let (org-time-was-given org-end-time-was-given)
13739 (when what (setq time (or time (org-read-date nil 'to-time))))
13740 (when (and org-insert-labeled-timestamps-at-point
13741 (member what '(scheduled deadline)))
13742 (insert
13743 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
13744 (org-insert-time-stamp time org-time-was-given
13745 nil nil nil (list org-end-time-was-given))
13746 (setq what nil))
13747 (save-excursion
13748 (save-restriction
13749 (let (col list elt ts buffer-invisibility-spec)
13750 (org-back-to-heading t)
13751 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
13752 (goto-char (match-end 1))
13753 (setq col (current-column))
13754 (goto-char (match-end 0))
13755 (if (eobp) (insert "\n") (forward-char 1))
13756 (if (and (not (looking-at outline-regexp))
13757 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
13758 "[^\r\n]*"))
13759 (not (equal (match-string 1) org-clock-string)))
13760 (narrow-to-region (match-beginning 0) (match-end 0))
13761 (insert-before-markers "\n")
13762 (backward-char 1)
13763 (narrow-to-region (point) (point))
13764 (indent-to-column col))
13765 ;; Check if we have to remove something.
13766 (setq list (cons what remove))
13767 (while list
13768 (setq elt (pop list))
13769 (goto-char (point-min))
13770 (when (or (and (eq elt 'scheduled)
13771 (re-search-forward org-scheduled-time-regexp nil t))
13772 (and (eq elt 'deadline)
13773 (re-search-forward org-deadline-time-regexp nil t))
13774 (and (eq elt 'closed)
13775 (re-search-forward org-closed-time-regexp nil t)))
13776 (replace-match "")
13777 (if (looking-at "--+<[^>]+>") (replace-match ""))
13778 (if (looking-at " +") (replace-match ""))))
13779 (goto-char (point-max))
13780 (when what
13781 (insert
13782 (if (not (equal (char-before) ?\ )) " " "")
13783 (cond ((eq what 'scheduled) org-scheduled-string)
13784 ((eq what 'deadline) org-deadline-string)
13785 ((eq what 'closed) org-closed-string))
13786 " ")
13787 (setq ts (org-insert-time-stamp
13788 time
13789 (or org-time-was-given
13790 (and (eq what 'closed) org-log-done-with-time))
13791 (eq what 'closed)
13792 nil nil (list org-end-time-was-given)))
13793 (end-of-line 1))
13794 (goto-char (point-min))
13795 (widen)
13796 (if (looking-at "[ \t]+\r?\n")
13797 (replace-match ""))
13798 ts)))))
13800 (defvar org-log-note-marker (make-marker))
13801 (defvar org-log-note-purpose nil)
13802 (defvar org-log-note-state nil)
13803 (defvar org-log-note-window-configuration nil)
13804 (defvar org-log-note-return-to (make-marker))
13805 (defvar org-log-post-message nil
13806 "Message to be displayed after a log note has been stored.
13807 The auto-repeater uses this.")
13809 (defun org-add-log-maybe (&optional purpose state findpos)
13810 "Set up the post command hook to take a note."
13811 (save-excursion
13812 (when (and (listp org-log-done)
13813 (memq purpose org-log-done))
13814 (when findpos
13815 (org-back-to-heading t)
13816 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
13817 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
13818 "[^\r\n]*\\)?"))
13819 (goto-char (match-end 0))
13820 (unless org-log-states-order-reversed
13821 (and (= (char-after) ?\n) (forward-char 1))
13822 (org-skip-over-state-notes)
13823 (skip-chars-backward " \t\n\r")))
13824 (move-marker org-log-note-marker (point))
13825 (setq org-log-note-purpose purpose)
13826 (setq org-log-note-state state)
13827 (add-hook 'post-command-hook 'org-add-log-note 'append))))
13829 (defun org-skip-over-state-notes ()
13830 "Skip past the list of State notes in an entry."
13831 (if (looking-at "\n[ \t]*- State") (forward-char 1))
13832 (while (looking-at "[ \t]*- State")
13833 (condition-case nil
13834 (org-next-item)
13835 (error (org-end-of-item)))))
13837 (defun org-add-log-note (&optional purpose)
13838 "Pop up a window for taking a note, and add this note later at point."
13839 (remove-hook 'post-command-hook 'org-add-log-note)
13840 (setq org-log-note-window-configuration (current-window-configuration))
13841 (delete-other-windows)
13842 (move-marker org-log-note-return-to (point))
13843 (switch-to-buffer (marker-buffer org-log-note-marker))
13844 (goto-char org-log-note-marker)
13845 (org-switch-to-buffer-other-window "*Org Note*")
13846 (erase-buffer)
13847 (let ((org-inhibit-startup t)) (org-mode))
13848 (insert (format "# Insert note for %s.
13849 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13850 (cond
13851 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13852 ((eq org-log-note-purpose 'done) "closed todo item")
13853 ((eq org-log-note-purpose 'state)
13854 (format "state change to \"%s\"" org-log-note-state))
13855 (t (error "This should not happen")))))
13856 (org-set-local 'org-finish-function 'org-store-log-note))
13858 (defun org-store-log-note ()
13859 "Finish taking a log note, and insert it to where it belongs."
13860 (let ((txt (buffer-string))
13861 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13862 lines ind)
13863 (kill-buffer (current-buffer))
13864 (while (string-match "\\`#.*\n[ \t\n]*" txt)
13865 (setq txt (replace-match "" t t txt)))
13866 (if (string-match "\\s-+\\'" txt)
13867 (setq txt (replace-match "" t t txt)))
13868 (setq lines (org-split-string txt "\n"))
13869 (when (and note (string-match "\\S-" note))
13870 (setq note
13871 (org-replace-escapes
13872 note
13873 (list (cons "%u" (user-login-name))
13874 (cons "%U" user-full-name)
13875 (cons "%t" (format-time-string
13876 (org-time-stamp-format 'long 'inactive)
13877 (current-time)))
13878 (cons "%s" (if org-log-note-state
13879 (concat "\"" org-log-note-state "\"")
13880 "")))))
13881 (if lines (setq note (concat note " \\\\")))
13882 (push note lines))
13883 (when (or current-prefix-arg org-note-abort) (setq lines nil))
13884 (when lines
13885 (save-excursion
13886 (set-buffer (marker-buffer org-log-note-marker))
13887 (save-excursion
13888 (goto-char org-log-note-marker)
13889 (move-marker org-log-note-marker nil)
13890 (end-of-line 1)
13891 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13892 (indent-relative nil)
13893 (insert " - " (pop lines))
13894 (org-indent-line-function)
13895 (beginning-of-line 1)
13896 (looking-at "[ \t]*")
13897 (setq ind (concat (match-string 0) " "))
13898 (end-of-line 1)
13899 (while lines (insert "\n" ind (pop lines)))))))
13900 (set-window-configuration org-log-note-window-configuration)
13901 (with-current-buffer (marker-buffer org-log-note-return-to)
13902 (goto-char org-log-note-return-to))
13903 (move-marker org-log-note-return-to nil)
13904 (and org-log-post-message (message org-log-post-message)))
13906 ;; FIXME: what else would be useful?
13907 ;; - priority
13908 ;; - date
13910 (defun org-sparse-tree (&optional arg)
13911 "Create a sparse tree, prompt for the details.
13912 This command can create sparse trees. You first need to select the type
13913 of match used to create the tree:
13915 t Show entries with a specific TODO keyword.
13916 T Show entries selected by a tags match.
13917 p Enter a property name and its value (both with completion on existing
13918 names/values) and show entries with that property.
13919 r Show entries matching a regular expression"
13920 (interactive "P")
13921 (let (ans kwd value)
13922 (message "Sparse tree: [r]egexp [t]odo-kwd [T]ag [p]roperty")
13923 (setq ans (read-char-exclusive))
13924 (cond
13925 ((equal ans ?t)
13926 (org-show-todo-tree '(4)))
13927 ((equal ans ?T)
13928 (call-interactively 'org-tags-sparse-tree))
13929 ((member ans '(?p ?P))
13930 (setq kwd (completing-read "Property: "
13931 (mapcar 'list (org-buffer-property-keys))))
13932 (setq value (completing-read "Value: "
13933 (mapcar 'list (org-property-values kwd))))
13934 (unless (string-match "\\`{.*}\\'" value)
13935 (setq value (concat "\"" value "\"")))
13936 (org-tags-sparse-tree arg (concat kwd "=" value)))
13937 ((member ans '(?r ?R))
13938 (call-interactively 'org-occur))
13939 (t (error "No such sparse tree command \"%c\"" ans)))))
13941 (defvar org-occur-highlights nil)
13942 (make-variable-buffer-local 'org-occur-highlights)
13944 (defun org-occur (regexp &optional keep-previous callback)
13945 "Make a compact tree which shows all matches of REGEXP.
13946 The tree will show the lines where the regexp matches, and all higher
13947 headlines above the match. It will also show the heading after the match,
13948 to make sure editing the matching entry is easy.
13949 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13950 call to `org-occur' will be kept, to allow stacking of calls to this
13951 command.
13952 If CALLBACK is non-nil, it is a function which is called to confirm
13953 that the match should indeed be shown."
13954 (interactive "sRegexp: \nP")
13955 (or keep-previous (org-remove-occur-highlights nil nil t))
13956 (let ((cnt 0))
13957 (save-excursion
13958 (goto-char (point-min))
13959 (if (or (not keep-previous) ; do not want to keep
13960 (not org-occur-highlights)) ; no previous matches
13961 ;; hide everything
13962 (org-overview))
13963 (while (re-search-forward regexp nil t)
13964 (when (or (not callback)
13965 (save-match-data (funcall callback)))
13966 (setq cnt (1+ cnt))
13967 (when org-highlight-sparse-tree-matches
13968 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13969 (org-show-context 'occur-tree))))
13970 (when org-remove-highlights-with-change
13971 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13972 nil 'local))
13973 (unless org-sparse-tree-open-archived-trees
13974 (org-hide-archived-subtrees (point-min) (point-max)))
13975 (run-hooks 'org-occur-hook)
13976 (if (interactive-p)
13977 (message "%d match(es) for regexp %s" cnt regexp))
13978 cnt))
13980 (defun org-show-context (&optional key)
13981 "Make sure point and context and visible.
13982 How much context is shown depends upon the variables
13983 `org-show-hierarchy-above', `org-show-following-heading'. and
13984 `org-show-siblings'."
13985 (let ((heading-p (org-on-heading-p t))
13986 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
13987 (following-p (org-get-alist-option org-show-following-heading key))
13988 (siblings-p (org-get-alist-option org-show-siblings key)))
13989 (catch 'exit
13990 ;; Show heading or entry text
13991 (if heading-p
13992 (org-flag-heading nil) ; only show the heading
13993 (and (or (org-invisible-p) (org-invisible-p2))
13994 (org-show-hidden-entry))) ; show entire entry
13995 (when following-p
13996 ;; Show next sibling, or heading below text
13997 (save-excursion
13998 (and (if heading-p (org-goto-sibling) (outline-next-heading))
13999 (org-flag-heading nil))))
14000 (when siblings-p (org-show-siblings))
14001 (when hierarchy-p
14002 ;; show all higher headings, possibly with siblings
14003 (save-excursion
14004 (while (and (condition-case nil
14005 (progn (org-up-heading-all 1) t)
14006 (error nil))
14007 (not (bobp)))
14008 (org-flag-heading nil)
14009 (when siblings-p (org-show-siblings))))))))
14011 (defun org-reveal (&optional siblings)
14012 "Show current entry, hierarchy above it, and the following headline.
14013 This can be used to show a consistent set of context around locations
14014 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14015 not t for the search context.
14017 With optional argument SIBLINGS, on each level of the hierarchy all
14018 siblings are shown. This repairs the tree structure to what it would
14019 look like when opened with hierarchical calls to `org-cycle'."
14020 (interactive "P")
14021 (let ((org-show-hierarchy-above t)
14022 (org-show-following-heading t)
14023 (org-show-siblings (if siblings t org-show-siblings)))
14024 (org-show-context nil)))
14026 (defun org-highlight-new-match (beg end)
14027 "Highlight from BEG to END and mark the highlight is an occur headline."
14028 (let ((ov (org-make-overlay beg end)))
14029 (org-overlay-put ov 'face 'secondary-selection)
14030 (push ov org-occur-highlights)))
14032 (defun org-remove-occur-highlights (&optional beg end noremove)
14033 "Remove the occur highlights from the buffer.
14034 BEG and END are ignored. If NOREMOVE is nil, remove this function
14035 from the `before-change-functions' in the current buffer."
14036 (interactive)
14037 (unless org-inhibit-highlight-removal
14038 (mapc 'org-delete-overlay org-occur-highlights)
14039 (setq org-occur-highlights nil)
14040 (unless noremove
14041 (remove-hook 'before-change-functions
14042 'org-remove-occur-highlights 'local))))
14044 ;;;; Priorities
14046 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14047 "Regular expression matching the priority indicator.")
14049 (defvar org-remove-priority-next-time nil)
14051 (defun org-priority-up ()
14052 "Increase the priority of the current item."
14053 (interactive)
14054 (org-priority 'up))
14056 (defun org-priority-down ()
14057 "Decrease the priority of the current item."
14058 (interactive)
14059 (org-priority 'down))
14061 (defun org-priority (&optional action)
14062 "Change the priority of an item by ARG.
14063 ACTION can be `set', `up', `down', or a character."
14064 (interactive)
14065 (setq action (or action 'set))
14066 (let (current new news have remove)
14067 (save-excursion
14068 (org-back-to-heading)
14069 (if (looking-at org-priority-regexp)
14070 (setq current (string-to-char (match-string 2))
14071 have t)
14072 (setq current org-default-priority))
14073 (cond
14074 ((or (eq action 'set) (integerp action))
14075 (if (integerp action)
14076 (setq new action)
14077 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14078 (setq new (read-char-exclusive)))
14079 (if (and (= (upcase org-highest-priority) org-highest-priority)
14080 (= (upcase org-lowest-priority) org-lowest-priority))
14081 (setq new (upcase new)))
14082 (cond ((equal new ?\ ) (setq remove t))
14083 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14084 (error "Priority must be between `%c' and `%c'"
14085 org-highest-priority org-lowest-priority))))
14086 ((eq action 'up)
14087 (if (and (not have) (eq last-command this-command))
14088 (setq new org-lowest-priority)
14089 (setq new (if (and org-priority-start-cycle-with-default (not have))
14090 org-default-priority (1- current)))))
14091 ((eq action 'down)
14092 (if (and (not have) (eq last-command this-command))
14093 (setq new org-highest-priority)
14094 (setq new (if (and org-priority-start-cycle-with-default (not have))
14095 org-default-priority (1+ current)))))
14096 (t (error "Invalid action")))
14097 (if (or (< (upcase new) org-highest-priority)
14098 (> (upcase new) org-lowest-priority))
14099 (setq remove t))
14100 (setq news (format "%c" new))
14101 (if have
14102 (if remove
14103 (replace-match "" t t nil 1)
14104 (replace-match news t t nil 2))
14105 (if remove
14106 (error "No priority cookie found in line")
14107 (looking-at org-todo-line-regexp)
14108 (if (match-end 2)
14109 (progn
14110 (goto-char (match-end 2))
14111 (insert " [#" news "]"))
14112 (goto-char (match-beginning 3))
14113 (insert "[#" news "] ")))))
14114 (org-preserve-lc (org-set-tags nil 'align))
14115 (if remove
14116 (message "Priority removed")
14117 (message "Priority of current item set to %s" news))))
14120 (defun org-get-priority (s)
14121 "Find priority cookie and return priority."
14122 (save-match-data
14123 (if (not (string-match org-priority-regexp s))
14124 (* 1000 (- org-lowest-priority org-default-priority))
14125 (* 1000 (- org-lowest-priority
14126 (string-to-char (match-string 2 s)))))))
14128 ;;;; Tags
14130 (defun org-scan-tags (action matcher &optional todo-only)
14131 "Scan headline tags with inheritance and produce output ACTION.
14132 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14133 evaluated, testing if a given set of tags qualifies a headline for
14134 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14135 are included in the output."
14136 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14137 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14138 (org-re
14139 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14140 (props (list 'face nil
14141 'done-face 'org-done
14142 'undone-face nil
14143 'mouse-face 'highlight
14144 'org-not-done-regexp org-not-done-regexp
14145 'org-todo-regexp org-todo-regexp
14146 'keymap org-agenda-keymap
14147 'help-echo
14148 (format "mouse-2 or RET jump to org file %s"
14149 (abbreviate-file-name
14150 (or (buffer-file-name (buffer-base-buffer))
14151 (buffer-name (buffer-base-buffer)))))))
14152 (case-fold-search nil)
14153 lspos
14154 tags tags-list tags-alist (llast 0) rtn level category i txt
14155 todo marker entry priority)
14156 (save-excursion
14157 (goto-char (point-min))
14158 (when (eq action 'sparse-tree)
14159 (org-overview)
14160 (org-remove-occur-highlights))
14161 (while (re-search-forward re nil t)
14162 (catch :skip
14163 (setq todo (if (match-end 1) (match-string 2))
14164 tags (if (match-end 4) (match-string 4)))
14165 (goto-char (setq lspos (1+ (match-beginning 0))))
14166 (setq level (org-reduced-level (funcall outline-level))
14167 category (org-get-category))
14168 (setq i llast llast level)
14169 ;; remove tag lists from same and sublevels
14170 (while (>= i level)
14171 (when (setq entry (assoc i tags-alist))
14172 (setq tags-alist (delete entry tags-alist)))
14173 (setq i (1- i)))
14174 ;; add the nex tags
14175 (when tags
14176 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14177 tags-alist
14178 (cons (cons level tags) tags-alist)))
14179 ;; compile tags for current headline
14180 (setq tags-list
14181 (if org-use-tag-inheritance
14182 (apply 'append (mapcar 'cdr tags-alist))
14183 tags))
14184 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14185 (eval matcher)
14186 (or (not org-agenda-skip-archived-trees)
14187 (not (member org-archive-tag tags-list))))
14188 (and (eq action 'agenda) (org-agenda-skip))
14189 ;; list this headline
14191 (if (eq action 'sparse-tree)
14192 (progn
14193 (and org-highlight-sparse-tree-matches
14194 (org-get-heading) (match-end 0)
14195 (org-highlight-new-match
14196 (match-beginning 0) (match-beginning 1)))
14197 (org-show-context 'tags-tree))
14198 (setq txt (org-format-agenda-item
14200 (concat
14201 (if org-tags-match-list-sublevels
14202 (make-string (1- level) ?.) "")
14203 (org-get-heading))
14204 category tags-list)
14205 priority (org-get-priority txt))
14206 (goto-char lspos)
14207 (setq marker (org-agenda-new-marker))
14208 (org-add-props txt props
14209 'org-marker marker 'org-hd-marker marker 'org-category category
14210 'priority priority 'type "tagsmatch")
14211 (push txt rtn))
14212 ;; if we are to skip sublevels, jump to end of subtree
14213 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14214 (when (and (eq action 'sparse-tree)
14215 (not org-sparse-tree-open-archived-trees))
14216 (org-hide-archived-subtrees (point-min) (point-max)))
14217 (nreverse rtn)))
14219 (defvar todo-only) ;; dynamically scoped
14221 (defun org-tags-sparse-tree (&optional todo-only match)
14222 "Create a sparse tree according to tags string MATCH.
14223 MATCH can contain positive and negative selection of tags, like
14224 \"+WORK+URGENT-WITHBOSS\".
14225 If optional argument TODO_ONLY is non-nil, only select lines that are
14226 also TODO lines."
14227 (interactive "P")
14228 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14230 (defvar org-cached-props nil)
14231 (defun org-cached-entry-get (pom property)
14232 (if org-use-property-inheritance
14233 ;; Caching is not possible, check it directly
14234 (org-entry-get pom property 'inherit)
14235 ;; Get all properties, so that we can do complicated checks easily
14236 (cdr (assoc property (or org-cached-props
14237 (setq org-cached-props
14238 (org-entry-properties pom)))))))
14240 (defun org-global-tags-completion-table (&optional files)
14241 "Return the list of all tags in all agenda buffer/files."
14242 (save-excursion
14243 (org-uniquify
14244 (apply 'append
14245 (mapcar
14246 (lambda (file)
14247 (set-buffer (find-file-noselect file))
14248 (org-get-buffer-tags))
14249 (if (and files (car files))
14250 files
14251 (org-agenda-files)))))))
14253 (defun org-make-tags-matcher (match)
14254 "Create the TAGS//TODO matcher form for the selection string MATCH."
14255 ;; todo-only is scoped dynamically into this function, and the function
14256 ;; may change it it the matcher asksk for it.
14257 (unless match
14258 ;; Get a new match request, with completion
14259 (let ((org-last-tags-completion-table
14260 (org-global-tags-completion-table)))
14261 (setq match (completing-read
14262 "Match: " 'org-tags-completion-function nil nil nil
14263 'org-tags-history))))
14265 ;; Parse the string and create a lisp form
14266 (let ((match0 match)
14267 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14268 minus tag mm
14269 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14270 orterms term orlist re-p level-p prop-p pn pv)
14271 (if (string-match "/+" match)
14272 ;; match contains also a todo-matching request
14273 (progn
14274 (setq tagsmatch (substring match 0 (match-beginning 0))
14275 todomatch (substring match (match-end 0)))
14276 (if (string-match "^!" todomatch)
14277 (setq todo-only t todomatch (substring todomatch 1)))
14278 (if (string-match "^\\s-*$" todomatch)
14279 (setq todomatch nil)))
14280 ;; only matching tags
14281 (setq tagsmatch match todomatch nil))
14283 ;; Make the tags matcher
14284 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14285 (setq tagsmatcher t)
14286 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14287 (while (setq term (pop orterms))
14288 (while (and (equal (substring term -1) "\\") orterms)
14289 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14290 (while (string-match re term)
14291 (setq minus (and (match-end 1)
14292 (equal (match-string 1 term) "-"))
14293 tag (match-string 2 term)
14294 re-p (equal (string-to-char tag) ?{)
14295 level-p (match-end 3)
14296 prop-p (match-end 4)
14297 mm (cond
14298 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14299 (level-p `(= level ,(string-to-number
14300 (match-string 3 term))))
14301 (prop-p
14302 (setq pn (match-string 4 term)
14303 pv (match-string 5 term)
14304 re-p (equal (string-to-char pv) ?{)
14305 pv (substring pv 1 -1))
14306 (if re-p
14307 `(string-match ,pv (or (org-cached-entry-get nil ,pn) ""))
14308 `(equal ,pv (org-cached-entry-get nil ,pn))))
14309 (t `(member ,(downcase tag) tags-list)))
14310 mm (if minus (list 'not mm) mm)
14311 term (substring term (match-end 0)))
14312 (push mm tagsmatcher))
14313 (push (if (> (length tagsmatcher) 1)
14314 (cons 'and tagsmatcher)
14315 (car tagsmatcher))
14316 orlist)
14317 (setq tagsmatcher nil))
14318 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14319 (setq tagsmatcher
14320 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14322 ;; Make the todo matcher
14323 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14324 (setq todomatcher t)
14325 (setq orterms (org-split-string todomatch "|") orlist nil)
14326 (while (setq term (pop orterms))
14327 (while (string-match re term)
14328 (setq minus (and (match-end 1)
14329 (equal (match-string 1 term) "-"))
14330 kwd (match-string 2 term)
14331 re-p (equal (string-to-char kwd) ?{)
14332 term (substring term (match-end 0))
14333 mm (if re-p
14334 `(string-match ,(substring kwd 1 -1) todo)
14335 (list 'equal 'todo kwd))
14336 mm (if minus (list 'not mm) mm))
14337 (push mm todomatcher))
14338 (push (if (> (length todomatcher) 1)
14339 (cons 'and todomatcher)
14340 (car todomatcher))
14341 orlist)
14342 (setq todomatcher nil))
14343 (setq todomatcher (if (> (length orlist) 1)
14344 (cons 'or orlist) (car orlist))))
14346 ;; Return the string and lisp forms of the matcher
14347 (setq matcher (if todomatcher
14348 (list 'and tagsmatcher todomatcher)
14349 tagsmatcher))
14350 (cons match0 matcher)))
14352 (defun org-match-any-p (re list)
14353 "Does re match any element of list?"
14354 (setq list (mapcar (lambda (x) (string-match re x)) list))
14355 (delq nil list))
14357 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14358 (defvar org-tags-overlay (org-make-overlay 1 1))
14359 (org-detach-overlay org-tags-overlay)
14361 (defun org-align-tags-here (to-col)
14362 ;; Assumes that this is a headline
14363 (let ((pos (point)) (col (current-column)) tags)
14364 (beginning-of-line 1)
14365 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14366 (< pos (match-beginning 2)))
14367 (progn
14368 (setq tags (match-string 2))
14369 (goto-char (match-beginning 1))
14370 (insert " ")
14371 (delete-region (point) (1+ (match-end 0)))
14372 (backward-char 1)
14373 (move-to-column
14374 (max (1+ (current-column))
14375 (1+ col)
14376 (if (> to-col 0)
14377 to-col
14378 (- (abs to-col) (length tags))))
14380 (insert tags)
14381 (move-to-column (min (current-column) col) t))
14382 (goto-char pos))))
14384 (defun org-set-tags (&optional arg just-align)
14385 "Set the tags for the current headline.
14386 With prefix ARG, realign all tags in headings in the current buffer."
14387 (interactive "P")
14388 (let* ((re (concat "^" outline-regexp))
14389 (current (org-get-tags-string))
14390 (col (current-column))
14391 (org-setting-tags t)
14392 table current-tags inherited-tags ; computed below when needed
14393 tags p0 c0 c1 rpl)
14394 (if arg
14395 (save-excursion
14396 (goto-char (point-min))
14397 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14398 (while (re-search-forward re nil t)
14399 (org-set-tags nil t)
14400 (end-of-line 1)))
14401 (message "All tags realigned to column %d" org-tags-column))
14402 (if just-align
14403 (setq tags current)
14404 ;; Get a new set of tags from the user
14405 (save-excursion
14406 (setq table (or org-tag-alist (org-get-buffer-tags))
14407 org-last-tags-completion-table table
14408 current-tags (org-split-string current ":")
14409 inherited-tags (nreverse
14410 (nthcdr (length current-tags)
14411 (nreverse (org-get-tags-at))))
14412 tags
14413 (if (or (eq t org-use-fast-tag-selection)
14414 (and org-use-fast-tag-selection
14415 (delq nil (mapcar 'cdr table))))
14416 (org-fast-tag-selection
14417 current-tags inherited-tags table
14418 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14419 (let ((org-add-colon-after-tag-completion t))
14420 (org-trim
14421 (org-without-partial-completion
14422 (completing-read "Tags: " 'org-tags-completion-function
14423 nil nil current 'org-tags-history)))))))
14424 (while (string-match "[-+&]+" tags)
14425 ;; No boolean logic, just a list
14426 (setq tags (replace-match ":" t t tags))))
14428 (if (string-match "\\`[\t ]*\\'" tags)
14429 (setq tags "")
14430 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14431 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14433 ;; Insert new tags at the correct column
14434 (beginning-of-line 1)
14435 (cond
14436 ((and (equal current "") (equal tags "")))
14437 ((re-search-forward
14438 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14439 (point-at-eol) t)
14440 (if (equal tags "")
14441 (setq rpl "")
14442 (goto-char (match-beginning 0))
14443 (setq c0 (current-column) p0 (point)
14444 c1 (max (1+ c0) (if (> org-tags-column 0)
14445 org-tags-column
14446 (- (- org-tags-column) (length tags))))
14447 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14448 (replace-match rpl t t)
14449 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14450 tags)
14451 (t (error "Tags alignment failed")))
14452 (move-to-column col)
14453 (unless just-align
14454 (run-hooks 'org-after-tags-change-hook)))))
14456 (defun org-change-tag-in-region (beg end tag off)
14457 "Add or remove TAG for each entry in the region.
14458 This works in the agenda, and also in an org-mode buffer."
14459 (interactive
14460 (list (region-beginning) (region-end)
14461 (let ((org-last-tags-completion-table
14462 (if (org-mode-p)
14463 (org-get-buffer-tags)
14464 (org-global-tags-completion-table))))
14465 (completing-read
14466 "Tag: " 'org-tags-completion-function nil nil nil
14467 'org-tags-history))
14468 (progn
14469 (message "[s]et or [r]emove? ")
14470 (equal (read-char-exclusive) ?r))))
14471 (if (fboundp 'deactivate-mark) (deactivate-mark))
14472 (let ((agendap (equal major-mode 'org-agenda-mode))
14473 l1 l2 m buf pos newhead (cnt 0))
14474 (goto-char end)
14475 (setq l2 (1- (org-current-line)))
14476 (goto-char beg)
14477 (setq l1 (org-current-line))
14478 (loop for l from l1 to l2 do
14479 (goto-line l)
14480 (setq m (get-text-property (point) 'org-hd-marker))
14481 (when (or (and (org-mode-p) (org-on-heading-p))
14482 (and agendap m))
14483 (setq buf (if agendap (marker-buffer m) (current-buffer))
14484 pos (if agendap m (point)))
14485 (with-current-buffer buf
14486 (save-excursion
14487 (save-restriction
14488 (goto-char pos)
14489 (setq cnt (1+ cnt))
14490 (org-toggle-tag tag (if off 'off 'on))
14491 (setq newhead (org-get-heading)))))
14492 (and agendap (org-agenda-change-all-lines newhead m))))
14493 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14495 (defun org-tags-completion-function (string predicate &optional flag)
14496 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14497 (confirm (lambda (x) (stringp (car x)))))
14498 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14499 (setq s1 (match-string 1 string)
14500 s2 (match-string 2 string))
14501 (setq s1 "" s2 string))
14502 (cond
14503 ((eq flag nil)
14504 ;; try completion
14505 (setq rtn (try-completion s2 ctable confirm))
14506 (if (stringp rtn)
14507 (setq rtn
14508 (concat s1 s2 (substring rtn (length s2))
14509 (if (and org-add-colon-after-tag-completion
14510 (assoc rtn ctable))
14511 ":" ""))))
14512 rtn)
14513 ((eq flag t)
14514 ;; all-completions
14515 (all-completions s2 ctable confirm)
14517 ((eq flag 'lambda)
14518 ;; exact match?
14519 (assoc s2 ctable)))
14522 (defun org-fast-tag-insert (kwd tags face &optional end)
14523 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14524 (insert (format "%-12s" (concat kwd ":"))
14525 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14526 (or end "")))
14528 (defun org-fast-tag-show-exit (flag)
14529 (save-excursion
14530 (goto-line 3)
14531 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14532 (replace-match ""))
14533 (when flag
14534 (end-of-line 1)
14535 (move-to-column (- (window-width) 19) t)
14536 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14538 (defun org-set-current-tags-overlay (current prefix)
14539 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14540 (if (featurep 'xemacs)
14541 (org-overlay-display org-tags-overlay (concat prefix s)
14542 'secondary-selection)
14543 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14544 (org-overlay-display org-tags-overlay (concat prefix s)))))
14546 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14547 "Fast tag selection with single keys.
14548 CURRENT is the current list of tags in the headline, INHERITED is the
14549 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14550 possibly with grouping information. TODO-TABLE is a similar table with
14551 TODO keywords, should these have keys assigned to them.
14552 If the keys are nil, a-z are automatically assigned.
14553 Returns the new tags string, or nil to not change the current settings."
14554 (let* ((fulltable (append table todo-table))
14555 (maxlen (apply 'max (mapcar
14556 (lambda (x)
14557 (if (stringp (car x)) (string-width (car x)) 0))
14558 fulltable)))
14559 (buf (current-buffer))
14560 (expert (eq org-fast-tag-selection-single-key 'expert))
14561 (buffer-tags nil)
14562 (fwidth (+ maxlen 3 1 3))
14563 (ncol (/ (- (window-width) 4) fwidth))
14564 (i-face 'org-done)
14565 (c-face 'org-todo)
14566 tg cnt e c char c1 c2 ntable tbl rtn
14567 ov-start ov-end ov-prefix
14568 (exit-after-next org-fast-tag-selection-single-key)
14569 (done-keywords org-done-keywords)
14570 groups ingroup)
14571 (save-excursion
14572 (beginning-of-line 1)
14573 (if (looking-at
14574 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14575 (setq ov-start (match-beginning 1)
14576 ov-end (match-end 1)
14577 ov-prefix "")
14578 (setq ov-start (1- (point-at-eol))
14579 ov-end (1+ ov-start))
14580 (skip-chars-forward "^\n\r")
14581 (setq ov-prefix
14582 (concat
14583 (buffer-substring (1- (point)) (point))
14584 (if (> (current-column) org-tags-column)
14586 (make-string (- org-tags-column (current-column)) ?\ ))))))
14587 (org-move-overlay org-tags-overlay ov-start ov-end)
14588 (save-window-excursion
14589 (if expert
14590 (set-buffer (get-buffer-create " *Org tags*"))
14591 (delete-other-windows)
14592 (split-window-vertically)
14593 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14594 (erase-buffer)
14595 (org-set-local 'org-done-keywords done-keywords)
14596 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14597 (org-fast-tag-insert "Current" current c-face "\n\n")
14598 (org-fast-tag-show-exit exit-after-next)
14599 (org-set-current-tags-overlay current ov-prefix)
14600 (setq tbl fulltable char ?a cnt 0)
14601 (while (setq e (pop tbl))
14602 (cond
14603 ((equal e '(:startgroup))
14604 (push '() groups) (setq ingroup t)
14605 (when (not (= cnt 0))
14606 (setq cnt 0)
14607 (insert "\n"))
14608 (insert "{ "))
14609 ((equal e '(:endgroup))
14610 (setq ingroup nil cnt 0)
14611 (insert "}\n"))
14613 (setq tg (car e) c2 nil)
14614 (if (cdr e)
14615 (setq c (cdr e))
14616 ;; automatically assign a character.
14617 (setq c1 (string-to-char
14618 (downcase (substring
14619 tg (if (= (string-to-char tg) ?@) 1 0)))))
14620 (if (or (rassoc c1 ntable) (rassoc c1 table))
14621 (while (or (rassoc char ntable) (rassoc char table))
14622 (setq char (1+ char)))
14623 (setq c2 c1))
14624 (setq c (or c2 char)))
14625 (if ingroup (push tg (car groups)))
14626 (setq tg (org-add-props tg nil 'face
14627 (cond
14628 ((not (assoc tg table))
14629 (org-get-todo-face tg))
14630 ((member tg current) c-face)
14631 ((member tg inherited) i-face)
14632 (t nil))))
14633 (if (and (= cnt 0) (not ingroup)) (insert " "))
14634 (insert "[" c "] " tg (make-string
14635 (- fwidth 4 (length tg)) ?\ ))
14636 (push (cons tg c) ntable)
14637 (when (= (setq cnt (1+ cnt)) ncol)
14638 (insert "\n")
14639 (if ingroup (insert " "))
14640 (setq cnt 0)))))
14641 (setq ntable (nreverse ntable))
14642 (insert "\n")
14643 (goto-char (point-min))
14644 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14645 (fit-window-to-buffer))
14646 (setq rtn
14647 (catch 'exit
14648 (while t
14649 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14650 (if groups " [!] no groups" " [!]groups")
14651 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14652 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14653 (cond
14654 ((= c ?\r) (throw 'exit t))
14655 ((= c ?!)
14656 (setq groups (not groups))
14657 (goto-char (point-min))
14658 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14659 ((= c ?\C-c)
14660 (if (not expert)
14661 (org-fast-tag-show-exit
14662 (setq exit-after-next (not exit-after-next)))
14663 (setq expert nil)
14664 (delete-other-windows)
14665 (split-window-vertically)
14666 (org-switch-to-buffer-other-window " *Org tags*")
14667 (and (fboundp 'fit-window-to-buffer)
14668 (fit-window-to-buffer))))
14669 ((or (= c ?\C-g)
14670 (and (= c ?q) (not (rassoc c ntable))))
14671 (org-detach-overlay org-tags-overlay)
14672 (setq quit-flag t))
14673 ((= c ?\ )
14674 (setq current nil)
14675 (if exit-after-next (setq exit-after-next 'now)))
14676 ((= c ?\t)
14677 (condition-case nil
14678 (setq tg (completing-read
14679 "Tag: "
14680 (or buffer-tags
14681 (with-current-buffer buf
14682 (org-get-buffer-tags)))))
14683 (quit (setq tg "")))
14684 (when (string-match "\\S-" tg)
14685 (add-to-list 'buffer-tags (list tg))
14686 (if (member tg current)
14687 (setq current (delete tg current))
14688 (push tg current)))
14689 (if exit-after-next (setq exit-after-next 'now)))
14690 ((setq e (rassoc c todo-table) tg (car e))
14691 (with-current-buffer buf
14692 (save-excursion (org-todo tg)))
14693 (if exit-after-next (setq exit-after-next 'now)))
14694 ((setq e (rassoc c ntable) tg (car e))
14695 (if (member tg current)
14696 (setq current (delete tg current))
14697 (loop for g in groups do
14698 (if (member tg g)
14699 (mapc (lambda (x)
14700 (setq current (delete x current)))
14701 g)))
14702 (push tg current))
14703 (if exit-after-next (setq exit-after-next 'now))))
14705 ;; Create a sorted list
14706 (setq current
14707 (sort current
14708 (lambda (a b)
14709 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14710 (if (eq exit-after-next 'now) (throw 'exit t))
14711 (goto-char (point-min))
14712 (beginning-of-line 2)
14713 (delete-region (point) (point-at-eol))
14714 (org-fast-tag-insert "Current" current c-face)
14715 (org-set-current-tags-overlay current ov-prefix)
14716 (while (re-search-forward
14717 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14718 (setq tg (match-string 1))
14719 (add-text-properties
14720 (match-beginning 1) (match-end 1)
14721 (list 'face
14722 (cond
14723 ((member tg current) c-face)
14724 ((member tg inherited) i-face)
14725 (t (get-text-property (match-beginning 1) 'face))))))
14726 (goto-char (point-min)))))
14727 (org-detach-overlay org-tags-overlay)
14728 (if rtn
14729 (mapconcat 'identity current ":")
14730 nil))))
14732 (defun org-get-tags-string ()
14733 "Get the TAGS string in the current headline."
14734 (unless (org-on-heading-p t)
14735 (error "Not on a heading"))
14736 (save-excursion
14737 (beginning-of-line 1)
14738 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14739 (org-match-string-no-properties 1)
14740 "")))
14742 (defun org-get-tags ()
14743 "Get the list of tags specified in the current headline."
14744 (org-split-string (org-get-tags-string) ":"))
14746 (defun org-get-buffer-tags ()
14747 "Get a table of all tags used in the buffer, for completion."
14748 (let (tags)
14749 (save-excursion
14750 (goto-char (point-min))
14751 (while (re-search-forward
14752 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
14753 (when (equal (char-after (point-at-bol 0)) ?*)
14754 (mapc (lambda (x) (add-to-list 'tags x))
14755 (org-split-string (org-match-string-no-properties 1) ":")))))
14756 (mapcar 'list tags)))
14759 ;;;; Properties
14761 ;;; Setting and retrieving properties
14763 (defconst org-special-properties
14764 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY")
14765 "The special properties valid in Org-mode.
14767 These are properties that are not defined in the property drawer,
14768 but in some other way.")
14770 (defconst org-default-properties
14771 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
14772 "LOCATION" "LOGGING" "COLUMNS")
14773 "Some properties that are used by Org-mode for various purposes.
14774 Being in this list makes sure that they are offered for completion.")
14776 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
14777 "Regular expression matching the first line of a property drawer.")
14779 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
14780 "Regular expression matching the first line of a property drawer.")
14782 (defun org-property-action ()
14783 "Do an action on properties."
14784 (interactive)
14785 (let (c)
14786 (org-at-property-p)
14787 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
14788 (setq c (read-char-exclusive))
14789 (cond
14790 ((equal c ?s)
14791 (call-interactively 'org-set-property))
14792 ((equal c ?d)
14793 (call-interactively 'org-delete-property))
14794 ((equal c ?D)
14795 (call-interactively 'org-delete-property-globally))
14796 ((equal c ?c)
14797 (call-interactively 'org-compute-property-at-point))
14798 (t (error "No such property action %c" c)))))
14800 (defun org-at-property-p ()
14801 "Is the cursor in a property line?"
14802 ;; FIXME: Does not check if we are actually in the drawer.
14803 ;; FIXME: also returns true on any drawers.....
14804 ;; This is used by C-c C-c for property action.
14805 (save-excursion
14806 (beginning-of-line 1)
14807 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
14809 (defmacro org-with-point-at (pom &rest body)
14810 "Move to buffer and point of point-or-marker POM for the duration of BODY."
14811 (declare (indent 1) (debug t))
14812 `(save-excursion
14813 (if (markerp pom) (set-buffer (marker-buffer pom)))
14814 (save-excursion
14815 (goto-char (or pom (point)))
14816 ,@body)))
14818 (defun org-get-property-block (&optional beg end force)
14819 "Return the (beg . end) range of the body of the property drawer.
14820 BEG and END can be beginning and end of subtree, if not given
14821 they will be found.
14822 If the drawer does not exist and FORCE is non-nil, create the drawer."
14823 (catch 'exit
14824 (save-excursion
14825 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
14826 (end (or end (progn (outline-next-heading) (point)))))
14827 (goto-char beg)
14828 (if (re-search-forward org-property-start-re end t)
14829 (setq beg (1+ (match-end 0)))
14830 (if force
14831 (save-excursion
14832 (org-insert-property-drawer)
14833 (setq end (progn (outline-next-heading) (point))))
14834 (throw 'exit nil))
14835 (goto-char beg)
14836 (if (re-search-forward org-property-start-re end t)
14837 (setq beg (1+ (match-end 0)))))
14838 (if (re-search-forward org-property-end-re end t)
14839 (setq end (match-beginning 0))
14840 (or force (throw 'exit nil))
14841 (goto-char beg)
14842 (setq end beg)
14843 (org-indent-line-function)
14844 (insert ":END:\n"))
14845 (cons beg end)))))
14847 (defun org-entry-properties (&optional pom which)
14848 "Get all properties of the entry at point-or-marker POM.
14849 This includes the TODO keyword, the tags, time strings for deadline,
14850 scheduled, and clocking, and any additional properties defined in the
14851 entry. The return value is an alist, keys may occur multiple times
14852 if the property key was used several times.
14853 POM may also be nil, in which case the current entry is used.
14854 If WHICH is nil or `all', get all properties. If WHICH is
14855 `special' or `standard', only get that subclass."
14856 (setq which (or which 'all))
14857 (org-with-point-at pom
14858 (let ((clockstr (substring org-clock-string 0 -1))
14859 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
14860 beg end range props sum-props key value)
14861 (save-excursion
14862 (when (condition-case nil (org-back-to-heading t) (error nil))
14863 (setq beg (point))
14864 (setq sum-props (get-text-property (point) 'org-summaries))
14865 (outline-next-heading)
14866 (setq end (point))
14867 (when (memq which '(all special))
14868 ;; Get the special properties, like TODO and tags
14869 (goto-char beg)
14870 (when (and (looking-at org-todo-line-regexp) (match-end 2))
14871 (push (cons "TODO" (org-match-string-no-properties 2)) props))
14872 (when (looking-at org-priority-regexp)
14873 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
14874 (when (and (setq value (org-get-tags-string))
14875 (string-match "\\S-" value))
14876 (push (cons "TAGS" value) props))
14877 (when (setq value (org-get-tags-at))
14878 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
14879 props))
14880 (while (re-search-forward org-keyword-time-regexp end t)
14881 (setq key (substring (org-match-string-no-properties 1) 0 -1))
14882 (unless (member key excluded) (push key excluded))
14883 (push (cons key
14884 (if (equal key clockstr)
14885 (org-no-properties
14886 (org-trim
14887 (buffer-substring
14888 (match-beginning 2) (point-at-eol))))
14889 (org-match-string-no-properties 2)))
14890 props)))
14891 (when (memq which '(all standard))
14892 ;; Get the standard properties, like :PORP: ...
14893 (setq range (org-get-property-block beg end))
14894 (when range
14895 (goto-char (car range))
14896 (while (re-search-forward
14897 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
14898 (cdr range) t)
14899 (setq key (org-match-string-no-properties 1)
14900 value (org-trim (or (org-match-string-no-properties 2) "")))
14901 (unless (member key excluded)
14902 (push (cons key (or value "")) props)))))
14903 (append sum-props (nreverse props)))))))
14905 (defun org-entry-get (pom property &optional inherit)
14906 "Get value of PROPERTY for entry at point-or-marker POM.
14907 If INHERIT is non-nil and the entry does not have the property,
14908 then also check higher levels of the hierarchy.
14909 If the property is present but empty, the return value is the empty string.
14910 If the property is not present at all, nil is returned."
14911 (org-with-point-at pom
14912 (if inherit
14913 (org-entry-get-with-inheritance property)
14914 (if (member property org-special-properties)
14915 ;; We need a special property. Use brute force, get all properties.
14916 (cdr (assoc property (org-entry-properties nil 'special)))
14917 (let ((range (org-get-property-block)))
14918 (if (and range
14919 (goto-char (car range))
14920 (re-search-forward
14921 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
14922 (cdr range) t))
14923 ;; Found the property, return it.
14924 (if (match-end 1)
14925 (org-match-string-no-properties 1)
14926 "")))))))
14928 (defun org-entry-delete (pom property)
14929 "Delete the property PROPERTY from entry at point-or-marker POM."
14930 (org-with-point-at pom
14931 (if (member property org-special-properties)
14932 nil ; cannot delete these properties.
14933 (let ((range (org-get-property-block)))
14934 (if (and range
14935 (goto-char (car range))
14936 (re-search-forward
14937 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
14938 (cdr range) t))
14939 (progn
14940 (delete-region (match-beginning 0) (1+ (point-at-eol)))
14942 nil)))))
14944 ;; Multi-values properties are properties that contain multiple values
14945 ;; These values are assumed to be single words, separated by whitespace.
14946 (defun org-entry-add-to-multivalued-property (pom property value)
14947 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
14948 (let* ((old (org-entry-get pom property))
14949 (values (and old (org-split-string old "[ \t]"))))
14950 (unless (member value values)
14951 (setq values (cons value values))
14952 (org-entry-put pom property
14953 (mapconcat 'identity values " ")))))
14955 (defun org-entry-remove-from-multivalued-property (pom property value)
14956 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
14957 (let* ((old (org-entry-get pom property))
14958 (values (and old (org-split-string old "[ \t]"))))
14959 (when (member value values)
14960 (setq values (delete value values))
14961 (org-entry-put pom property
14962 (mapconcat 'identity values " ")))))
14964 (defun org-entry-member-in-multivalued-property (pom property value)
14965 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
14966 (let* ((old (org-entry-get pom property))
14967 (values (and old (org-split-string old "[ \t]"))))
14968 (member value values)))
14970 (defvar org-entry-property-inherited-from (make-marker))
14972 (defun org-entry-get-with-inheritance (property)
14973 "Get entry property, and search higher levels if not present."
14974 (let (tmp)
14975 (save-excursion
14976 (save-restriction
14977 (widen)
14978 (catch 'ex
14979 (while t
14980 (when (setq tmp (org-entry-get nil property))
14981 (org-back-to-heading t)
14982 (move-marker org-entry-property-inherited-from (point))
14983 (throw 'ex tmp))
14984 (or (org-up-heading-safe) (throw 'ex nil)))))
14985 (or tmp (cdr (assoc property org-local-properties))
14986 (cdr (assoc property org-global-properties))))))
14988 (defun org-entry-put (pom property value)
14989 "Set PROPERTY to VALUE for entry at point-or-marker POM."
14990 (org-with-point-at pom
14991 (org-back-to-heading t)
14992 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
14993 range)
14994 (cond
14995 ((equal property "TODO")
14996 (when (and (stringp value) (string-match "\\S-" value)
14997 (not (member value org-todo-keywords-1)))
14998 (error "\"%s\" is not a valid TODO state" value))
14999 (if (or (not value)
15000 (not (string-match "\\S-" value)))
15001 (setq value 'none))
15002 (org-todo value)
15003 (org-set-tags nil 'align))
15004 ((equal property "PRIORITY")
15005 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15006 (string-to-char value) ?\ ))
15007 (org-set-tags nil 'align))
15008 ((equal property "SCHEDULED")
15009 (if (re-search-forward org-scheduled-time-regexp end t)
15010 (cond
15011 ((eq value 'earlier) (org-timestamp-change -1 'day))
15012 ((eq value 'later) (org-timestamp-change 1 'day))
15013 (t (call-interactively 'org-schedule)))
15014 (call-interactively 'org-schedule)))
15015 ((equal property "DEADLINE")
15016 (if (re-search-forward org-deadline-time-regexp end t)
15017 (cond
15018 ((eq value 'earlier) (org-timestamp-change -1 'day))
15019 ((eq value 'later) (org-timestamp-change 1 'day))
15020 (t (call-interactively 'org-deadline)))
15021 (call-interactively 'org-deadline)))
15022 ((member property org-special-properties)
15023 (error "The %s property can not yet be set with `org-entry-put'"
15024 property))
15025 (t ; a non-special property
15026 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15027 (setq range (org-get-property-block beg end 'force))
15028 (goto-char (car range))
15029 (if (re-search-forward
15030 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15031 (progn
15032 (delete-region (match-beginning 1) (match-end 1))
15033 (goto-char (match-beginning 1)))
15034 (goto-char (cdr range))
15035 (insert "\n")
15036 (backward-char 1)
15037 (org-indent-line-function)
15038 (insert ":" property ":"))
15039 (and value (insert " " value))
15040 (org-indent-line-function)))))))
15042 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15043 "Get all property keys in the current buffer.
15044 With INCLUDE-SPECIALS, also list the special properties that relect things
15045 like tags and TODO state.
15046 With INCLUDE-DEFAULTS, also include properties that has special meaning
15047 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15048 (let (rtn range)
15049 (save-excursion
15050 (save-restriction
15051 (widen)
15052 (goto-char (point-min))
15053 (while (re-search-forward org-property-start-re nil t)
15054 (setq range (org-get-property-block))
15055 (goto-char (car range))
15056 (while (re-search-forward
15057 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15058 (cdr range) t)
15059 (add-to-list 'rtn (org-match-string-no-properties 1)))
15060 (outline-next-heading))))
15062 (when include-specials
15063 (setq rtn (append org-special-properties rtn)))
15065 (when include-defaults
15066 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15068 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15070 (defun org-property-values (key)
15071 "Return a list of all values of property KEY."
15072 (save-excursion
15073 (save-restriction
15074 (widen)
15075 (goto-char (point-min))
15076 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15077 values)
15078 (while (re-search-forward re nil t)
15079 (add-to-list 'values (org-trim (match-string 1))))
15080 (delete "" values)))))
15082 (defun org-insert-property-drawer ()
15083 "Insert a property drawer into the current entry."
15084 (interactive)
15085 (org-back-to-heading t)
15086 (looking-at outline-regexp)
15087 (let ((indent (- (match-end 0)(match-beginning 0)))
15088 (beg (point))
15089 (re (concat "^[ \t]*" org-keyword-time-regexp))
15090 end hiddenp)
15091 (outline-next-heading)
15092 (setq end (point))
15093 (goto-char beg)
15094 (while (re-search-forward re end t))
15095 (setq hiddenp (org-invisible-p))
15096 (end-of-line 1)
15097 (and (equal (char-after) ?\n) (forward-char 1))
15098 (org-skip-over-state-notes)
15099 (skip-chars-backward " \t\n\r")
15100 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15101 (beginning-of-line 0)
15102 (indent-to-column indent)
15103 (beginning-of-line 2)
15104 (indent-to-column indent)
15105 (beginning-of-line 0)
15106 (if hiddenp
15107 (save-excursion
15108 (org-back-to-heading t)
15109 (hide-entry))
15110 (org-flag-drawer t))))
15112 (defun org-set-property (property value)
15113 "In the current entry, set PROPERTY to VALUE.
15114 When called interactively, this will prompt for a property name, offering
15115 completion on existing and default properties. And then it will prompt
15116 for a value, offering competion either on allowed values (via an inherited
15117 xxx_ALL property) or on existing values in other instances of this property
15118 in the current file."
15119 (interactive
15120 (let* ((prop (completing-read
15121 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15122 (cur (org-entry-get nil prop))
15123 (allowed (org-property-get-allowed-values nil prop 'table))
15124 (existing (mapcar 'list (org-property-values prop)))
15125 (val (if allowed
15126 (completing-read "Value: " allowed nil 'req-match)
15127 (completing-read
15128 (concat "Value" (if (and cur (string-match "\\S-" cur))
15129 (concat "[" cur "]") "")
15130 ": ")
15131 existing nil nil "" nil cur))))
15132 (list prop (if (equal val "") cur val))))
15133 (unless (equal (org-entry-get nil property) value)
15134 (org-entry-put nil property value)))
15136 (defun org-delete-property (property)
15137 "In the current entry, delete PROPERTY."
15138 (interactive
15139 (let* ((prop (completing-read
15140 "Property: " (org-entry-properties nil 'standard))))
15141 (list prop)))
15142 (message (concat "Property " property
15143 (if (org-entry-delete nil property)
15144 " deleted"
15145 " was not present in the entry"))))
15147 (defun org-delete-property-globally (property)
15148 "Remove PROPERTY globally, from all entries."
15149 (interactive
15150 (let* ((prop (completing-read
15151 "Globally remove property: "
15152 (mapcar 'list (org-buffer-property-keys)))))
15153 (list prop)))
15154 (save-excursion
15155 (save-restriction
15156 (widen)
15157 (goto-char (point-min))
15158 (let ((cnt 0))
15159 (while (re-search-forward
15160 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15161 nil t)
15162 (setq cnt (1+ cnt))
15163 (replace-match ""))
15164 (message "Property \"%s\" removed from %d entries" property cnt)))))
15166 (defvar org-columns-current-fmt-compiled) ; defined below
15168 (defun org-compute-property-at-point ()
15169 "Compute the property at point.
15170 This looks for an enclosing column format, extracts the operator and
15171 then applies it to the proerty in the column format's scope."
15172 (interactive)
15173 (unless (org-at-property-p)
15174 (error "Not at a property"))
15175 (let ((prop (org-match-string-no-properties 2)))
15176 (org-columns-get-format-and-top-level)
15177 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15178 (error "No operator defined for property %s" prop))
15179 (org-columns-compute prop)))
15181 (defun org-property-get-allowed-values (pom property &optional table)
15182 "Get allowed values for the property PROPERTY.
15183 When TABLE is non-nil, return an alist that can directly be used for
15184 completion."
15185 (let (vals)
15186 (cond
15187 ((equal property "TODO")
15188 (setq vals (org-with-point-at pom
15189 (append org-todo-keywords-1 '("")))))
15190 ((equal property "PRIORITY")
15191 (let ((n org-lowest-priority))
15192 (while (>= n org-highest-priority)
15193 (push (char-to-string n) vals)
15194 (setq n (1- n)))))
15195 ((member property org-special-properties))
15197 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15199 (when (and vals (string-match "\\S-" vals))
15200 (setq vals (car (read-from-string (concat "(" vals ")"))))
15201 (setq vals (mapcar (lambda (x)
15202 (cond ((stringp x) x)
15203 ((numberp x) (number-to-string x))
15204 ((symbolp x) (symbol-name x))
15205 (t "???")))
15206 vals)))))
15207 (if table (mapcar 'list vals) vals)))
15209 (defun org-property-previous-allowed-value (&optional previous)
15210 "Switch to the next allowed value for this property."
15211 (interactive)
15212 (org-property-next-allowed-value t))
15214 (defun org-property-next-allowed-value (&optional previous)
15215 "Switch to the next allowed value for this property."
15216 (interactive)
15217 (unless (org-at-property-p)
15218 (error "Not at a property"))
15219 (let* ((key (match-string 2))
15220 (value (match-string 3))
15221 (allowed (or (org-property-get-allowed-values (point) key)
15222 (and (member value '("[ ]" "[-]" "[X]"))
15223 '("[ ]" "[X]"))))
15224 nval)
15225 (unless allowed
15226 (error "Allowed values for this property have not been defined"))
15227 (if previous (setq allowed (reverse allowed)))
15228 (if (member value allowed)
15229 (setq nval (car (cdr (member value allowed)))))
15230 (setq nval (or nval (car allowed)))
15231 (if (equal nval value)
15232 (error "Only one allowed value for this property"))
15233 (org-at-property-p)
15234 (replace-match (concat " :" key ": " nval) t t)
15235 (org-indent-line-function)
15236 (beginning-of-line 1)
15237 (skip-chars-forward " \t")))
15239 (defun org-find-entry-with-id (ident)
15240 "Locate the entry that contains the ID property with exact value IDENT.
15241 IDENT can be a string, a symbol or a number, this function will search for
15242 the string representation of it.
15243 Return the position where this entry starts, or nil if there is no such entry."
15244 (let ((id (cond
15245 ((stringp ident) ident)
15246 ((symbol-name ident) (symbol-name ident))
15247 ((numberp ident) (number-to-string ident))
15248 (t (error "IDENT %s must be a string, symbol or number" ident))))
15249 (case-fold-search nil))
15250 (save-excursion
15251 (save-restriction
15252 (goto-char (point-min))
15253 (when (re-search-forward
15254 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15255 nil t)
15256 (org-back-to-heading)
15257 (point))))))
15259 ;;; Column View
15261 (defvar org-columns-overlays nil
15262 "Holds the list of current column overlays.")
15264 (defvar org-columns-current-fmt nil
15265 "Local variable, holds the currently active column format.")
15266 (defvar org-columns-current-fmt-compiled nil
15267 "Local variable, holds the currently active column format.
15268 This is the compiled version of the format.")
15269 (defvar org-columns-current-widths nil
15270 "Loval variable, holds the currently widths of fields.")
15271 (defvar org-columns-current-maxwidths nil
15272 "Loval variable, holds the currently active maximum column widths.")
15273 (defvar org-columns-begin-marker (make-marker)
15274 "Points to the position where last a column creation command was called.")
15275 (defvar org-columns-top-level-marker (make-marker)
15276 "Points to the position where current columns region starts.")
15278 (defvar org-columns-map (make-sparse-keymap)
15279 "The keymap valid in column display.")
15281 (defun org-columns-content ()
15282 "Switch to contents view while in columns view."
15283 (interactive)
15284 (org-overview)
15285 (org-content))
15287 (org-defkey org-columns-map "c" 'org-columns-content)
15288 (org-defkey org-columns-map "o" 'org-overview)
15289 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15290 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15291 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15292 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15293 (org-defkey org-columns-map "v" 'org-columns-show-value)
15294 (org-defkey org-columns-map "q" 'org-columns-quit)
15295 (org-defkey org-columns-map "r" 'org-columns-redo)
15296 (org-defkey org-columns-map [left] 'backward-char)
15297 (org-defkey org-columns-map "\M-b" 'backward-char)
15298 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15299 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15300 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15301 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15302 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15303 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15304 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15305 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15306 (org-defkey org-columns-map "<" 'org-columns-narrow)
15307 (org-defkey org-columns-map ">" 'org-columns-widen)
15308 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15309 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15310 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15311 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15313 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15314 '("Column"
15315 ["Edit property" org-columns-edit-value t]
15316 ["Next allowed value" org-columns-next-allowed-value t]
15317 ["Previous allowed value" org-columns-previous-allowed-value t]
15318 ["Show full value" org-columns-show-value t]
15319 ["Edit allowed values" org-columns-edit-allowed t]
15320 "--"
15321 ["Edit column attributes" org-columns-edit-attributes t]
15322 ["Increase column width" org-columns-widen t]
15323 ["Decrease column width" org-columns-narrow t]
15324 "--"
15325 ["Move column right" org-columns-move-right t]
15326 ["Move column left" org-columns-move-left t]
15327 ["Add column" org-columns-new t]
15328 ["Delete column" org-columns-delete t]
15329 "--"
15330 ["CONTENTS" org-columns-content t]
15331 ["OVERVIEW" org-overview t]
15332 ["Refresh columns display" org-columns-redo t]
15333 "--"
15334 ["Open link" org-columns-open-link t]
15335 "--"
15336 ["Quit" org-columns-quit t]))
15338 (defun org-columns-new-overlay (beg end &optional string face)
15339 "Create a new column overlay and add it to the list."
15340 (let ((ov (org-make-overlay beg end)))
15341 (org-overlay-put ov 'face (or face 'secondary-selection))
15342 (org-overlay-display ov string face)
15343 (push ov org-columns-overlays)
15344 ov))
15346 (defun org-columns-display-here (&optional props)
15347 "Overlay the current line with column display."
15348 (interactive)
15349 (let* ((fmt org-columns-current-fmt-compiled)
15350 (beg (point-at-bol))
15351 (level-face (save-excursion
15352 (beginning-of-line 1)
15353 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15354 (org-get-level-face 2))))
15355 (color (list :foreground
15356 (face-attribute (or level-face 'default) :foreground)))
15357 props pom property ass width f string ov column val modval)
15358 ;; Check if the entry is in another buffer.
15359 (unless props
15360 (if (eq major-mode 'org-agenda-mode)
15361 (setq pom (or (get-text-property (point) 'org-hd-marker)
15362 (get-text-property (point) 'org-marker))
15363 props (if pom (org-entry-properties pom) nil))
15364 (setq props (org-entry-properties nil))))
15365 ;; Walk the format
15366 (while (setq column (pop fmt))
15367 (setq property (car column)
15368 ass (if (equal property "ITEM")
15369 (cons "ITEM"
15370 (save-match-data
15371 (org-no-properties
15372 (org-remove-tabs
15373 (buffer-substring-no-properties
15374 (point-at-bol) (point-at-eol))))))
15375 (assoc property props))
15376 width (or (cdr (assoc property org-columns-current-maxwidths))
15377 (nth 2 column)
15378 (length property))
15379 f (format "%%-%d.%ds | " width width)
15380 val (or (cdr ass) "")
15381 modval (if (equal property "ITEM")
15382 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15383 string (format f (or modval val)))
15384 ;; Create the overlay
15385 (org-unmodified
15386 (setq ov (org-columns-new-overlay
15387 beg (setq beg (1+ beg)) string
15388 (list color 'org-column)))
15389 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15390 (org-overlay-put ov 'keymap org-columns-map)
15391 (org-overlay-put ov 'org-columns-key property)
15392 (org-overlay-put ov 'org-columns-value (cdr ass))
15393 (org-overlay-put ov 'org-columns-value-modified modval)
15394 (org-overlay-put ov 'org-columns-pom pom)
15395 (org-overlay-put ov 'org-columns-format f))
15396 (if (or (not (char-after beg))
15397 (equal (char-after beg) ?\n))
15398 (let ((inhibit-read-only t))
15399 (save-excursion
15400 (goto-char beg)
15401 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15402 ;; Make the rest of the line disappear.
15403 (org-unmodified
15404 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15405 (org-overlay-put ov 'invisible t)
15406 (org-overlay-put ov 'keymap org-columns-map)
15407 (org-overlay-put ov 'intangible t)
15408 (push ov org-columns-overlays)
15409 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15410 (org-overlay-put ov 'keymap org-columns-map)
15411 (push ov org-columns-overlays)
15412 (let ((inhibit-read-only t))
15413 (put-text-property (max (point-min) (1- (point-at-bol)))
15414 (min (point-max) (1+ (point-at-eol)))
15415 'read-only "Type `e' to edit property")))))
15417 (defvar org-previous-header-line-format nil
15418 "The header line format before column view was turned on.")
15419 (defvar org-columns-inhibit-recalculation nil
15420 "Inhibit recomputing of columns on column view startup.")
15423 (defvar header-line-format)
15424 (defun org-columns-display-here-title ()
15425 "Overlay the newline before the current line with the table title."
15426 (interactive)
15427 (let ((fmt org-columns-current-fmt-compiled)
15428 string (title "")
15429 property width f column str widths)
15430 (while (setq column (pop fmt))
15431 (setq property (car column)
15432 str (or (nth 1 column) property)
15433 width (or (cdr (assoc property org-columns-current-maxwidths))
15434 (nth 2 column)
15435 (length str))
15436 widths (push width widths)
15437 f (format "%%-%d.%ds | " width width)
15438 string (format f str)
15439 title (concat title string)))
15440 (setq title (concat
15441 (org-add-props " " nil 'display '(space :align-to 0))
15442 (org-add-props title nil 'face '(:weight bold :underline t))))
15443 (org-set-local 'org-previous-header-line-format header-line-format)
15444 (org-set-local 'org-columns-current-widths (nreverse widths))
15445 (setq header-line-format title)))
15447 (defun org-columns-remove-overlays ()
15448 "Remove all currently active column overlays."
15449 (interactive)
15450 (when (marker-buffer org-columns-begin-marker)
15451 (with-current-buffer (marker-buffer org-columns-begin-marker)
15452 (when (local-variable-p 'org-previous-header-line-format)
15453 (setq header-line-format org-previous-header-line-format)
15454 (kill-local-variable 'org-previous-header-line-format))
15455 (move-marker org-columns-begin-marker nil)
15456 (move-marker org-columns-top-level-marker nil)
15457 (org-unmodified
15458 (mapc 'org-delete-overlay org-columns-overlays)
15459 (setq org-columns-overlays nil)
15460 (let ((inhibit-read-only t))
15461 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15463 (defun org-columns-cleanup-item (item fmt)
15464 "Remove from ITEM what is a column in the format FMT."
15465 (if (not org-complex-heading-regexp)
15466 item
15467 (when (string-match org-complex-heading-regexp item)
15468 (concat
15469 (org-add-props (concat (match-string 1 item) " ") nil
15470 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
15471 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
15472 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
15473 " " (match-string 4 item)
15474 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
15476 (defun org-columns-show-value ()
15477 "Show the full value of the property."
15478 (interactive)
15479 (let ((value (get-char-property (point) 'org-columns-value)))
15480 (message "Value is: %s" (or value ""))))
15482 (defun org-columns-quit ()
15483 "Remove the column overlays and in this way exit column editing."
15484 (interactive)
15485 (org-unmodified
15486 (org-columns-remove-overlays)
15487 (let ((inhibit-read-only t))
15488 (remove-text-properties (point-min) (point-max) '(read-only t))))
15489 (when (eq major-mode 'org-agenda-mode)
15490 (message
15491 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15493 (defun org-columns-check-computed ()
15494 "Check if this column value is computed.
15495 If yes, throw an error indicating that changing it does not make sense."
15496 (let ((val (get-char-property (point) 'org-columns-value)))
15497 (when (and (stringp val)
15498 (get-char-property 0 'org-computed val))
15499 (error "This value is computed from the entry's children"))))
15501 (defun org-columns-todo (&optional arg)
15502 "Change the TODO state during column view."
15503 (interactive "P")
15504 (org-columns-edit-value "TODO"))
15506 (defun org-columns-set-tags-or-toggle (&optional arg)
15507 "Toggle checkbox at point, or set tags for current headline."
15508 (interactive "P")
15509 (if (string-match "\\`\\[[ xX-]\\]\\'"
15510 (get-char-property (point) 'org-columns-value))
15511 (org-columns-next-allowed-value)
15512 (org-columns-edit-value "TAGS")))
15514 (defun org-columns-edit-value (&optional key)
15515 "Edit the value of the property at point in column view.
15516 Where possible, use the standard interface for changing this line."
15517 (interactive)
15518 (org-columns-check-computed)
15519 (let* ((external-key key)
15520 (col (current-column))
15521 (key (or key (get-char-property (point) 'org-columns-key)))
15522 (value (get-char-property (point) 'org-columns-value))
15523 (bol (point-at-bol)) (eol (point-at-eol))
15524 (pom (or (get-text-property bol 'org-hd-marker)
15525 (point))) ; keep despite of compiler waring
15526 (line-overlays
15527 (delq nil (mapcar (lambda (x)
15528 (and (eq (overlay-buffer x) (current-buffer))
15529 (>= (overlay-start x) bol)
15530 (<= (overlay-start x) eol)
15532 org-columns-overlays)))
15533 nval eval allowed)
15534 (cond
15535 ((equal key "ITEM")
15536 (setq eval '(org-with-point-at pom
15537 (org-edit-headline))))
15538 ((equal key "TODO")
15539 (setq eval '(org-with-point-at pom
15540 (let ((current-prefix-arg
15541 (if external-key current-prefix-arg '(4))))
15542 (call-interactively 'org-todo)))))
15543 ((equal key "PRIORITY")
15544 (setq eval '(org-with-point-at pom
15545 (call-interactively 'org-priority))))
15546 ((equal key "TAGS")
15547 (setq eval '(org-with-point-at pom
15548 (let ((org-fast-tag-selection-single-key
15549 (if (eq org-fast-tag-selection-single-key 'expert)
15550 t org-fast-tag-selection-single-key)))
15551 (call-interactively 'org-set-tags)))))
15552 ((equal key "DEADLINE")
15553 (setq eval '(org-with-point-at pom
15554 (call-interactively 'org-deadline))))
15555 ((equal key "SCHEDULED")
15556 (setq eval '(org-with-point-at pom
15557 (call-interactively 'org-schedule))))
15559 (setq allowed (org-property-get-allowed-values pom key 'table))
15560 (if allowed
15561 (setq nval (completing-read "Value: " allowed nil t))
15562 (setq nval (read-string "Edit: " value)))
15563 (setq nval (org-trim nval))
15564 (when (not (equal nval value))
15565 (setq eval '(org-entry-put pom key nval)))))
15566 (when eval
15567 (let ((inhibit-read-only t))
15568 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
15569 (unwind-protect
15570 (progn
15571 (setq org-columns-overlays
15572 (org-delete-all line-overlays org-columns-overlays))
15573 (mapc 'org-delete-overlay line-overlays)
15574 (org-columns-eval eval))
15575 (org-columns-display-here))))
15576 (move-to-column col)
15577 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15578 (org-columns-update key))))
15580 (defun org-edit-headline () ; FIXME: this is not columns specific
15581 "Edit the current headline, the part without TODO keyword, TAGS."
15582 (org-back-to-heading)
15583 (when (looking-at org-todo-line-regexp)
15584 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
15585 (txt (match-string 3))
15586 (post "")
15587 txt2)
15588 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
15589 (setq post (match-string 0 txt)
15590 txt (substring txt 0 (match-beginning 0))))
15591 (setq txt2 (read-string "Edit: " txt))
15592 (when (not (equal txt txt2))
15593 (beginning-of-line 1)
15594 (insert pre txt2 post)
15595 (delete-region (point) (point-at-eol))
15596 (org-set-tags nil t)))))
15598 (defun org-columns-edit-allowed ()
15599 "Edit the list of allowed values for the current property."
15600 (interactive)
15601 (let* ((key (get-char-property (point) 'org-columns-key))
15602 (key1 (concat key "_ALL"))
15603 (allowed (org-entry-get (point) key1 t))
15604 nval)
15605 ;; FIXME: Cover editing TODO, TAGS etc inbiffer settings.????
15606 (setq nval (read-string "Allowed: " allowed))
15607 (org-entry-put
15608 (cond ((marker-position org-entry-property-inherited-from)
15609 org-entry-property-inherited-from)
15610 ((marker-position org-columns-top-level-marker)
15611 org-columns-top-level-marker))
15612 key1 nval)))
15614 (defmacro org-no-warnings (&rest body)
15615 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
15617 (defun org-columns-eval (form)
15618 (let (hidep)
15619 (save-excursion
15620 (beginning-of-line 1)
15621 ;; `next-line' is needed here, because it skips invisible line.
15622 ;; FIXME: RMS says this should be wrapped into `with-no-warnings'
15623 ;; but I don't know how to do this and keep the code XEmacs compatible.
15624 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
15625 (setq hidep (org-on-heading-p 1)))
15626 (eval form)
15627 (and hidep (hide-entry))))
15629 (defun org-columns-previous-allowed-value ()
15630 "Switch to the previous allowed value for this column."
15631 (interactive)
15632 (org-columns-next-allowed-value t))
15634 (defun org-columns-next-allowed-value (&optional previous)
15635 "Switch to the next allowed value for this column."
15636 (interactive)
15637 (org-columns-check-computed)
15638 (let* ((col (current-column))
15639 (key (get-char-property (point) 'org-columns-key))
15640 (value (get-char-property (point) 'org-columns-value))
15641 (bol (point-at-bol)) (eol (point-at-eol))
15642 (pom (or (get-text-property bol 'org-hd-marker)
15643 (point))) ; keep despite of compiler waring
15644 (line-overlays
15645 (delq nil (mapcar (lambda (x)
15646 (and (eq (overlay-buffer x) (current-buffer))
15647 (>= (overlay-start x) bol)
15648 (<= (overlay-start x) eol)
15650 org-columns-overlays)))
15651 (allowed (or (org-property-get-allowed-values pom key)
15652 (and (equal
15653 (nth 4 (assoc key org-columns-current-fmt-compiled))
15654 'checkbox) '("[ ]" "[X]"))))
15655 nval)
15656 (when (equal key "ITEM")
15657 (error "Cannot edit item headline from here"))
15658 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15659 (error "Allowed values for this property have not been defined"))
15660 (if (member key '("SCHEDULED" "DEADLINE"))
15661 (setq nval (if previous 'earlier 'later))
15662 (if previous (setq allowed (reverse allowed)))
15663 (if (member value allowed)
15664 (setq nval (car (cdr (member value allowed)))))
15665 (setq nval (or nval (car allowed)))
15666 (if (equal nval value)
15667 (error "Only one allowed value for this property")))
15668 (let ((inhibit-read-only t))
15669 (remove-text-properties (1- bol) eol '(read-only t))
15670 (unwind-protect
15671 (progn
15672 (setq org-columns-overlays
15673 (org-delete-all line-overlays org-columns-overlays))
15674 (mapc 'org-delete-overlay line-overlays)
15675 (org-columns-eval '(org-entry-put pom key nval)))
15676 (org-columns-display-here)))
15677 (move-to-column col)
15678 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15679 (org-columns-update key))))
15681 (defun org-verify-version (task)
15682 (cond
15683 ((eq task 'columns)
15684 (if (or (featurep 'xemacs)
15685 (< emacs-major-version 22))
15686 (error "Emacs 22 is required for the columns feature")))))
15688 (defun org-columns-open-link (&optional arg)
15689 (interactive "P")
15690 (let ((key (get-char-property (point) 'org-columns-key))
15691 (value (get-char-property (point) 'org-columns-value)))
15692 (org-open-link-from-string arg)))
15694 (defun org-open-link-from-string (s &optional arg)
15695 "Open a link in the string S, as if it was in Org-mode."
15696 (interactive)
15697 (with-temp-buffer
15698 (let ((org-inhibit-startup t))
15699 (org-mode)
15700 (insert s)
15701 (goto-char (point-min))
15702 (org-open-at-point arg))))
15704 (defun org-columns-get-format-and-top-level ()
15705 (let (fmt)
15706 (when (condition-case nil (org-back-to-heading) (error nil))
15707 (move-marker org-entry-property-inherited-from nil)
15708 (setq fmt (org-entry-get nil "COLUMNS" t)))
15709 (setq fmt (or fmt org-columns-default-format))
15710 (org-set-local 'org-columns-current-fmt fmt)
15711 (org-columns-compile-format fmt)
15712 (if (marker-position org-entry-property-inherited-from)
15713 (move-marker org-columns-top-level-marker
15714 org-entry-property-inherited-from)
15715 (move-marker org-columns-top-level-marker (point)))
15716 fmt))
15718 (defun org-columns ()
15719 "Turn on column view on an org-mode file."
15720 (interactive)
15721 (org-verify-version 'columns)
15722 (org-columns-remove-overlays)
15723 (move-marker org-columns-begin-marker (point))
15724 (let (beg end fmt cache maxwidths)
15725 (setq fmt (org-columns-get-format-and-top-level))
15726 (save-excursion
15727 (goto-char org-columns-top-level-marker)
15728 (setq beg (point))
15729 (unless org-columns-inhibit-recalculation
15730 (org-columns-compute-all))
15731 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
15732 (point-max)))
15733 (goto-char beg)
15734 ;; Get and cache the properties
15735 (while (re-search-forward (concat "^" outline-regexp) end t)
15736 (push (cons (org-current-line) (org-entry-properties)) cache))
15737 (when cache
15738 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15739 (org-set-local 'org-columns-current-maxwidths maxwidths)
15740 (org-columns-display-here-title)
15741 (mapc (lambda (x)
15742 (goto-line (car x))
15743 (org-columns-display-here (cdr x)))
15744 cache)))))
15746 (defun org-columns-new (&optional prop title width op fmt)
15747 "Insert a new column, to the leeft o the current column."
15748 (interactive)
15749 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
15750 cell)
15751 (setq prop (completing-read
15752 "Property: " (mapcar 'list (org-buffer-property-keys t))
15753 nil nil prop))
15754 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
15755 (setq width (read-string "Column width: " (if width (number-to-string width))))
15756 (if (string-match "\\S-" width)
15757 (setq width (string-to-number width))
15758 (setq width nil))
15759 (setq fmt (completing-read "Summary [none]: "
15760 '(("none") ("add_numbers") ("add_times") ("checkbox"))
15761 nil t))
15762 (if (string-match "\\S-" fmt)
15763 (setq fmt (intern fmt))
15764 (setq fmt nil))
15765 (if (eq fmt 'none) (setq fmt nil))
15766 (if editp
15767 (progn
15768 (setcar editp prop)
15769 (setcdr editp (list title width nil fmt)))
15770 (setq cell (nthcdr (1- (current-column))
15771 org-columns-current-fmt-compiled))
15772 (setcdr cell (cons (list prop title width nil fmt)
15773 (cdr cell))))
15774 (org-columns-store-format)
15775 (org-columns-redo)))
15777 (defun org-columns-delete ()
15778 "Delete the column at point from columns view."
15779 (interactive)
15780 (let* ((n (current-column))
15781 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
15782 (when (y-or-n-p
15783 (format "Are you sure you want to remove column \"%s\"? " title))
15784 (setq org-columns-current-fmt-compiled
15785 (delq (nth n org-columns-current-fmt-compiled)
15786 org-columns-current-fmt-compiled))
15787 (org-columns-store-format)
15788 (org-columns-redo)
15789 (if (>= (current-column) (length org-columns-current-fmt-compiled))
15790 (backward-char 1)))))
15792 (defun org-columns-edit-attributes ()
15793 "Edit the attributes of the current column."
15794 (interactive)
15795 (let* ((n (current-column))
15796 (info (nth n org-columns-current-fmt-compiled)))
15797 (apply 'org-columns-new info)))
15799 (defun org-columns-widen (arg)
15800 "Make the column wider by ARG characters."
15801 (interactive "p")
15802 (let* ((n (current-column))
15803 (entry (nth n org-columns-current-fmt-compiled))
15804 (width (or (nth 2 entry)
15805 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
15806 (setq width (max 1 (+ width arg)))
15807 (setcar (nthcdr 2 entry) width)
15808 (org-columns-store-format)
15809 (org-columns-redo)))
15811 (defun org-columns-narrow (arg)
15812 "Make the column nrrower by ARG characters."
15813 (interactive "p")
15814 (org-columns-widen (- arg)))
15816 (defun org-columns-move-right ()
15817 "Swap this column with the one to the right."
15818 (interactive)
15819 (let* ((n (current-column))
15820 (cell (nthcdr n org-columns-current-fmt-compiled))
15822 (when (>= n (1- (length org-columns-current-fmt-compiled)))
15823 (error "Cannot shift this column further to the right"))
15824 (setq e (car cell))
15825 (setcar cell (car (cdr cell)))
15826 (setcdr cell (cons e (cdr (cdr cell))))
15827 (org-columns-store-format)
15828 (org-columns-redo)
15829 (forward-char 1)))
15831 (defun org-columns-move-left ()
15832 "Swap this column with the one to the left."
15833 (interactive)
15834 (let* ((n (current-column)))
15835 (when (= n 0)
15836 (error "Cannot shift this column further to the left"))
15837 (backward-char 1)
15838 (org-columns-move-right)
15839 (backward-char 1)))
15841 (defun org-columns-store-format ()
15842 "Store the text version of the current columns format in appropriate place.
15843 This is either in the COLUMNS property of the node starting the current column
15844 display, or in the #+COLUMNS line of the current buffer."
15845 (let (fmt (cnt 0))
15846 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
15847 (org-set-local 'org-columns-current-fmt fmt)
15848 (if (marker-position org-columns-top-level-marker)
15849 (save-excursion
15850 (goto-char org-columns-top-level-marker)
15851 (if (and (org-at-heading-p)
15852 (org-entry-get nil "COLUMNS"))
15853 (org-entry-put nil "COLUMNS" fmt)
15854 (goto-char (point-min))
15855 ;; Overwrite all #+COLUMNS lines....
15856 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
15857 (setq cnt (1+ cnt))
15858 (replace-match (concat "#+COLUMNS: " fmt) t t))
15859 (unless (> cnt 0)
15860 (goto-char (point-min))
15861 (or (org-on-heading-p t) (outline-next-heading))
15862 (let ((inhibit-read-only t))
15863 (insert-before-markers "#+COLUMNS: " fmt "\n")))
15864 (org-set-local 'org-columns-default-format fmt))))))
15866 (defvar org-overriding-columns-format nil
15867 "When set, overrides any other definition.")
15868 (defvar org-agenda-view-columns-initially nil
15869 "When set, switch to columns view immediately after creating the agenda.")
15871 (defun org-agenda-columns ()
15872 "Turn on column view in the agenda."
15873 (interactive)
15874 (org-verify-version 'columns)
15875 (org-columns-remove-overlays)
15876 (move-marker org-columns-begin-marker (point))
15877 (let (fmt cache maxwidths m)
15878 (cond
15879 ((and (local-variable-p 'org-overriding-columns-format)
15880 org-overriding-columns-format)
15881 (setq fmt org-overriding-columns-format))
15882 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
15883 (setq fmt (org-entry-get m "COLUMNS" t)))
15884 ((and (boundp 'org-columns-current-fmt)
15885 (local-variable-p 'org-columns-current-fmt)
15886 org-columns-current-fmt)
15887 (setq fmt org-columns-current-fmt))
15888 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
15889 (setq m (get-text-property m 'org-hd-marker))
15890 (setq fmt (org-entry-get m "COLUMNS" t))))
15891 (setq fmt (or fmt org-columns-default-format))
15892 (org-set-local 'org-columns-current-fmt fmt)
15893 (org-columns-compile-format fmt)
15894 (save-excursion
15895 ;; Get and cache the properties
15896 (goto-char (point-min))
15897 (while (not (eobp))
15898 (when (setq m (or (get-text-property (point) 'org-hd-marker)
15899 (get-text-property (point) 'org-marker)))
15900 (push (cons (org-current-line) (org-entry-properties m)) cache))
15901 (beginning-of-line 2))
15902 (when cache
15903 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
15904 (org-set-local 'org-columns-current-maxwidths maxwidths)
15905 (org-columns-display-here-title)
15906 (mapc (lambda (x)
15907 (goto-line (car x))
15908 (org-columns-display-here (cdr x)))
15909 cache)))))
15911 (defun org-columns-get-autowidth-alist (s cache)
15912 "Derive the maximum column widths from the format and the cache."
15913 (let ((start 0) rtn)
15914 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
15915 (push (cons (match-string 1 s) 1) rtn)
15916 (setq start (match-end 0)))
15917 (mapc (lambda (x)
15918 (setcdr x (apply 'max
15919 (mapcar
15920 (lambda (y)
15921 (length (or (cdr (assoc (car x) (cdr y))) " ")))
15922 cache))))
15923 rtn)
15924 rtn))
15926 (defun org-columns-compute-all ()
15927 "Compute all columns that have operators defined."
15928 (org-unmodified
15929 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
15930 (let ((columns org-columns-current-fmt-compiled) col)
15931 (while (setq col (pop columns))
15932 (when (nth 3 col)
15933 (save-excursion
15934 (org-columns-compute (car col)))))))
15936 (defun org-columns-update (property)
15937 "Recompute PROPERTY, and update the columns display for it."
15938 (org-columns-compute property)
15939 (let (fmt val pos)
15940 (save-excursion
15941 (mapc (lambda (ov)
15942 (when (equal (org-overlay-get ov 'org-columns-key) property)
15943 (setq pos (org-overlay-start ov))
15944 (goto-char pos)
15945 (when (setq val (cdr (assoc property
15946 (get-text-property
15947 (point-at-bol) 'org-summaries))))
15948 (setq fmt (org-overlay-get ov 'org-columns-format))
15949 (org-overlay-put ov 'org-columns-value val)
15950 (org-overlay-put ov 'display (format fmt val)))))
15951 org-columns-overlays))))
15953 (defun org-columns-compute (property)
15954 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
15955 (interactive)
15956 (let* ((re (concat "^" outline-regexp))
15957 (lmax 30) ; Does anyone use deeper levels???
15958 (lsum (make-vector lmax 0))
15959 (lflag (make-vector lmax nil))
15960 (level 0)
15961 (ass (assoc property org-columns-current-fmt-compiled))
15962 (format (nth 4 ass))
15963 (beg org-columns-top-level-marker)
15964 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
15965 (save-excursion
15966 ;; Find the region to compute
15967 (goto-char beg)
15968 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
15969 (goto-char end)
15970 ;; Walk the tree from the back and do the computations
15971 (while (re-search-backward re beg t)
15972 (setq sumpos (match-beginning 0)
15973 last-level level
15974 level (org-outline-level)
15975 val (org-entry-get nil property)
15976 valflag (and val (string-match "\\S-" val)))
15977 (cond
15978 ((< level last-level)
15979 ;; put the sum of lower levels here as a property
15980 (setq sum (aref lsum last-level) ; current sum
15981 flag (aref lflag last-level) ; any valid entries from children?
15982 str (org-column-number-to-string sum format)
15983 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
15984 useval (if flag str1 (if valflag val ""))
15985 sum-alist (get-text-property sumpos 'org-summaries))
15986 (if (assoc property sum-alist)
15987 (setcdr (assoc property sum-alist) useval)
15988 (push (cons property useval) sum-alist)
15989 (org-unmodified
15990 (add-text-properties sumpos (1+ sumpos)
15991 (list 'org-summaries sum-alist))))
15992 (when val
15993 (org-entry-put nil property (if flag str val)))
15994 ;; add current to current level accumulator
15995 (when (or flag valflag)
15996 ;; FIXME: is this ok?????????
15997 (aset lsum level (+ (aref lsum level)
15998 (if flag sum (org-column-string-to-number
15999 (if flag str val) format))))
16000 (aset lflag level t))
16001 ;; clear accumulators for deeper levels
16002 (loop for l from (1+ level) to (1- lmax) do
16003 (aset lsum l 0)
16004 (aset lflag l nil)))
16005 ((>= level last-level)
16006 ;; add what we have here to the accumulator for this level
16007 (aset lsum level (+ (aref lsum level)
16008 (org-column-string-to-number (or val "0") format)))
16009 (and valflag (aset lflag level t)))
16010 (t (error "This should not happen")))))))
16012 (defun org-columns-redo ()
16013 "Construct the column display again."
16014 (interactive)
16015 (message "Recomputing columns...")
16016 (save-excursion
16017 (if (marker-position org-columns-begin-marker)
16018 (goto-char org-columns-begin-marker))
16019 (org-columns-remove-overlays)
16020 (if (org-mode-p)
16021 (call-interactively 'org-columns)
16022 (call-interactively 'org-agenda-columns)))
16023 (message "Recomputing columns...done"))
16025 (defun org-columns-not-in-agenda ()
16026 (if (eq major-mode 'org-agenda-mode)
16027 (error "This command is only allowed in Org-mode buffers")))
16030 (defun org-string-to-number (s)
16031 "Convert string to number, and interpret hh:mm:ss."
16032 (if (not (string-match ":" s))
16033 (string-to-number s)
16034 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16035 (while l
16036 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16037 sum)))
16039 (defun org-column-number-to-string (n fmt)
16040 "Convert a computed column number to a string value, according to FMT."
16041 (cond
16042 ((eq fmt 'add_times)
16043 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16044 (format "%d:%02d" h m)))
16045 ((eq fmt 'checkbox)
16046 (cond ((= n (floor n)) "[X]")
16047 ((> n 1.) "[-]")
16048 (t "[ ]")))
16049 (t (number-to-string n))))
16051 (defun org-column-string-to-number (s fmt)
16052 "Convert a column value to a number that can be used for column computing."
16053 (cond
16054 ((string-match ":" s)
16055 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16056 (while l
16057 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16058 sum))
16059 ((eq fmt 'checkbox)
16060 (if (equal s "[X]") 1. 0.000001))
16061 (t (string-to-number s))))
16063 (defun org-columns-uncompile-format (cfmt)
16064 "Turn the compiled columns format back into a string representation."
16065 (let ((rtn "") e s prop title op width fmt)
16066 (while (setq e (pop cfmt))
16067 (setq prop (car e)
16068 title (nth 1 e)
16069 width (nth 2 e)
16070 op (nth 3 e)
16071 fmt (nth 4 e))
16072 (cond
16073 ((eq fmt 'add_times) (setq op ":"))
16074 ((eq fmt 'checkbox) (setq op "X"))
16075 ((eq fmt 'add_numbers) (setq op "+")))
16076 (if (equal title prop) (setq title nil))
16077 (setq s (concat "%" (if width (number-to-string width))
16078 prop
16079 (if title (concat "(" title ")"))
16080 (if op (concat "{" op "}"))))
16081 (setq rtn (concat rtn " " s)))
16082 (org-trim rtn)))
16084 (defun org-columns-compile-format (fmt)
16085 "Turn a column format string into an alist of specifications.
16086 The alist has one entry for each column in the format. The elements of
16087 that list are:
16088 property the property
16089 title the title field for the columns
16090 width the column width in characters, can be nil for automatic
16091 operator the operator if any
16092 format the output format for computed results, derived from operator"
16093 (let ((start 0) width prop title op f)
16094 (setq org-columns-current-fmt-compiled nil)
16095 (while (string-match
16096 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16097 fmt start)
16098 (setq start (match-end 0)
16099 width (match-string 1 fmt)
16100 prop (match-string 2 fmt)
16101 title (or (match-string 3 fmt) prop)
16102 op (match-string 4 fmt)
16103 f nil)
16104 (if width (setq width (string-to-number width)))
16105 (cond
16106 ((equal op "+") (setq f 'add_numbers))
16107 ((equal op ":") (setq f 'add_times))
16108 ((equal op "X") (setq f 'checkbox)))
16109 (push (list prop title width op f) org-columns-current-fmt-compiled))
16110 (setq org-columns-current-fmt-compiled
16111 (nreverse org-columns-current-fmt-compiled))))
16114 ;;; Dynamic block for Column view
16116 (defun org-columns-capture-view ()
16117 "Get the column view of the current buffer and return it as a list.
16118 The list will contains the title row and all other rows. Each row is
16119 a list of fields."
16120 (save-excursion
16121 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16122 (n (length title)) row tbl)
16123 (goto-char (point-min))
16124 (while (re-search-forward "^\\*+ " nil t)
16125 (when (get-char-property (match-beginning 0) 'org-columns-key)
16126 (setq row nil)
16127 (loop for i from 0 to (1- n) do
16128 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16129 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16131 row))
16132 (setq row (nreverse row))
16133 (push row tbl)))
16134 (append (list title 'hline) (nreverse tbl)))))
16136 (defun org-dblock-write:columnview (params)
16137 "Write the column view table.
16138 PARAMS is a property list of parameters:
16140 :width enforce same column widths with <N> specifiers.
16141 :id the :ID: property of the entry where the columns view
16142 should be built, as a string. When `local', call locally.
16143 When `global' call column view with the cursor at the beginning
16144 of the buffer (usually this means that the whole buffer switches
16145 to column view).
16146 :hlines When t, insert a hline before each item. When a number, insert
16147 a hline before each level <= that number.
16148 :vlines When t, make each column a colgroup to enforce vertical lines."
16149 (let ((pos (move-marker (make-marker) (point)))
16150 (hlines (plist-get params :hlines))
16151 (vlines (plist-get params :vlines))
16152 tbl id idpos nfields tmp)
16153 (save-excursion
16154 (save-restriction
16155 (when (setq id (plist-get params :id))
16156 (cond ((not id) nil)
16157 ((eq id 'global) (goto-char (point-min)))
16158 ((eq id 'local) nil)
16159 ((setq idpos (org-find-entry-with-id id))
16160 (goto-char idpos))
16161 (t (error "Cannot find entry with :ID: %s" id))))
16162 (org-columns)
16163 (setq tbl (org-columns-capture-view))
16164 (setq nfields (length (car tbl)))
16165 (org-columns-quit)))
16166 (goto-char pos)
16167 (move-marker pos nil)
16168 (when tbl
16169 (when (plist-get params :hlines)
16170 (setq tmp nil)
16171 (while tbl
16172 (if (eq (car tbl) 'hline)
16173 (push (pop tbl) tmp)
16174 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16175 (if (and (not (eq (car tmp) 'hline))
16176 (or (eq hlines t)
16177 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16178 (push 'hline tmp)))
16179 (push (pop tbl) tmp)))
16180 (setq tbl (nreverse tmp)))
16181 (when vlines
16182 (setq tbl (mapcar (lambda (x)
16183 (if (eq 'hline x) x (cons "" x)))
16184 tbl))
16185 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16186 (setq pos (point))
16187 (insert (org-listtable-to-string tbl))
16188 (when (plist-get params :width)
16189 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16190 org-columns-current-widths "|")))
16191 (goto-char pos)
16192 (org-table-align))))
16194 (defun org-listtable-to-string (tbl)
16195 "Convert a listtable TBL to a string that contains the Org-mode table.
16196 The table still need to be alligned. The resulting string has no leading
16197 and tailing newline characters."
16198 (mapconcat
16199 (lambda (x)
16200 (cond
16201 ((listp x)
16202 (concat "|" (mapconcat 'identity x "|") "|"))
16203 ((eq x 'hline) "|-|")
16204 (t (error "Garbage in listtable: %s" x))))
16205 tbl "\n"))
16207 (defun org-insert-columns-dblock ()
16208 "Create a dynamic block capturing a column view table."
16209 (interactive)
16210 (let ((defaults '(:name "columnview" :hlines 1))
16211 (id (completing-read
16212 "Capture columns (local, global, entry with :ID: property) [local]: "
16213 (append '(("global") ("local"))
16214 (mapcar 'list (org-property-values "ID"))))))
16215 (if (equal id "") (setq id 'local))
16216 (if (equal id "global") (setq id 'global))
16217 (setq defaults (append defaults (list :id id)))
16218 (org-create-dblock defaults)
16219 (org-update-dblock)))
16221 ;;;; Timestamps
16223 (defvar org-last-changed-timestamp nil)
16224 (defvar org-time-was-given) ; dynamically scoped parameter
16225 (defvar org-end-time-was-given) ; dynamically scoped parameter
16226 (defvar org-ts-what) ; dynamically scoped parameter
16228 (defun org-time-stamp (arg)
16229 "Prompt for a date/time and insert a time stamp.
16230 If the user specifies a time like HH:MM, or if this command is called
16231 with a prefix argument, the time stamp will contain date and time.
16232 Otherwise, only the date will be included. All parts of a date not
16233 specified by the user will be filled in from the current date/time.
16234 So if you press just return without typing anything, the time stamp
16235 will represent the current date/time. If there is already a timestamp
16236 at the cursor, it will be modified."
16237 (interactive "P")
16238 (let ((default-time
16239 ;; Default time is either today, or, when entering a range,
16240 ;; the range start.
16241 (if (or (org-at-timestamp-p t)
16242 (save-excursion
16243 (re-search-backward
16244 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16245 (- (point) 20) t)))
16246 (apply 'encode-time (org-parse-time-string (match-string 1)))
16247 (current-time)))
16248 org-time-was-given org-end-time-was-given time)
16249 (cond
16250 ((and (org-at-timestamp-p)
16251 (eq last-command 'org-time-stamp)
16252 (eq this-command 'org-time-stamp))
16253 (insert "--")
16254 (setq time (let ((this-command this-command))
16255 (org-read-date arg 'totime nil nil default-time)))
16256 (org-insert-time-stamp time (or org-time-was-given arg)))
16257 ((org-at-timestamp-p)
16258 (setq time (let ((this-command this-command))
16259 (org-read-date arg 'totime nil nil default-time)))
16260 (when (org-at-timestamp-p) ; just to get the match data
16261 (replace-match "")
16262 (setq org-last-changed-timestamp
16263 (org-insert-time-stamp
16264 time (or org-time-was-given arg)
16265 nil nil nil (list org-end-time-was-given))))
16266 (message "Timestamp updated"))
16268 (setq time (let ((this-command this-command))
16269 (org-read-date arg 'totime nil nil default-time)))
16270 (org-insert-time-stamp time (or org-time-was-given arg)
16271 nil nil nil (list org-end-time-was-given))))))
16273 (defun org-time-stamp-inactive (&optional arg)
16274 "Insert an inactive time stamp.
16275 An inactive time stamp is enclosed in square brackets instead of angle
16276 brackets. It is inactive in the sense that it does not trigger agenda entries,
16277 does not link to the calendar and cannot be changed with the S-cursor keys.
16278 So these are more for recording a certain time/date."
16279 (interactive "P")
16280 (let (org-time-was-given org-end-time-was-given time)
16281 (setq time (org-read-date arg 'totime))
16282 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16283 nil nil (list org-end-time-was-given))))
16285 (defvar org-date-ovl (org-make-overlay 1 1))
16286 (org-overlay-put org-date-ovl 'face 'org-warning)
16287 (org-detach-overlay org-date-ovl)
16289 (defvar org-ans1) ; dynamically scoped parameter
16290 (defvar org-ans2) ; dynamically scoped parameter
16292 (defvar org-plain-time-of-day-regexp) ; defined below
16293 (defun org-read-date (&optional with-time to-time from-string prompt
16294 default-time)
16295 "Read a date and make things smooth for the user.
16296 The prompt will suggest to enter an ISO date, but you can also enter anything
16297 which will at least partially be understood by `parse-time-string'.
16298 Unrecognized parts of the date will default to the current day, month, year,
16299 hour and minute. If this command is called to replace a timestamp at point,
16300 of to enter the second timestamp of a range, the default time is taken from the
16301 existing stamp. For example,
16302 3-2-5 --> 2003-02-05
16303 feb 15 --> currentyear-02-15
16304 sep 12 9 --> 2009-09-12
16305 12:45 --> today 12:45
16306 22 sept 0:34 --> currentyear-09-22 0:34
16307 12 --> currentyear-currentmonth-12
16308 Fri --> nearest Friday (today or later)
16309 etc.
16311 Furthermore you can specify a relative date by giving, as the *first* thing
16312 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16313 change in days weeks, months, years.
16314 With a single plus or minus, the date is relative to today. With a double
16315 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16316 +4d --> four days from today
16317 +4 --> same as above
16318 +2w --> two weeks from today
16319 ++5 --> five days from default date
16321 The function understands only English month and weekday abbreviations,
16322 but this can be configured with the variables `parse-time-months' and
16323 `parse-time-weekdays'.
16325 While prompting, a calendar is popped up - you can also select the
16326 date with the mouse (button 1). The calendar shows a period of three
16327 months. To scroll it to other months, use the keys `>' and `<'.
16328 If you don't like the calendar, turn it off with
16329 \(setq org-popup-calendar-for-date-prompt nil)
16331 With optional argument TO-TIME, the date will immediately be converted
16332 to an internal time.
16333 With an optional argument WITH-TIME, the prompt will suggest to also
16334 insert a time. Note that when WITH-TIME is not set, you can still
16335 enter a time, and this function will inform the calling routine about
16336 this change. The calling routine may then choose to change the format
16337 used to insert the time stamp into the buffer to include the time.
16338 With optional argument FROM-STRING, read fomr this string instead from
16339 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16340 the time/date that is used for everything that is not specified by the
16341 user."
16342 (require 'parse-time)
16343 (let* ((org-time-stamp-rounding-minutes
16344 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16345 (ct (org-current-time))
16346 (def (or default-time ct))
16347 (defdecode (decode-time def))
16348 (calendar-move-hook nil)
16349 (view-diary-entries-initially nil)
16350 (view-calendar-holidays-initially nil)
16351 (timestr (format-time-string
16352 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16353 (prompt (concat (if prompt (concat prompt " ") "")
16354 (format "Date and/or time (default [%s]): " timestr)))
16355 ans (org-ans0 "") org-ans1 org-ans2 delta deltan deltaw deltadef
16356 second minute hour day month year tl wday wday1 pm h2 m2)
16358 (cond
16359 (from-string (setq ans from-string))
16360 (org-popup-calendar-for-date-prompt
16361 (save-excursion
16362 (save-window-excursion
16363 (calendar)
16364 (calendar-forward-day (- (time-to-days def)
16365 (calendar-absolute-from-gregorian
16366 (calendar-current-date))))
16367 (org-eval-in-calendar nil t)
16368 (let* ((old-map (current-local-map))
16369 (map (copy-keymap calendar-mode-map))
16370 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16371 (org-defkey map (kbd "RET") 'org-calendar-select)
16372 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16373 'org-calendar-select-mouse)
16374 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16375 'org-calendar-select-mouse)
16376 (org-defkey minibuffer-local-map [(meta shift left)]
16377 (lambda () (interactive)
16378 (org-eval-in-calendar '(calendar-backward-month 1))))
16379 (org-defkey minibuffer-local-map [(meta shift right)]
16380 (lambda () (interactive)
16381 (org-eval-in-calendar '(calendar-forward-month 1))))
16382 (org-defkey minibuffer-local-map [(shift up)]
16383 (lambda () (interactive)
16384 (org-eval-in-calendar '(calendar-backward-week 1))))
16385 (org-defkey minibuffer-local-map [(shift down)]
16386 (lambda () (interactive)
16387 (org-eval-in-calendar '(calendar-forward-week 1))))
16388 (org-defkey minibuffer-local-map [(shift left)]
16389 (lambda () (interactive)
16390 (org-eval-in-calendar '(calendar-backward-day 1))))
16391 (org-defkey minibuffer-local-map [(shift right)]
16392 (lambda () (interactive)
16393 (org-eval-in-calendar '(calendar-forward-day 1))))
16394 (org-defkey minibuffer-local-map ">"
16395 (lambda () (interactive)
16396 (org-eval-in-calendar '(scroll-calendar-left 1))))
16397 (org-defkey minibuffer-local-map "<"
16398 (lambda () (interactive)
16399 (org-eval-in-calendar '(scroll-calendar-right 1))))
16400 (unwind-protect
16401 (progn
16402 (use-local-map map)
16403 (setq org-ans0 (read-string prompt "" nil nil))
16404 ;; org-ans0: from prompt
16405 ;; org-ans1: from mouse click
16406 ;; org-ans2: from calendar motion
16407 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16408 (use-local-map old-map))))))
16409 (t ; Naked prompt only
16410 (setq ans (read-string prompt "" nil timestr))))
16411 (org-detach-overlay org-date-ovl)
16413 (when (setq delta (org-read-date-get-relative ans (current-time) def))
16414 (setq ans (replace-match "" t t ans)
16415 deltan (car delta)
16416 deltaw (nth 1 delta)
16417 deltadef (nth 2 delta)))
16419 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
16420 (when (string-match
16421 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16422 (setq year (if (match-end 2)
16423 (string-to-number (match-string 2 ans))
16424 (string-to-number (format-time-string "%Y")))
16425 month (string-to-number (match-string 3 ans))
16426 day (string-to-number (match-string 4 ans)))
16427 (if (< year 100) (setq year (+ 2000 year)))
16428 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16429 t nil ans)))
16430 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16431 ;; If there is a time with am/pm, and *no* time without it, we convert
16432 ;; so that matching will be successful.
16433 (loop for i from 1 to 2 do ; twice, for end time as well
16434 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16435 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16436 (setq hour (string-to-number (match-string 1 ans))
16437 minute (if (match-end 3)
16438 (string-to-number (match-string 3 ans))
16440 pm (equal ?p
16441 (string-to-char (downcase (match-string 4 ans)))))
16442 (if (and (= hour 12) (not pm))
16443 (setq hour 0)
16444 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16445 (setq ans (replace-match (format "%02d:%02d" hour minute)
16446 t t ans))))
16448 ;; Check if a time range is given as a duration
16449 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16450 (setq hour (string-to-number (match-string 1 ans))
16451 h2 (+ hour (string-to-number (match-string 3 ans)))
16452 minute (string-to-number (match-string 2 ans))
16453 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
16454 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
16456 ;; Check if there is a time range
16457 (when (and (boundp 'org-end-time-was-given)
16458 (string-match org-plain-time-of-day-regexp ans)
16459 (match-end 8))
16460 (setq org-end-time-was-given (match-string 8 ans))
16461 (setq ans (concat (substring ans 0 (match-beginning 7))
16462 (substring ans (match-end 7)))))
16464 (setq tl (parse-time-string ans)
16465 day (or (nth 3 tl) (string-to-number (format-time-string "%d" def)))
16466 month (or (nth 4 tl) (string-to-number (format-time-string "%m" def)))
16467 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" def)))
16468 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" def)))
16469 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" def)))
16470 second (or (nth 0 tl) 0)
16471 wday (nth 6 tl))
16472 (when deltan
16473 (unless deltadef
16474 (let ((now (decode-time (current-time))))
16475 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16476 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16477 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16478 ((equal deltaw "m") (setq month (+ month deltan)))
16479 ((equal deltaw "y") (setq year (+ year deltan)))))
16480 (when (and wday (not (nth 3 tl)))
16481 ;; Weekday was given, but no day, so pick that day in the week
16482 ;; on or after the derived date.
16483 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16484 (unless (equal wday wday1)
16485 (setq day (+ day (% (- wday wday1 -7) 7)))))
16486 (if (and (boundp 'org-time-was-given)
16487 (nth 2 tl))
16488 (setq org-time-was-given t))
16489 (if (< year 100) (setq year (+ 2000 year)))
16490 (if to-time
16491 (encode-time second minute hour day month year)
16492 (if (or (nth 1 tl) (nth 2 tl))
16493 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
16494 (format "%04d-%02d-%02d" year month day)))))
16496 ;(defun org-parse-for-shift (n1 n2 given-dec default-dec)
16497 ; (cond
16498 ; ((not (nth n1 given-dec))
16499 ; (nth n1 default-dec))
16500 ; ((or (> (nth n1 given-dec) (nth n1 (default-dec)))
16501 ; (not org-read-date-prefer-future))
16502 ; (nth n1 given-dec))
16503 ; (t (1+
16504 ; (if (nth 3 given-dec)
16505 ; (nth 3 given-dec)
16506 ; (if (> (nth
16507 ; (setq given
16508 ; (if (and
16510 (defvar parse-time-weekdays)
16512 (defun org-read-date-get-relative (s today default)
16513 "Check string S for special relative date string.
16514 TODAY and DEFAULT are internal times, for today and for a default.
16515 Return shift list (N what def-flag)
16516 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
16517 N is the number if WHATs to shift
16518 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16519 the DEFAULT date rather than TODAY."
16520 (when (string-match
16521 (concat
16522 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
16523 "\\([0-9]+\\)?"
16524 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16525 "\\([ \t]\\|$\\)") s)
16526 (let* ((dir (if (match-end 1)
16527 (string-to-char (substring (match-string 1 s) -1))
16528 ?+))
16529 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16530 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16531 (what (if (match-end 3) (match-string 3 s) "d"))
16532 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16533 (date (if rel default today))
16534 (wday (nth 6 (decode-time date)))
16535 delta)
16536 (if wday1
16537 (progn
16538 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16539 (if (= dir ?-) (setq delta (- delta 7)))
16540 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16541 (list delta "d" rel))
16542 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16544 (defun org-eval-in-calendar (form &optional keepdate)
16545 "Eval FORM in the calendar window and return to current window.
16546 Also, store the cursor date in variable org-ans2."
16547 (let ((sw (selected-window)))
16548 (select-window (get-buffer-window "*Calendar*"))
16549 (eval form)
16550 (when (and (not keepdate) (calendar-cursor-to-date))
16551 (let* ((date (calendar-cursor-to-date))
16552 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16553 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16554 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16555 (select-window sw)
16556 ;; Update the prompt to show new default date
16557 (save-excursion
16558 (goto-char (point-min))
16559 (when (and org-ans2
16560 (re-search-forward "\\[[-0-9]+\\]" nil t)
16561 (get-text-property (match-end 0) 'field))
16562 (let ((inhibit-read-only t))
16563 (replace-match (concat "[" org-ans2 "]") t t)
16564 (add-text-properties (point-min) (1+ (match-end 0))
16565 (text-properties-at (1+ (point-min)))))))))
16567 (defun org-calendar-select ()
16568 "Return to `org-read-date' with the date currently selected.
16569 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16570 (interactive)
16571 (when (calendar-cursor-to-date)
16572 (let* ((date (calendar-cursor-to-date))
16573 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16574 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16575 (if (active-minibuffer-window) (exit-minibuffer))))
16577 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16578 "Insert a date stamp for the date given by the internal TIME.
16579 WITH-HM means, use the stamp format that includes the time of the day.
16580 INACTIVE means use square brackets instead of angular ones, so that the
16581 stamp will not contribute to the agenda.
16582 PRE and POST are optional strings to be inserted before and after the
16583 stamp.
16584 The command returns the inserted time stamp."
16585 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16586 stamp)
16587 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16588 (insert-before-markers (or pre ""))
16589 (insert-before-markers (setq stamp (format-time-string fmt time)))
16590 (when (listp extra)
16591 (setq extra (car extra))
16592 (if (and (stringp extra)
16593 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16594 (setq extra (format "-%02d:%02d"
16595 (string-to-number (match-string 1 extra))
16596 (string-to-number (match-string 2 extra))))
16597 (setq extra nil)))
16598 (when extra
16599 (backward-char 1)
16600 (insert-before-markers extra)
16601 (forward-char 1))
16602 (insert-before-markers (or post ""))
16603 stamp))
16605 (defun org-toggle-time-stamp-overlays ()
16606 "Toggle the use of custom time stamp formats."
16607 (interactive)
16608 (setq org-display-custom-times (not org-display-custom-times))
16609 (unless org-display-custom-times
16610 (let ((p (point-min)) (bmp (buffer-modified-p)))
16611 (while (setq p (next-single-property-change p 'display))
16612 (if (and (get-text-property p 'display)
16613 (eq (get-text-property p 'face) 'org-date))
16614 (remove-text-properties
16615 p (setq p (next-single-property-change p 'display))
16616 '(display t))))
16617 (set-buffer-modified-p bmp)))
16618 (if (featurep 'xemacs)
16619 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
16620 (org-restart-font-lock)
16621 (setq org-table-may-need-update t)
16622 (if org-display-custom-times
16623 (message "Time stamps are overlayed with custom format")
16624 (message "Time stamp overlays removed")))
16626 (defun org-display-custom-time (beg end)
16627 "Overlay modified time stamp format over timestamp between BED and END."
16628 (let* ((ts (buffer-substring beg end))
16629 t1 w1 with-hm tf time str w2 (off 0))
16630 (save-match-data
16631 (setq t1 (org-parse-time-string ts t))
16632 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
16633 (setq off (- (match-end 0) (match-beginning 0)))))
16634 (setq end (- end off))
16635 (setq w1 (- end beg)
16636 with-hm (and (nth 1 t1) (nth 2 t1))
16637 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
16638 time (org-fix-decoded-time t1)
16639 str (org-add-props
16640 (format-time-string
16641 (substring tf 1 -1) (apply 'encode-time time))
16642 nil 'mouse-face 'highlight)
16643 w2 (length str))
16644 (if (not (= w2 w1))
16645 (add-text-properties (1+ beg) (+ 2 beg)
16646 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
16647 (if (featurep 'xemacs)
16648 (progn
16649 (put-text-property beg end 'invisible t)
16650 (put-text-property beg end 'end-glyph (make-glyph str)))
16651 (put-text-property beg end 'display str))))
16653 (defun org-translate-time (string)
16654 "Translate all timestamps in STRING to custom format.
16655 But do this only if the variable `org-display-custom-times' is set."
16656 (when org-display-custom-times
16657 (save-match-data
16658 (let* ((start 0)
16659 (re org-ts-regexp-both)
16660 t1 with-hm inactive tf time str beg end)
16661 (while (setq start (string-match re string start))
16662 (setq beg (match-beginning 0)
16663 end (match-end 0)
16664 t1 (save-match-data
16665 (org-parse-time-string (substring string beg end) t))
16666 with-hm (and (nth 1 t1) (nth 2 t1))
16667 inactive (equal (substring string beg (1+ beg)) "[")
16668 tf (funcall (if with-hm 'cdr 'car)
16669 org-time-stamp-custom-formats)
16670 time (org-fix-decoded-time t1)
16671 str (format-time-string
16672 (concat
16673 (if inactive "[" "<") (substring tf 1 -1)
16674 (if inactive "]" ">"))
16675 (apply 'encode-time time))
16676 string (replace-match str t t string)
16677 start (+ start (length str)))))))
16678 string)
16680 (defun org-fix-decoded-time (time)
16681 "Set 0 instead of nil for the first 6 elements of time.
16682 Don't touch the rest."
16683 (let ((n 0))
16684 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
16686 (defun org-days-to-time (timestamp-string)
16687 "Difference between TIMESTAMP-STRING and now in days."
16688 (- (time-to-days (org-time-string-to-time timestamp-string))
16689 (time-to-days (current-time))))
16691 (defun org-deadline-close (timestamp-string &optional ndays)
16692 "Is the time in TIMESTAMP-STRING close to the current date?"
16693 (setq ndays (or ndays (org-get-wdays timestamp-string)))
16694 (and (< (org-days-to-time timestamp-string) ndays)
16695 (not (org-entry-is-done-p))))
16697 (defun org-get-wdays (ts)
16698 "Get the deadline lead time appropriate for timestring TS."
16699 (cond
16700 ((<= org-deadline-warning-days 0)
16701 ;; 0 or negative, enforce this value no matter what
16702 (- org-deadline-warning-days))
16703 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
16704 ;; lead time is specified.
16705 (floor (* (string-to-number (match-string 1 ts))
16706 (cdr (assoc (match-string 2 ts)
16707 '(("d" . 1) ("w" . 7)
16708 ("m" . 30.4) ("y" . 365.25)))))))
16709 ;; go for the default.
16710 (t org-deadline-warning-days)))
16712 (defun org-calendar-select-mouse (ev)
16713 "Return to `org-read-date' with the date currently selected.
16714 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16715 (interactive "e")
16716 (mouse-set-point ev)
16717 (when (calendar-cursor-to-date)
16718 (let* ((date (calendar-cursor-to-date))
16719 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16720 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16721 (if (active-minibuffer-window) (exit-minibuffer))))
16723 (defun org-check-deadlines (ndays)
16724 "Check if there are any deadlines due or past due.
16725 A deadline is considered due if it happens within `org-deadline-warning-days'
16726 days from today's date. If the deadline appears in an entry marked DONE,
16727 it is not shown. The prefix arg NDAYS can be used to test that many
16728 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
16729 (interactive "P")
16730 (let* ((org-warn-days
16731 (cond
16732 ((equal ndays '(4)) 100000)
16733 (ndays (prefix-numeric-value ndays))
16734 (t (abs org-deadline-warning-days))))
16735 (case-fold-search nil)
16736 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
16737 (callback
16738 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
16740 (message "%d deadlines past-due or due within %d days"
16741 (org-occur regexp nil callback)
16742 org-warn-days)))
16744 (defun org-evaluate-time-range (&optional to-buffer)
16745 "Evaluate a time range by computing the difference between start and end.
16746 Normally the result is just printed in the echo area, but with prefix arg
16747 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
16748 If the time range is actually in a table, the result is inserted into the
16749 next column.
16750 For time difference computation, a year is assumed to be exactly 365
16751 days in order to avoid rounding problems."
16752 (interactive "P")
16754 (org-clock-update-time-maybe)
16755 (save-excursion
16756 (unless (org-at-date-range-p t)
16757 (goto-char (point-at-bol))
16758 (re-search-forward org-tr-regexp-both (point-at-eol) t))
16759 (if (not (org-at-date-range-p t))
16760 (error "Not at a time-stamp range, and none found in current line")))
16761 (let* ((ts1 (match-string 1))
16762 (ts2 (match-string 2))
16763 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
16764 (match-end (match-end 0))
16765 (time1 (org-time-string-to-time ts1))
16766 (time2 (org-time-string-to-time ts2))
16767 (t1 (time-to-seconds time1))
16768 (t2 (time-to-seconds time2))
16769 (diff (abs (- t2 t1)))
16770 (negative (< (- t2 t1) 0))
16771 ;; (ys (floor (* 365 24 60 60)))
16772 (ds (* 24 60 60))
16773 (hs (* 60 60))
16774 (fy "%dy %dd %02d:%02d")
16775 (fy1 "%dy %dd")
16776 (fd "%dd %02d:%02d")
16777 (fd1 "%dd")
16778 (fh "%02d:%02d")
16779 y d h m align)
16780 (if havetime
16781 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16783 d (floor (/ diff ds)) diff (mod diff ds)
16784 h (floor (/ diff hs)) diff (mod diff hs)
16785 m (floor (/ diff 60)))
16786 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
16788 d (floor (+ (/ diff ds) 0.5))
16789 h 0 m 0))
16790 (if (not to-buffer)
16791 (message (org-make-tdiff-string y d h m))
16792 (when (org-at-table-p)
16793 (goto-char match-end)
16794 (setq align t)
16795 (and (looking-at " *|") (goto-char (match-end 0))))
16796 (if (looking-at
16797 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
16798 (replace-match ""))
16799 (if negative (insert " -"))
16800 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
16801 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
16802 (insert " " (format fh h m))))
16803 (if align (org-table-align))
16804 (message "Time difference inserted")))))
16806 (defun org-make-tdiff-string (y d h m)
16807 (let ((fmt "")
16808 (l nil))
16809 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
16810 l (push y l)))
16811 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
16812 l (push d l)))
16813 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
16814 l (push h l)))
16815 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
16816 l (push m l)))
16817 (apply 'format fmt (nreverse l))))
16819 (defun org-time-string-to-time (s)
16820 (apply 'encode-time (org-parse-time-string s)))
16822 (defun org-time-string-to-absolute (s &optional daynr)
16823 "Convert a time stamp to an absolute day number.
16824 If there is a specifyer for a cyclic time stamp, get the closest date to
16825 DAYNR."
16826 (cond
16827 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
16828 (if (org-diary-sexp-entry (match-string 1 s) "" date)
16829 daynr
16830 (+ daynr 1000)))
16831 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
16832 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
16833 (time-to-days (current-time))) (match-string 0 s)))
16834 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
16836 (defun org-time-from-absolute (d)
16837 "Return the time corresponding to date D.
16838 D may be an absolute day number, or a calendar-type list (month day year)."
16839 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
16840 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
16842 (defun org-calendar-holiday ()
16843 "List of holidays, for Diary display in Org-mode."
16844 (let ((hl (check-calendar-holidays date)))
16845 (if hl (mapconcat 'identity hl "; "))))
16847 (defun org-diary-sexp-entry (sexp entry date)
16848 "Process a SEXP diary ENTRY for DATE."
16849 (require 'diary-lib)
16850 (let ((result (if calendar-debug-sexp
16851 (let ((stack-trace-on-error t))
16852 (eval (car (read-from-string sexp))))
16853 (condition-case nil
16854 (eval (car (read-from-string sexp)))
16855 (error
16856 (beep)
16857 (message "Bad sexp at line %d in %s: %s"
16858 (org-current-line)
16859 (buffer-file-name) sexp)
16860 (sleep-for 2))))))
16861 (cond ((stringp result) result)
16862 ((and (consp result)
16863 (stringp (cdr result))) (cdr result))
16864 (result entry)
16865 (t nil))))
16867 (defun org-diary-to-ical-string (frombuf)
16868 "Get iCalendar entreis from diary entries in buffer FROMBUF.
16869 This uses the icalendar.el library."
16870 (let* ((tmpdir (if (featurep 'xemacs)
16871 (temp-directory)
16872 temporary-file-directory))
16873 (tmpfile (make-temp-name
16874 (expand-file-name "orgics" tmpdir)))
16875 buf rtn b e)
16876 (save-excursion
16877 (set-buffer frombuf)
16878 (icalendar-export-region (point-min) (point-max) tmpfile)
16879 (setq buf (find-buffer-visiting tmpfile))
16880 (set-buffer buf)
16881 (goto-char (point-min))
16882 (if (re-search-forward "^BEGIN:VEVENT" nil t)
16883 (setq b (match-beginning 0)))
16884 (goto-char (point-max))
16885 (if (re-search-backward "^END:VEVENT" nil t)
16886 (setq e (match-end 0)))
16887 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
16888 (kill-buffer buf)
16889 (kill-buffer frombuf)
16890 (delete-file tmpfile)
16891 rtn))
16893 (defun org-closest-date (start current change)
16894 "Find the date closest to CURRENT that is consistent with START and CHANGE."
16895 ;; Make the proper lists from the dates
16896 (catch 'exit
16897 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
16898 dn dw sday cday n1 n2
16899 d m y y1 y2 date1 date2 nmonths nm ny m2)
16901 (setq start (org-date-to-gregorian start)
16902 current (org-date-to-gregorian
16903 (if org-agenda-repeating-timestamp-show-all
16904 current
16905 (time-to-days (current-time))))
16906 sday (calendar-absolute-from-gregorian start)
16907 cday (calendar-absolute-from-gregorian current))
16909 (if (<= cday sday) (throw 'exit sday))
16911 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
16912 (setq dn (string-to-number (match-string 1 change))
16913 dw (cdr (assoc (match-string 2 change) a1)))
16914 (error "Invalid change specifyer: %s" change))
16915 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
16916 (cond
16917 ((eq dw 'day)
16918 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
16919 n2 (+ n1 dn)))
16920 ((eq dw 'year)
16921 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
16922 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
16923 (setq date1 (list m d y1)
16924 n1 (calendar-absolute-from-gregorian date1)
16925 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
16926 n2 (calendar-absolute-from-gregorian date2)))
16927 ((eq dw 'month)
16928 ;; approx number of month between the tow dates
16929 (setq nmonths (floor (/ (- cday sday) 30.436875)))
16930 ;; How often does dn fit in there?
16931 (setq d (nth 1 start) m (car start) y (nth 2 start)
16932 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
16933 m (+ m nm)
16934 ny (floor (/ m 12))
16935 y (+ y ny)
16936 m (- m (* ny 12)))
16937 (while (> m 12) (setq m (- m 12) y (1+ y)))
16938 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
16939 (setq m2 (+ m dn) y2 y)
16940 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16941 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
16942 (while (< n2 cday)
16943 (setq n1 n2 m m2 y y2)
16944 (setq m2 (+ m dn) y2 y)
16945 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
16946 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
16948 (if org-agenda-repeating-timestamp-show-all
16949 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
16950 (if (= cday n1) n1 n2)))))
16952 (defun org-date-to-gregorian (date)
16953 "Turn any specification of DATE into a gregorian date for the calendar."
16954 (cond ((integerp date) (calendar-gregorian-from-absolute date))
16955 ((and (listp date) (= (length date) 3)) date)
16956 ((stringp date)
16957 (setq date (org-parse-time-string date))
16958 (list (nth 4 date) (nth 3 date) (nth 5 date)))
16959 ((listp date)
16960 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
16962 (defun org-parse-time-string (s &optional nodefault)
16963 "Parse the standard Org-mode time string.
16964 This should be a lot faster than the normal `parse-time-string'.
16965 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
16966 hour and minute fields will be nil if not given."
16967 (if (string-match org-ts-regexp0 s)
16968 (list 0
16969 (if (or (match-beginning 8) (not nodefault))
16970 (string-to-number (or (match-string 8 s) "0")))
16971 (if (or (match-beginning 7) (not nodefault))
16972 (string-to-number (or (match-string 7 s) "0")))
16973 (string-to-number (match-string 4 s))
16974 (string-to-number (match-string 3 s))
16975 (string-to-number (match-string 2 s))
16976 nil nil nil)
16977 (make-list 9 0)))
16979 (defun org-timestamp-up (&optional arg)
16980 "Increase the date item at the cursor by one.
16981 If the cursor is on the year, change the year. If it is on the month or
16982 the day, change that.
16983 With prefix ARG, change by that many units."
16984 (interactive "p")
16985 (org-timestamp-change (prefix-numeric-value arg)))
16987 (defun org-timestamp-down (&optional arg)
16988 "Decrease the date item at the cursor by one.
16989 If the cursor is on the year, change the year. If it is on the month or
16990 the day, change that.
16991 With prefix ARG, change by that many units."
16992 (interactive "p")
16993 (org-timestamp-change (- (prefix-numeric-value arg))))
16995 (defun org-timestamp-up-day (&optional arg)
16996 "Increase the date in the time stamp by one day.
16997 With prefix ARG, change that many days."
16998 (interactive "p")
16999 (if (and (not (org-at-timestamp-p t))
17000 (org-on-heading-p))
17001 (org-todo 'up)
17002 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17004 (defun org-timestamp-down-day (&optional arg)
17005 "Decrease the date in the time stamp by one day.
17006 With prefix ARG, change that many days."
17007 (interactive "p")
17008 (if (and (not (org-at-timestamp-p t))
17009 (org-on-heading-p))
17010 (org-todo 'down)
17011 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17013 (defsubst org-pos-in-match-range (pos n)
17014 (and (match-beginning n)
17015 (<= (match-beginning n) pos)
17016 (>= (match-end n) pos)))
17018 (defun org-at-timestamp-p (&optional inactive-ok)
17019 "Determine if the cursor is in or at a timestamp."
17020 (interactive)
17021 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17022 (pos (point))
17023 (ans (or (looking-at tsr)
17024 (save-excursion
17025 (skip-chars-backward "^[<\n\r\t")
17026 (if (> (point) (point-min)) (backward-char 1))
17027 (and (looking-at tsr)
17028 (> (- (match-end 0) pos) -1))))))
17029 (and ans
17030 (boundp 'org-ts-what)
17031 (setq org-ts-what
17032 (cond
17033 ((= pos (match-beginning 0)) 'bracket)
17034 ((= pos (1- (match-end 0))) 'bracket)
17035 ((org-pos-in-match-range pos 2) 'year)
17036 ((org-pos-in-match-range pos 3) 'month)
17037 ((org-pos-in-match-range pos 7) 'hour)
17038 ((org-pos-in-match-range pos 8) 'minute)
17039 ((or (org-pos-in-match-range pos 4)
17040 (org-pos-in-match-range pos 5)) 'day)
17041 ((and (> pos (or (match-end 8) (match-end 5)))
17042 (< pos (match-end 0)))
17043 (- pos (or (match-end 8) (match-end 5))))
17044 (t 'day))))
17045 ans))
17047 (defun org-toggle-timestamp-type ()
17049 (interactive)
17050 (when (org-at-timestamp-p t)
17051 (save-excursion
17052 (goto-char (match-beginning 0))
17053 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17054 (goto-char (1- (match-end 0)))
17055 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17056 (message "Timestamp is now %sactive"
17057 (if (equal (char-before) ?>) "in" ""))))
17059 (defun org-timestamp-change (n &optional what)
17060 "Change the date in the time stamp at point.
17061 The date will be changed by N times WHAT. WHAT can be `day', `month',
17062 `year', `minute', `second'. If WHAT is not given, the cursor position
17063 in the timestamp determines what will be changed."
17064 (let ((pos (point))
17065 with-hm inactive
17066 org-ts-what
17067 extra
17068 ts time time0)
17069 (if (not (org-at-timestamp-p t))
17070 (error "Not at a timestamp"))
17071 (if (and (not what) (eq org-ts-what 'bracket))
17072 (org-toggle-timestamp-type)
17073 (if (and (not what) (not (eq org-ts-what 'day))
17074 org-display-custom-times
17075 (get-text-property (point) 'display)
17076 (not (get-text-property (1- (point)) 'display)))
17077 (setq org-ts-what 'day))
17078 (setq org-ts-what (or what org-ts-what)
17079 inactive (= (char-after (match-beginning 0)) ?\[)
17080 ts (match-string 0))
17081 (replace-match "")
17082 (if (string-match
17083 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17085 (setq extra (match-string 1 ts)))
17086 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17087 (setq with-hm t))
17088 (setq time0 (org-parse-time-string ts))
17089 (setq time
17090 (encode-time (or (car time0) 0)
17091 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17092 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17093 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17094 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17095 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17096 (nthcdr 6 time0)))
17097 (when (integerp org-ts-what)
17098 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17099 (if (eq what 'calendar)
17100 (let ((cal-date (org-get-date-from-calendar)))
17101 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17102 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17103 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17104 (setcar time0 (or (car time0) 0))
17105 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17106 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17107 (setq time (apply 'encode-time time0))))
17108 (setq org-last-changed-timestamp
17109 (org-insert-time-stamp time with-hm inactive nil nil extra))
17110 (org-clock-update-time-maybe)
17111 (goto-char pos)
17112 ;; Try to recenter the calendar window, if any
17113 (if (and org-calendar-follow-timestamp-change
17114 (get-buffer-window "*Calendar*" t)
17115 (memq org-ts-what '(day month year)))
17116 (org-recenter-calendar (time-to-days time))))))
17118 ;; FIXME: does not yet work for lead times
17119 (defun org-modify-ts-extra (s pos n)
17120 "Change the different parts of the lead-time and repeat fields in timestamp."
17121 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17122 ng h m new)
17123 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17124 (cond
17125 ((or (org-pos-in-match-range pos 2)
17126 (org-pos-in-match-range pos 3))
17127 (setq m (string-to-number (match-string 3 s))
17128 h (string-to-number (match-string 2 s)))
17129 (if (org-pos-in-match-range pos 2)
17130 (setq h (+ h n))
17131 (setq m (+ m n)))
17132 (if (< m 0) (setq m (+ m 60) h (1- h)))
17133 (if (> m 59) (setq m (- m 60) h (1+ h)))
17134 (setq h (min 24 (max 0 h)))
17135 (setq ng 1 new (format "-%02d:%02d" h m)))
17136 ((org-pos-in-match-range pos 6)
17137 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17138 ((org-pos-in-match-range pos 5)
17139 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17141 (when ng
17142 (setq s (concat
17143 (substring s 0 (match-beginning ng))
17145 (substring s (match-end ng))))))
17148 (defun org-recenter-calendar (date)
17149 "If the calendar is visible, recenter it to DATE."
17150 (let* ((win (selected-window))
17151 (cwin (get-buffer-window "*Calendar*" t))
17152 (calendar-move-hook nil))
17153 (when cwin
17154 (select-window cwin)
17155 (calendar-goto-date (if (listp date) date
17156 (calendar-gregorian-from-absolute date)))
17157 (select-window win))))
17159 (defun org-goto-calendar (&optional arg)
17160 "Go to the Emacs calendar at the current date.
17161 If there is a time stamp in the current line, go to that date.
17162 A prefix ARG can be used to force the current date."
17163 (interactive "P")
17164 (let ((tsr org-ts-regexp) diff
17165 (calendar-move-hook nil)
17166 (view-calendar-holidays-initially nil)
17167 (view-diary-entries-initially nil))
17168 (if (or (org-at-timestamp-p)
17169 (save-excursion
17170 (beginning-of-line 1)
17171 (looking-at (concat ".*" tsr))))
17172 (let ((d1 (time-to-days (current-time)))
17173 (d2 (time-to-days
17174 (org-time-string-to-time (match-string 1)))))
17175 (setq diff (- d2 d1))))
17176 (calendar)
17177 (calendar-goto-today)
17178 (if (and diff (not arg)) (calendar-forward-day diff))))
17180 (defun org-get-date-from-calendar ()
17181 "Return a list (month day year) of date at point in calendar."
17182 (with-current-buffer "*Calendar*"
17183 (save-match-data
17184 (calendar-cursor-to-date))))
17186 (defun org-date-from-calendar ()
17187 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17188 If there is already a time stamp at the cursor position, update it."
17189 (interactive)
17190 (if (org-at-timestamp-p t)
17191 (org-timestamp-change 0 'calendar)
17192 (let ((cal-date (org-get-date-from-calendar)))
17193 (org-insert-time-stamp
17194 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17196 ;; Make appt aware of appointments from the agenda
17197 ;;;###autoload
17198 (defun org-agenda-to-appt (&optional filter)
17199 "Activate appointments found in `org-agenda-files'.
17200 When prefixed, prompt for a regular expression and use it as a
17201 filter: only add entries if they match this regular expression.
17203 FILTER can be a string. In this case, use this string as a
17204 regular expression to filter results.
17206 FILTER can also be an alist, with the car of each cell being
17207 either 'headline or 'category. For example:
17209 '((headline \"IMPORTANT\")
17210 (category \"Work\"))
17212 will only add headlines containing IMPORTANT or headlines
17213 belonging to the category \"Work\"."
17214 (interactive "P")
17215 (require 'calendar)
17216 (if (equal filter '(4))
17217 (setq filter (read-from-minibuffer "Regexp filter: ")))
17218 (let* ((cnt 0) ; count added events
17219 (today (org-date-to-gregorian
17220 (time-to-days (current-time))))
17221 (files (org-agenda-files)) entries file)
17222 ;; Get all entries which may contain an appt
17223 (while (setq file (pop files))
17224 (setq entries
17225 (append entries
17226 (org-agenda-get-day-entries
17227 file today
17228 :timestamp :scheduled :deadline))))
17229 (setq entries (delq nil entries))
17230 ;; Map thru entries and find if they pass thru the filter
17231 (mapc
17232 (lambda(x)
17233 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17234 (cat (get-text-property 1 'org-category x))
17235 (tod (get-text-property 1 'time-of-day x))
17236 (ok (or (null filter)
17237 (and (stringp filter) (string-match filter evt))
17238 (and (listp filter)
17239 (or (string-match
17240 (cadr (assoc 'category filter)) cat)
17241 (string-match
17242 (cadr (assoc 'headline filter)) evt))))))
17243 ;; FIXME Shall we remove text-properties for the appt text?
17244 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17245 (when (and ok tod)
17246 (setq tod (number-to-string tod)
17247 tod (when (string-match
17248 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17249 (concat (match-string 1 tod) ":"
17250 (match-string 2 tod))))
17251 (appt-add tod evt)
17252 (setq cnt (1+ cnt))))) entries)
17253 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17255 ;;; The clock for measuring work time.
17257 (defvar org-mode-line-string "")
17258 (put 'org-mode-line-string 'risky-local-variable t)
17260 (defvar org-mode-line-timer nil)
17261 (defvar org-clock-heading "")
17262 (defvar org-clock-start-time "")
17264 (defun org-update-mode-line ()
17265 (let* ((delta (- (time-to-seconds (current-time))
17266 (time-to-seconds org-clock-start-time)))
17267 (h (floor delta 3600))
17268 (m (floor (- delta (* 3600 h)) 60)))
17269 (setq org-mode-line-string
17270 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17271 'help-echo "Org-mode clock is running"))
17272 (force-mode-line-update)))
17274 (defvar org-clock-marker (make-marker)
17275 "Marker recording the last clock-in.")
17276 (defvar org-clock-mode-line-entry nil
17277 "Information for the modeline about the running clock.")
17279 (defun org-clock-in ()
17280 "Start the clock on the current item.
17281 If necessary, clock-out of the currently active clock."
17282 (interactive)
17283 (org-clock-out t)
17284 (let (ts)
17285 (save-excursion
17286 (org-back-to-heading t)
17287 (if (looking-at org-todo-line-regexp)
17288 (setq org-clock-heading (match-string 3))
17289 (setq org-clock-heading "???"))
17290 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17291 (org-clock-find-position)
17293 (insert "\n") (backward-char 1)
17294 (indent-relative)
17295 (insert org-clock-string " ")
17296 (setq org-clock-start-time (current-time))
17297 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17298 (move-marker org-clock-marker (point) (buffer-base-buffer))
17299 (or global-mode-string (setq global-mode-string '("")))
17300 (or (memq 'org-mode-line-string global-mode-string)
17301 (setq global-mode-string
17302 (append global-mode-string '(org-mode-line-string))))
17303 (org-update-mode-line)
17304 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17305 (message "Clock started at %s" ts))))
17307 (defun org-clock-find-position ()
17308 "Find the location where the next clock line should be inserted."
17309 (org-back-to-heading t)
17310 (catch 'exit
17311 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17312 (re (concat "^[ \t]*" org-clock-string))
17313 (cnt 0)
17314 first last)
17315 (goto-char beg)
17316 (when (eobp) (newline) (setq end (max (point) end)))
17317 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17318 ;; we seem to have a CLOCK drawer, so go there.
17319 (beginning-of-line 2)
17320 (throw 'exit t))
17321 ;; Lets count the CLOCK lines
17322 (goto-char beg)
17323 (while (re-search-forward re end t)
17324 (setq first (or first (match-beginning 0))
17325 last (match-beginning 0)
17326 cnt (1+ cnt)))
17327 (when (and (integerp org-clock-into-drawer)
17328 (>= (1+ cnt) org-clock-into-drawer))
17329 ;; Wrap current entries into a new drawer
17330 (goto-char last)
17331 (beginning-of-line 2)
17332 (if (org-at-item-p) (org-end-of-item))
17333 (insert ":END:\n")
17334 (beginning-of-line 0)
17335 (org-indent-line-function)
17336 (goto-char first)
17337 (insert ":CLOCK:\n")
17338 (beginning-of-line 0)
17339 (org-indent-line-function)
17340 (org-flag-drawer t)
17341 (beginning-of-line 2)
17342 (throw 'exit nil))
17344 (goto-char beg)
17345 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17346 (not (equal (match-string 1) org-clock-string)))
17347 ;; Planning info, skip to after it
17348 (beginning-of-line 2)
17349 (or (bolp) (newline)))
17350 (when (eq t org-clock-into-drawer)
17351 (insert ":CLOCK:\n:END:\n")
17352 (beginning-of-line -1)
17353 (org-indent-line-function)
17354 (org-flag-drawer t)
17355 (beginning-of-line 2)
17356 (org-indent-line-function)))))
17358 (defun org-clock-out (&optional fail-quietly)
17359 "Stop the currently running clock.
17360 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
17361 (interactive)
17362 (catch 'exit
17363 (if (not (marker-buffer org-clock-marker))
17364 (if fail-quietly (throw 'exit t) (error "No active clock")))
17365 (let (ts te s h m)
17366 (save-excursion
17367 (set-buffer (marker-buffer org-clock-marker))
17368 (goto-char org-clock-marker)
17369 (beginning-of-line 1)
17370 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17371 (equal (match-string 1) org-clock-string))
17372 (setq ts (match-string 2))
17373 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
17374 (goto-char (match-end 0))
17375 (delete-region (point) (point-at-eol))
17376 (insert "--")
17377 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17378 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
17379 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
17380 h (floor (/ s 3600))
17381 s (- s (* 3600 h))
17382 m (floor (/ s 60))
17383 s (- s (* 60 s)))
17384 (insert " => " (format "%2d:%02d" h m))
17385 (move-marker org-clock-marker nil)
17386 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
17387 (org-log-done (org-parse-local-options logging 'org-log-done))
17388 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
17389 (org-add-log-maybe 'clock-out))
17390 (when org-mode-line-timer
17391 (cancel-timer org-mode-line-timer)
17392 (setq org-mode-line-timer nil))
17393 (setq global-mode-string
17394 (delq 'org-mode-line-string global-mode-string))
17395 (force-mode-line-update)
17396 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
17398 (defun org-clock-cancel ()
17399 "Cancel the running clock be removing the start timestamp."
17400 (interactive)
17401 (if (not (marker-buffer org-clock-marker))
17402 (error "No active clock"))
17403 (save-excursion
17404 (set-buffer (marker-buffer org-clock-marker))
17405 (goto-char org-clock-marker)
17406 (delete-region (1- (point-at-bol)) (point-at-eol)))
17407 (message "Clock canceled"))
17409 (defun org-clock-goto (&optional delete-windows)
17410 "Go to the currently clocked-in entry."
17411 (interactive "P")
17412 (if (not (marker-buffer org-clock-marker))
17413 (error "No active clock"))
17414 (switch-to-buffer-other-window
17415 (marker-buffer org-clock-marker))
17416 (if delete-windows (delete-other-windows))
17417 (goto-char org-clock-marker)
17418 (org-show-entry)
17419 (org-back-to-heading)
17420 (recenter))
17422 (defvar org-clock-file-total-minutes nil
17423 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
17424 (make-variable-buffer-local 'org-clock-file-total-minutes)
17426 (defun org-clock-sum (&optional tstart tend)
17427 "Sum the times for each subtree.
17428 Puts the resulting times in minutes as a text property on each headline."
17429 (interactive)
17430 (let* ((bmp (buffer-modified-p))
17431 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
17432 org-clock-string
17433 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
17434 (lmax 30)
17435 (ltimes (make-vector lmax 0))
17436 (t1 0)
17437 (level 0)
17438 ts te dt
17439 time)
17440 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
17441 (save-excursion
17442 (goto-char (point-max))
17443 (while (re-search-backward re nil t)
17444 (cond
17445 ((match-end 2)
17446 ;; Two time stamps
17447 (setq ts (match-string 2)
17448 te (match-string 3)
17449 ts (time-to-seconds
17450 (apply 'encode-time (org-parse-time-string ts)))
17451 te (time-to-seconds
17452 (apply 'encode-time (org-parse-time-string te)))
17453 ts (if tstart (max ts tstart) ts)
17454 te (if tend (min te tend) te)
17455 dt (- te ts)
17456 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
17457 ((match-end 4)
17458 ;; A naket time
17459 (setq t1 (+ t1 (string-to-number (match-string 5))
17460 (* 60 (string-to-number (match-string 4))))))
17461 (t ;; A headline
17462 (setq level (- (match-end 1) (match-beginning 1)))
17463 (when (or (> t1 0) (> (aref ltimes level) 0))
17464 (loop for l from 0 to level do
17465 (aset ltimes l (+ (aref ltimes l) t1)))
17466 (setq t1 0 time (aref ltimes level))
17467 (loop for l from level to (1- lmax) do
17468 (aset ltimes l 0))
17469 (goto-char (match-beginning 0))
17470 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
17471 (setq org-clock-file-total-minutes (aref ltimes 0)))
17472 (set-buffer-modified-p bmp)))
17474 (defun org-clock-display (&optional total-only)
17475 "Show subtree times in the entire buffer.
17476 If TOTAL-ONLY is non-nil, only show the total time for the entire file
17477 in the echo area."
17478 (interactive)
17479 (org-remove-clock-overlays)
17480 (let (time h m p)
17481 (org-clock-sum)
17482 (unless total-only
17483 (save-excursion
17484 (goto-char (point-min))
17485 (while (or (and (equal (setq p (point)) (point-min))
17486 (get-text-property p :org-clock-minutes))
17487 (setq p (next-single-property-change
17488 (point) :org-clock-minutes)))
17489 (goto-char p)
17490 (when (setq time (get-text-property p :org-clock-minutes))
17491 (org-put-clock-overlay time (funcall outline-level))))
17492 (setq h (/ org-clock-file-total-minutes 60)
17493 m (- org-clock-file-total-minutes (* 60 h)))
17494 ;; Arrange to remove the overlays upon next change.
17495 (when org-remove-highlights-with-change
17496 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
17497 nil 'local))))
17498 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
17500 (defvar org-clock-overlays nil)
17501 (make-variable-buffer-local 'org-clock-overlays)
17503 (defun org-put-clock-overlay (time &optional level)
17504 "Put an overlays on the current line, displaying TIME.
17505 If LEVEL is given, prefix time with a corresponding number of stars.
17506 This creates a new overlay and stores it in `org-clock-overlays', so that it
17507 will be easy to remove."
17508 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
17509 (l (if level (org-get-legal-level level 0) 0))
17510 (off 0)
17511 ov tx)
17512 (move-to-column c)
17513 (unless (eolp) (skip-chars-backward "^ \t"))
17514 (skip-chars-backward " \t")
17515 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
17516 tx (concat (buffer-substring (1- (point)) (point))
17517 (make-string (+ off (max 0 (- c (current-column)))) ?.)
17518 (org-add-props (format "%s %2d:%02d%s"
17519 (make-string l ?*) h m
17520 (make-string (- 10 l) ?\ ))
17521 '(face secondary-selection))
17522 ""))
17523 (if (not (featurep 'xemacs))
17524 (org-overlay-put ov 'display tx)
17525 (org-overlay-put ov 'invisible t)
17526 (org-overlay-put ov 'end-glyph (make-glyph tx)))
17527 (push ov org-clock-overlays)))
17529 (defun org-remove-clock-overlays (&optional beg end noremove)
17530 "Remove the occur highlights from the buffer.
17531 BEG and END are ignored. If NOREMOVE is nil, remove this function
17532 from the `before-change-functions' in the current buffer."
17533 (interactive)
17534 (unless org-inhibit-highlight-removal
17535 (mapc 'org-delete-overlay org-clock-overlays)
17536 (setq org-clock-overlays nil)
17537 (unless noremove
17538 (remove-hook 'before-change-functions
17539 'org-remove-clock-overlays 'local))))
17541 (defun org-clock-out-if-current ()
17542 "Clock out if the current entry contains the running clock.
17543 This is used to stop the clock after a TODO entry is marked DONE,
17544 and is only done if the variable `org-clock-out-when-done' is not nil."
17545 (when (and org-clock-out-when-done
17546 (member state org-done-keywords)
17547 (equal (marker-buffer org-clock-marker) (current-buffer))
17548 (< (point) org-clock-marker)
17549 (> (save-excursion (outline-next-heading) (point))
17550 org-clock-marker))
17551 ;; Clock out, but don't accept a logging message for this.
17552 (let ((org-log-done (if (and (listp org-log-done)
17553 (member 'clock-out org-log-done))
17554 '(done)
17555 org-log-done)))
17556 (org-clock-out))))
17558 (add-hook 'org-after-todo-state-change-hook
17559 'org-clock-out-if-current)
17561 (defun org-check-running-clock ()
17562 "Check if the current buffer contains the running clock.
17563 If yes, offer to stop it and to save the buffer with the changes."
17564 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
17565 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
17566 (buffer-name))))
17567 (org-clock-out)
17568 (when (y-or-n-p "Save changed buffer?")
17569 (save-buffer))))
17571 (defun org-clock-report (&optional arg)
17572 "Create a table containing a report about clocked time.
17573 If the cursor is inside an existing clocktable block, then the table
17574 will be updated. If not, a new clocktable will be inserted.
17575 When called with a prefix argument, move to the first clock table in the
17576 buffer and update it."
17577 (interactive "P")
17578 (org-remove-clock-overlays)
17579 (when arg (org-find-dblock "clocktable"))
17580 (if (org-in-clocktable-p)
17581 (goto-char (org-in-clocktable-p))
17582 (org-create-dblock (list :name "clocktable"
17583 :maxlevel 2 :scope 'file)))
17584 (org-update-dblock))
17586 (defun org-in-clocktable-p ()
17587 "Check if the cursor is in a clocktable."
17588 (let ((pos (point)) start)
17589 (save-excursion
17590 (end-of-line 1)
17591 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
17592 (setq start (match-beginning 0))
17593 (re-search-forward "^#\\+END:.*" nil t)
17594 (>= (match-end 0) pos)
17595 start))))
17597 (defun org-clock-update-time-maybe ()
17598 "If this is a CLOCK line, update it and return t.
17599 Otherwise, return nil."
17600 (interactive)
17601 (save-excursion
17602 (beginning-of-line 1)
17603 (skip-chars-forward " \t")
17604 (when (looking-at org-clock-string)
17605 (let ((re (concat "[ \t]*" org-clock-string
17606 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
17607 "\\([ \t]*=>.*\\)?"))
17608 ts te h m s)
17609 (if (not (looking-at re))
17611 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
17612 (end-of-line 1)
17613 (setq ts (match-string 1)
17614 te (match-string 2))
17615 (setq s (- (time-to-seconds
17616 (apply 'encode-time (org-parse-time-string te)))
17617 (time-to-seconds
17618 (apply 'encode-time (org-parse-time-string ts))))
17619 h (floor (/ s 3600))
17620 s (- s (* 3600 h))
17621 m (floor (/ s 60))
17622 s (- s (* 60 s)))
17623 (insert " => " (format "%2d:%02d" h m))
17624 t)))))
17626 (defun org-clock-special-range (key &optional time as-strings)
17627 "Return two times bordering a special time range.
17628 Key is a symbol specifying the range and can be one of `today', `yesterday',
17629 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
17630 A week starts Monday 0:00 and ends Sunday 24:00.
17631 The range is determined relative to TIME. TIME defaults to the current time.
17632 The return value is a cons cell with two internal times like the ones
17633 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
17634 the returned times will be formatted strings."
17635 (let* ((tm (decode-time (or time (current-time))))
17636 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
17637 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
17638 (dow (nth 6 tm))
17639 s1 m1 h1 d1 month1 y1 diff ts te fm)
17640 (cond
17641 ((eq key 'today)
17642 (setq h 0 m 0 h1 24 m1 0))
17643 ((eq key 'yesterday)
17644 (setq d (1- d) h 0 m 0 h1 24 m1 0))
17645 ((eq key 'thisweek)
17646 (setq diff (if (= dow 0) 6 (1- dow))
17647 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17648 ((eq key 'lastweek)
17649 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
17650 m 0 h 0 d (- d diff) d1 (+ 7 d)))
17651 ((eq key 'thismonth)
17652 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
17653 ((eq key 'lastmonth)
17654 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
17655 ((eq key 'thisyear)
17656 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
17657 ((eq key 'lastyear)
17658 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
17659 (t (error "No such time block %s" key)))
17660 (setq ts (encode-time s m h d month y)
17661 te (encode-time (or s1 s) (or m1 m) (or h1 h)
17662 (or d1 d) (or month1 month) (or y1 y)))
17663 (setq fm (cdr org-time-stamp-formats))
17664 (if as-strings
17665 (cons (format-time-string fm ts) (format-time-string fm te))
17666 (cons ts te))))
17668 (defun org-dblock-write:clocktable (params)
17669 "Write the standard clocktable."
17670 (let ((hlchars '((1 . "*") (2 . "/")))
17671 (emph nil)
17672 (ins (make-marker))
17673 (total-time nil)
17674 ipos time h m p level hlc hdl maxlevel
17675 ts te cc block beg end pos scope tbl tostring multifile)
17676 (setq scope (plist-get params :scope)
17677 tostring (plist-get params :tostring)
17678 multifile (plist-get params :multifile)
17679 maxlevel (or (plist-get params :maxlevel) 3)
17680 emph (plist-get params :emphasize)
17681 ts (plist-get params :tstart)
17682 te (plist-get params :tend)
17683 block (plist-get params :block))
17684 (when block
17685 (setq cc (org-clock-special-range block nil t)
17686 ts (car cc) te (cdr cc)))
17687 (if ts (setq ts (time-to-seconds
17688 (apply 'encode-time (org-parse-time-string ts)))))
17689 (if te (setq te (time-to-seconds
17690 (apply 'encode-time (org-parse-time-string te)))))
17691 (move-marker ins (point))
17692 (setq ipos (point))
17694 ;; Get the right scope
17695 (setq pos (point))
17696 (save-restriction
17697 (cond
17698 ((not scope))
17699 ((eq scope 'file) (widen))
17700 ((eq scope 'subtree) (org-narrow-to-subtree))
17701 ((eq scope 'tree)
17702 (while (org-up-heading-safe))
17703 (org-narrow-to-subtree))
17704 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
17705 (symbol-name scope)))
17706 (setq level (string-to-number (match-string 1 (symbol-name scope))))
17707 (catch 'exit
17708 (while (org-up-heading-safe)
17709 (looking-at outline-regexp)
17710 (if (<= (org-reduced-level (funcall outline-level)) level)
17711 (throw 'exit nil))))
17712 (org-narrow-to-subtree))
17713 ((or (listp scope) (eq scope 'agenda))
17714 (let* ((files (if (listp scope) scope (org-agenda-files)))
17715 (scope 'agenda)
17716 (p1 (copy-sequence params))
17717 file)
17718 (plist-put p1 :tostring t)
17719 (plist-put p1 :multifile t)
17720 (plist-put p1 :scope 'file)
17721 (org-prepare-agenda-buffers files)
17722 (while (setq file (pop files))
17723 (with-current-buffer (find-buffer-visiting file)
17724 (push (org-clocktable-add-file
17725 file (org-dblock-write:clocktable p1)) tbl)
17726 (setq total-time (+ (or total-time 0)
17727 org-clock-file-total-minutes)))))))
17728 (goto-char pos)
17730 (unless (eq scope 'agenda)
17731 (org-clock-sum ts te)
17732 (goto-char (point-min))
17733 (while (setq p (next-single-property-change (point) :org-clock-minutes))
17734 (goto-char p)
17735 (when (setq time (get-text-property p :org-clock-minutes))
17736 (save-excursion
17737 (beginning-of-line 1)
17738 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
17739 (setq level (org-reduced-level
17740 (- (match-end 1) (match-beginning 1))))
17741 (<= level maxlevel))
17742 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
17743 hdl (match-string 2)
17744 h (/ time 60)
17745 m (- time (* 60 h)))
17746 (if (and (not multifile) (= level 1)) (push "|-" tbl))
17747 (push (concat
17748 "| " (int-to-string level) "|" hlc hdl hlc " |"
17749 (make-string (1- level) ?|)
17750 hlc (format "%d:%02d" h m) hlc
17751 " |") tbl))))))
17752 (setq tbl (nreverse tbl))
17753 (if tostring
17754 (if tbl (mapconcat 'identity tbl "\n") nil)
17755 (goto-char ins)
17756 (insert-before-markers
17757 "Clock summary at ["
17758 (substring
17759 (format-time-string (cdr org-time-stamp-formats))
17760 1 -1)
17761 "]."
17762 (if block
17763 (format " Considered range is /%s/." block)
17765 "\n\n"
17766 (if (eq scope 'agenda) "|File" "")
17767 "|L|Headline|Time|\n")
17768 (setq total-time (or total-time org-clock-file-total-minutes)
17769 h (/ total-time 60)
17770 m (- total-time (* 60 h)))
17771 (insert-before-markers
17772 "|-\n|"
17773 (if (eq scope 'agenda) "|" "")
17775 "*Total time*| "
17776 (format "*%d:%02d*" h m)
17777 "|\n|-\n")
17778 (setq tbl (delq nil tbl))
17779 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
17780 (equal (substring (car tbl) 0 2) "|-"))
17781 (pop tbl))
17782 (insert-before-markers (mapconcat
17783 'identity (delq nil tbl)
17784 (if (eq scope 'agenda) "\n|-\n" "\n")))
17785 (backward-delete-char 1)
17786 (goto-char ipos)
17787 (skip-chars-forward "^|")
17788 (org-table-align)))))
17790 (defun org-clocktable-add-file (file table)
17791 (if table
17792 (let ((lines (org-split-string table "\n"))
17793 (ff (file-name-nondirectory file)))
17794 (mapconcat 'identity
17795 (mapcar (lambda (x)
17796 (if (string-match org-table-dataline-regexp x)
17797 (concat "|" ff x)
17799 lines)
17800 "\n"))))
17802 ;; FIXME: I don't think anybody uses this, ask David
17803 (defun org-collect-clock-time-entries ()
17804 "Return an internal list with clocking information.
17805 This list has one entry for each CLOCK interval.
17806 FIXME: describe the elements."
17807 (interactive)
17808 (let ((re (concat "^[ \t]*" org-clock-string
17809 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
17810 rtn beg end next cont level title total closedp leafp
17811 clockpos titlepos h m donep)
17812 (save-excursion
17813 (org-clock-sum)
17814 (goto-char (point-min))
17815 (while (re-search-forward re nil t)
17816 (setq clockpos (match-beginning 0)
17817 beg (match-string 1) end (match-string 2)
17818 cont (match-end 0))
17819 (setq beg (apply 'encode-time (org-parse-time-string beg))
17820 end (apply 'encode-time (org-parse-time-string end)))
17821 (org-back-to-heading t)
17822 (setq donep (org-entry-is-done-p))
17823 (setq titlepos (point)
17824 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
17825 h (/ total 60) m (- total (* 60 h))
17826 total (cons h m))
17827 (looking-at "\\(\\*+\\) +\\(.*\\)")
17828 (setq level (- (match-end 1) (match-beginning 1))
17829 title (org-match-string-no-properties 2))
17830 (save-excursion (outline-next-heading) (setq next (point)))
17831 (setq closedp (re-search-forward org-closed-time-regexp next t))
17832 (goto-char next)
17833 (setq leafp (and (looking-at "^\\*+ ")
17834 (<= (- (match-end 0) (point)) level)))
17835 (push (list beg end clockpos closedp donep
17836 total title titlepos level leafp)
17837 rtn)
17838 (goto-char cont)))
17839 (nreverse rtn)))
17841 ;;;; Agenda, and Diary Integration
17843 ;;; Define the Org-agenda-mode
17845 (defvar org-agenda-mode-map (make-sparse-keymap)
17846 "Keymap for `org-agenda-mode'.")
17848 (defvar org-agenda-menu) ; defined later in this file.
17849 (defvar org-agenda-follow-mode nil)
17850 (defvar org-agenda-show-log nil)
17851 (defvar org-agenda-redo-command nil)
17852 (defvar org-agenda-mode-hook nil)
17853 (defvar org-agenda-type nil)
17854 (defvar org-agenda-force-single-file nil)
17856 (defun org-agenda-mode ()
17857 "Mode for time-sorted view on action items in Org-mode files.
17859 The following commands are available:
17861 \\{org-agenda-mode-map}"
17862 (interactive)
17863 (kill-all-local-variables)
17864 (setq org-agenda-undo-list nil
17865 org-agenda-pending-undo-list nil)
17866 (setq major-mode 'org-agenda-mode)
17867 ;; Keep global-font-lock-mode from turning on font-lock-mode
17868 (org-set-local 'font-lock-global-modes (list 'not major-mode))
17869 (setq mode-name "Org-Agenda")
17870 (use-local-map org-agenda-mode-map)
17871 (easy-menu-add org-agenda-menu)
17872 (if org-startup-truncated (setq truncate-lines t))
17873 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
17874 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
17875 ;; Make sure properties are removed when copying text
17876 (when (boundp 'buffer-substring-filters)
17877 (org-set-local 'buffer-substring-filters
17878 (cons (lambda (x)
17879 (set-text-properties 0 (length x) nil x) x)
17880 buffer-substring-filters)))
17881 (unless org-agenda-keep-modes
17882 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
17883 org-agenda-show-log nil))
17884 (easy-menu-change
17885 '("Agenda") "Agenda Files"
17886 (append
17887 (list
17888 (vector
17889 (if (get 'org-agenda-files 'org-restrict)
17890 "Restricted to single file"
17891 "Edit File List")
17892 '(org-edit-agenda-file-list)
17893 (not (get 'org-agenda-files 'org-restrict)))
17894 "--")
17895 (mapcar 'org-file-menu-entry (org-agenda-files))))
17896 (org-agenda-set-mode-name)
17897 (apply
17898 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
17899 (list 'org-agenda-mode-hook)))
17901 (substitute-key-definition 'undo 'org-agenda-undo
17902 org-agenda-mode-map global-map)
17903 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
17904 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
17905 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
17906 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
17907 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
17908 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
17909 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
17910 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
17911 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
17912 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
17913 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
17914 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
17915 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
17916 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
17917 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
17918 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
17919 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
17920 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
17921 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
17922 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
17923 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
17924 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
17925 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
17926 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
17927 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
17928 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
17929 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
17930 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
17931 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
17933 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
17934 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
17935 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
17936 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
17937 (while l (org-defkey org-agenda-mode-map
17938 (int-to-string (pop l)) 'digit-argument)))
17940 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
17941 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
17942 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
17943 (org-defkey org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
17944 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
17945 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
17946 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
17947 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
17948 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
17949 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
17950 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
17951 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
17952 (org-defkey org-agenda-mode-map "n" 'next-line)
17953 (org-defkey org-agenda-mode-map "p" 'previous-line)
17954 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
17955 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
17956 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
17957 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
17958 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
17959 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
17960 (eval-after-load "calendar"
17961 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
17962 'org-calendar-goto-agenda))
17963 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
17964 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
17965 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
17966 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
17967 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
17968 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
17969 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
17970 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
17971 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
17972 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
17973 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
17974 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
17975 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
17976 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
17977 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
17978 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
17979 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
17980 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
17981 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
17982 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
17983 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
17984 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
17986 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
17987 "Local keymap for agenda entries from Org-mode.")
17989 (org-defkey org-agenda-keymap
17990 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
17991 (org-defkey org-agenda-keymap
17992 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
17993 (when org-agenda-mouse-1-follows-link
17994 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
17995 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
17996 '("Agenda"
17997 ("Agenda Files")
17998 "--"
17999 ["Show" org-agenda-show t]
18000 ["Go To (other window)" org-agenda-goto t]
18001 ["Go To (this window)" org-agenda-switch-to t]
18002 ["Follow Mode" org-agenda-follow-mode
18003 :style toggle :selected org-agenda-follow-mode :active t]
18004 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18005 "--"
18006 ["Cycle TODO" org-agenda-todo t]
18007 ["Archive subtree" org-agenda-archive t]
18008 ["Delete subtree" org-agenda-kill t]
18009 "--"
18010 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18011 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18012 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18013 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18014 "--"
18015 ("Tags and Properties"
18016 ["Show all Tags" org-agenda-show-tags t]
18017 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18018 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18019 "--"
18020 ["Column View" org-columns t])
18021 ("Date/Schedule"
18022 ["Schedule" org-agenda-schedule t]
18023 ["Set Deadline" org-agenda-deadline t]
18024 "--"
18025 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18026 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18027 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18028 ("Clock"
18029 ["Clock in" org-agenda-clock-in t]
18030 ["Clock out" org-agenda-clock-out t]
18031 ["Clock cancel" org-agenda-clock-cancel t]
18032 ["Goto running clock" org-clock-goto t])
18033 ("Priority"
18034 ["Set Priority" org-agenda-priority t]
18035 ["Increase Priority" org-agenda-priority-up t]
18036 ["Decrease Priority" org-agenda-priority-down t]
18037 ["Show Priority" org-agenda-show-priority t])
18038 ("Calendar/Diary"
18039 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18040 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18041 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18042 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18043 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18044 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18045 "--"
18046 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18047 "--"
18048 ("View"
18049 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18050 :style radio :selected (equal org-agenda-ndays 1)]
18051 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18052 :style radio :selected (equal org-agenda-ndays 7)]
18053 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18054 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18055 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18056 :style radio :selected (member org-agenda-ndays '(365 366))]
18057 "--"
18058 ["Show Logbook entries" org-agenda-log-mode
18059 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18060 ["Include Diary" org-agenda-toggle-diary
18061 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18062 ["Use Time Grid" org-agenda-toggle-time-grid
18063 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18064 ["Write view to file" org-write-agenda t]
18065 ["Rebuild buffer" org-agenda-redo t]
18066 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18067 "--"
18068 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18069 "--"
18070 ["Quit" org-agenda-quit t]
18071 ["Exit and Release Buffers" org-agenda-exit t]
18074 ;;; Agenda undo
18076 (defvar org-agenda-allow-remote-undo t
18077 "Non-nil means, allow remote undo from the agenda buffer.")
18078 (defvar org-agenda-undo-list nil
18079 "List of undoable operations in the agenda since last refresh.")
18080 (defvar org-agenda-undo-has-started-in nil
18081 "Buffers that have already seen `undo-start' in the current undo sequence.")
18082 (defvar org-agenda-pending-undo-list nil
18083 "In a series of undo commands, this is the list of remaning undo items.")
18085 (defmacro org-if-unprotected (&rest body)
18086 "Execute BODY if there is no `org-protected' text property at point."
18087 (declare (debug t))
18088 `(unless (get-text-property (point) 'org-protected)
18089 ,@body))
18091 (defmacro org-with-remote-undo (_buffer &rest _body)
18092 "Execute BODY while recording undo information in two buffers."
18093 (declare (indent 1) (debug t))
18094 `(let ((_cline (org-current-line))
18095 (_cmd this-command)
18096 (_buf1 (current-buffer))
18097 (_buf2 ,_buffer)
18098 (_undo1 buffer-undo-list)
18099 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18100 _c1 _c2)
18101 ,@_body
18102 (when org-agenda-allow-remote-undo
18103 (setq _c1 (org-verify-change-for-undo
18104 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18105 _c2 (org-verify-change-for-undo
18106 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18107 (when (or _c1 _c2)
18108 ;; make sure there are undo boundaries
18109 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18110 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18111 ;; remember which buffer to undo
18112 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18113 org-agenda-undo-list)))))
18115 (defun org-agenda-undo ()
18116 "Undo a remote editing step in the agenda.
18117 This undoes changes both in the agenda buffer and in the remote buffer
18118 that have been changed along."
18119 (interactive)
18120 (or org-agenda-allow-remote-undo
18121 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18122 (if (not (eq this-command last-command))
18123 (setq org-agenda-undo-has-started-in nil
18124 org-agenda-pending-undo-list org-agenda-undo-list))
18125 (if (not org-agenda-pending-undo-list)
18126 (error "No further undo information"))
18127 (let* ((entry (pop org-agenda-pending-undo-list))
18128 buf line cmd rembuf)
18129 (setq cmd (pop entry) line (pop entry))
18130 (setq rembuf (nth 2 entry))
18131 (org-with-remote-undo rembuf
18132 (while (bufferp (setq buf (pop entry)))
18133 (if (pop entry)
18134 (with-current-buffer buf
18135 (let ((last-undo-buffer buf)
18136 (inhibit-read-only t))
18137 (unless (memq buf org-agenda-undo-has-started-in)
18138 (push buf org-agenda-undo-has-started-in)
18139 (make-local-variable 'pending-undo-list)
18140 (undo-start))
18141 (while (and pending-undo-list
18142 (listp pending-undo-list)
18143 (not (car pending-undo-list)))
18144 (pop pending-undo-list))
18145 (undo-more 1))))))
18146 (goto-line line)
18147 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18149 (defun org-verify-change-for-undo (l1 l2)
18150 "Verify that a real change occurred between the undo lists L1 and L2."
18151 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18152 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18153 (not (eq l1 l2)))
18155 ;;; Agenda dispatch
18157 (defvar org-agenda-restrict nil)
18158 (defvar org-agenda-restrict-begin (make-marker))
18159 (defvar org-agenda-restrict-end (make-marker))
18160 (defvar org-agenda-last-dispatch-buffer nil)
18162 ;;;###autoload
18163 (defun org-agenda (arg &optional keys restriction)
18164 "Dispatch agenda commands to collect entries to the agenda buffer.
18165 Prompts for a command to execute. Any prefix arg will be passed
18166 on to the selected command. The default selections are:
18168 a Call `org-agenda-list' to display the agenda for current day or week.
18169 t Call `org-todo-list' to display the global todo list.
18170 T Call `org-todo-list' to display the global todo list, select only
18171 entries with a specific TODO keyword (the user gets a prompt).
18172 m Call `org-tags-view' to display headlines with tags matching
18173 a condition (the user is prompted for the condition).
18174 M Like `m', but select only TODO entries, no ordinary headlines.
18175 L Create a timeline for the current buffer.
18176 e Export views to associated files.
18178 More commands can be added by configuring the variable
18179 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18180 searches can be pre-defined in this way.
18182 If the current buffer is in Org-mode and visiting a file, you can also
18183 first press `<' once to indicate that the agenda should be temporarily
18184 \(until the next use of \\[org-agenda]) restricted to the current file.
18185 Pressing `<' twice means to restrict to the current subtree or region
18186 \(if active)."
18187 (interactive "P")
18188 (catch 'exit
18189 (let* ((prefix-descriptions nil)
18190 (org-agenda-custom-commands
18191 ;; normalize different versions
18192 (delq nil
18193 (mapcar
18194 (lambda (x)
18195 (cond ((stringp (cdr x))
18196 (push x prefix-descriptions)
18197 nil)
18198 ((stringp (nth 1 x)) x)
18199 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18200 (t (cons (car x) (cons "" (cdr x))))))
18201 org-agenda-custom-commands)))
18202 (buf (current-buffer))
18203 (bfn (buffer-file-name (buffer-base-buffer)))
18204 entry key type match lprops ans)
18205 ;; Turn off restriction
18206 (put 'org-agenda-files 'org-restrict nil)
18207 (setq org-agenda-restrict nil)
18208 (move-marker org-agenda-restrict-begin nil)
18209 (move-marker org-agenda-restrict-end nil)
18210 ;; Delete old local properties
18211 (put 'org-agenda-redo-command 'org-lprops nil)
18212 ;; Remember where this call originated
18213 (setq org-agenda-last-dispatch-buffer (current-buffer))
18214 (unless keys
18215 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18216 keys (car ans)
18217 restriction (cdr ans)))
18218 ;; Estabish the restriction, if any
18219 (when restriction
18220 (put 'org-agenda-files 'org-restrict (list bfn))
18221 (cond
18222 ((eq restriction 'region)
18223 (setq org-agenda-restrict t)
18224 (move-marker org-agenda-restrict-begin (region-beginning))
18225 (move-marker org-agenda-restrict-end (region-end)))
18226 ((eq restriction 'subtree)
18227 (save-excursion
18228 (setq org-agenda-restrict t)
18229 (org-back-to-heading t)
18230 (move-marker org-agenda-restrict-begin (point))
18231 (move-marker org-agenda-restrict-end
18232 (progn (org-end-of-subtree t)))))))
18234 (require 'calendar) ; FIXME: can we avoid this for some commands?
18235 ;; For example the todo list should not need it (but does...)
18236 (cond
18237 ((setq entry (assoc keys org-agenda-custom-commands))
18238 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18239 (progn
18240 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18241 (put 'org-agenda-redo-command 'org-lprops lprops)
18242 (cond
18243 ((eq type 'agenda)
18244 (org-let lprops '(org-agenda-list current-prefix-arg)))
18245 ((eq type 'alltodo)
18246 (org-let lprops '(org-todo-list current-prefix-arg)))
18247 ((eq type 'stuck)
18248 (org-let lprops '(org-agenda-list-stuck-projects
18249 current-prefix-arg)))
18250 ((eq type 'tags)
18251 (org-let lprops '(org-tags-view current-prefix-arg match)))
18252 ((eq type 'tags-todo)
18253 (org-let lprops '(org-tags-view '(4) match)))
18254 ((eq type 'todo)
18255 (org-let lprops '(org-todo-list match)))
18256 ((eq type 'tags-tree)
18257 (org-check-for-org-mode)
18258 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18259 ((eq type 'todo-tree)
18260 (org-check-for-org-mode)
18261 (org-let lprops
18262 '(org-occur (concat "^" outline-regexp "[ \t]*"
18263 (regexp-quote match) "\\>"))))
18264 ((eq type 'occur-tree)
18265 (org-check-for-org-mode)
18266 (org-let lprops '(org-occur match)))
18267 ((functionp type)
18268 (org-let lprops '(funcall type match)))
18269 ((fboundp type)
18270 (org-let lprops '(funcall type match)))
18271 (t (error "Invalid custom agenda command type %s" type))))
18272 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18273 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18274 ((equal keys "a") (call-interactively 'org-agenda-list))
18275 ((equal keys "t") (call-interactively 'org-todo-list))
18276 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18277 ((equal keys "m") (call-interactively 'org-tags-view))
18278 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18279 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18280 ((equal keys "L")
18281 (unless (org-mode-p)
18282 (error "This is not an Org-mode file"))
18283 (unless restriction
18284 (put 'org-agenda-files 'org-restrict (list bfn))
18285 (org-call-with-arg 'org-timeline arg)))
18286 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18287 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18288 ((equal keys "!") (customize-variable 'org-stuck-projects))
18289 (t (error "Invalid agenda key"))))))
18291 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18292 "The user interface for selecting an agenda command."
18293 (catch 'exit
18294 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18295 (restrict-ok (and bfn (org-mode-p)))
18296 (region-p (org-region-active-p))
18297 (custom org-agenda-custom-commands)
18298 (selstring "")
18299 restriction second-time
18300 c entry key type match prefixes rmheader header-end custom1 desc)
18301 (save-window-excursion
18302 (delete-other-windows)
18303 (org-switch-to-buffer-other-window " *Agenda Commands*")
18304 (erase-buffer)
18305 (insert (eval-when-compile
18306 (let ((header
18307 "Press key for an agenda command: < Buffer,subtree/region restriction
18308 -------------------------------- C Configure custom agenda commands
18309 a Agenda for current week or day e Export agenda views
18310 t List of all TODO entries T Entries with special TODO kwd
18311 m Match a TAGS query M Like m, but only TODO entries
18312 L Timeline for current buffer # List stuck projects (!=configure)
18313 / Multi-occur
18315 (start 0))
18316 (while (string-match
18317 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18318 header start)
18319 (setq start (match-end 0))
18320 (add-text-properties (match-beginning 2) (match-end 2)
18321 '(face bold) header))
18322 header)))
18323 (setq header-end (move-marker (make-marker) (point)))
18324 (while t
18325 (setq custom1 custom)
18326 (when (eq rmheader t)
18327 (goto-line 1)
18328 (re-search-forward ":" nil t)
18329 (delete-region (match-end 0) (line-end-position))
18330 (forward-char 1)
18331 (looking-at "-+")
18332 (delete-region (match-end 0) (line-end-position))
18333 (move-marker header-end (match-end 0)))
18334 (goto-char header-end)
18335 (delete-region (point) (point-max))
18336 (while (setq entry (pop custom1))
18337 (setq key (car entry) desc (nth 1 entry)
18338 type (nth 2 entry) match (nth 3 entry))
18339 (if (> (length key) 1)
18340 (add-to-list 'prefixes (string-to-char key))
18341 (insert
18342 (format
18343 "\n%-4s%-14s: %s"
18344 (org-add-props (copy-sequence key)
18345 '(face bold))
18346 (cond
18347 ((string-match "\\S-" desc) desc)
18348 ((eq type 'agenda) "Agenda for current week or day")
18349 ((eq type 'alltodo) "List of all TODO entries")
18350 ((eq type 'stuck) "List of stuck projects")
18351 ((eq type 'todo) "TODO keyword")
18352 ((eq type 'tags) "Tags query")
18353 ((eq type 'tags-todo) "Tags (TODO)")
18354 ((eq type 'tags-tree) "Tags tree")
18355 ((eq type 'todo-tree) "TODO kwd tree")
18356 ((eq type 'occur-tree) "Occur tree")
18357 ((functionp type) (if (symbolp type)
18358 (symbol-name type)
18359 "Lambda expression"))
18360 (t "???"))
18361 (cond
18362 ((stringp match)
18363 (org-add-props match nil 'face 'org-warning))
18364 (match
18365 (format "set of %d commands" (length match)))
18366 (t ""))))))
18367 (when prefixes
18368 (mapc (lambda (x)
18369 (insert
18370 (format "\n%s %s"
18371 (org-add-props (char-to-string x)
18372 nil 'face 'bold)
18373 (or (cdr (assoc (concat selstring (char-to-string x))
18374 prefix-descriptions))
18375 "Prefix key"))))
18376 prefixes))
18377 (goto-char (point-min))
18378 (when (fboundp 'fit-window-to-buffer)
18379 (if second-time
18380 (if (not (pos-visible-in-window-p (point-max)))
18381 (fit-window-to-buffer))
18382 (setq second-time t)
18383 (fit-window-to-buffer)))
18384 (message "Press key for agenda command%s:"
18385 (if restrict-ok
18386 (if restriction
18387 (format " (restricted to %s)" restriction)
18388 " (unrestricted)")
18389 ""))
18390 (setq c (read-char-exclusive))
18391 (message "")
18392 (cond
18393 ((assoc (char-to-string c) custom)
18394 (setq selstring (concat selstring (char-to-string c)))
18395 (throw 'exit (cons selstring restriction)))
18396 ((memq c prefixes)
18397 (setq selstring (concat selstring (char-to-string c))
18398 prefixes nil
18399 rmheader (or rmheader t)
18400 custom (delq nil (mapcar
18401 (lambda (x)
18402 (if (or (= (length (car x)) 1)
18403 (/= (string-to-char (car x)) c))
18405 (cons (substring (car x) 1) (cdr x))))
18406 custom))))
18407 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
18408 (message "Restriction is only possible in Org-mode buffers")
18409 (ding) (sit-for 1))
18410 ((eq c ?1)
18411 (setq restriction 'buffer))
18412 ((eq c ?0)
18413 (setq restriction (if region-p 'region 'subtree)))
18414 ((eq c ?<)
18415 (setq restriction
18416 (cond
18417 ((eq restriction 'buffer)
18418 (if region-p 'region 'subtree))
18419 ((memq restriction '(subtree region))
18420 nil)
18421 (t 'buffer))))
18422 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
18423 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
18424 ((equal c ?q) (error "Abort"))
18425 (t (error "Invalid key %c" c))))))))
18427 (defun org-run-agenda-series (name series)
18428 (org-prepare-agenda name)
18429 (let* ((org-agenda-multi t)
18430 (redo (list 'org-run-agenda-series name (list 'quote series)))
18431 (cmds (car series))
18432 (gprops (nth 1 series))
18433 match ;; The byte compiler incorrectly complains about this. Keep it!
18434 cmd type lprops)
18435 (while (setq cmd (pop cmds))
18436 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
18437 (cond
18438 ((eq type 'agenda)
18439 (org-let2 gprops lprops
18440 '(call-interactively 'org-agenda-list)))
18441 ((eq type 'alltodo)
18442 (org-let2 gprops lprops
18443 '(call-interactively 'org-todo-list)))
18444 ((eq type 'stuck)
18445 (org-let2 gprops lprops
18446 '(call-interactively 'org-agenda-list-stuck-projects)))
18447 ((eq type 'tags)
18448 (org-let2 gprops lprops
18449 '(org-tags-view current-prefix-arg match)))
18450 ((eq type 'tags-todo)
18451 (org-let2 gprops lprops
18452 '(org-tags-view '(4) match)))
18453 ((eq type 'todo)
18454 (org-let2 gprops lprops
18455 '(org-todo-list match)))
18456 ((fboundp type)
18457 (org-let2 gprops lprops
18458 '(funcall type match)))
18459 (t (error "Invalid type in command series"))))
18460 (widen)
18461 (setq org-agenda-redo-command redo)
18462 (goto-char (point-min)))
18463 (org-finalize-agenda))
18465 ;;;###autoload
18466 (defmacro org-batch-agenda (cmd-key &rest parameters)
18467 "Run an agenda command in batch mode and send the result to STDOUT.
18468 If CMD-KEY is a string of length 1, it is used as a key in
18469 `org-agenda-custom-commands' and triggers this command. If it is a
18470 longer string is is used as a tags/todo match string.
18471 Paramters are alternating variable names and values that will be bound
18472 before running the agenda command."
18473 (let (pars)
18474 (while parameters
18475 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18476 (if (> (length cmd-key) 2)
18477 (eval (list 'let (nreverse pars)
18478 (list 'org-tags-view nil cmd-key)))
18479 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18480 (set-buffer org-agenda-buffer-name)
18481 (princ (org-encode-for-stdout (buffer-string)))))
18483 (defun org-encode-for-stdout (string)
18484 (if (fboundp 'encode-coding-string)
18485 (encode-coding-string string buffer-file-coding-system)
18486 string))
18488 (defvar org-agenda-info nil)
18490 ;;;###autoload
18491 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
18492 "Run an agenda command in batch mode and send the result to STDOUT.
18493 If CMD-KEY is a string of length 1, it is used as a key in
18494 `org-agenda-custom-commands' and triggers this command. If it is a
18495 longer string is is used as a tags/todo match string.
18496 Paramters are alternating variable names and values that will be bound
18497 before running the agenda command.
18499 The output gives a line for each selected agenda item. Each
18500 item is a list of comma-separated values, like this:
18502 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
18504 category The category of the item
18505 head The headline, without TODO kwd, TAGS and PRIORITY
18506 type The type of the agenda entry, can be
18507 todo selected in TODO match
18508 tagsmatch selected in tags match
18509 diary imported from diary
18510 deadline a deadline on given date
18511 scheduled scheduled on given date
18512 timestamp entry has timestamp on given date
18513 closed entry was closed on given date
18514 upcoming-deadline warning about deadline
18515 past-scheduled forwarded scheduled item
18516 block entry has date block including g. date
18517 todo The todo keyword, if any
18518 tags All tags including inherited ones, separated by colons
18519 date The relevant date, like 2007-2-14
18520 time The time, like 15:00-16:50
18521 extra Sting with extra planning info
18522 priority-l The priority letter if any was given
18523 priority-n The computed numerical priority
18524 agenda-day The day in the agenda where this is listed"
18526 (let (pars)
18527 (while parameters
18528 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18529 (push (list 'org-agenda-remove-tags t) pars)
18530 (if (> (length cmd-key) 2)
18531 (eval (list 'let (nreverse pars)
18532 (list 'org-tags-view nil cmd-key)))
18533 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18534 (set-buffer org-agenda-buffer-name)
18535 (let* ((lines (org-split-string (buffer-string) "\n"))
18536 line)
18537 (while (setq line (pop lines))
18538 (catch 'next
18539 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
18540 (setq org-agenda-info
18541 (org-fix-agenda-info (text-properties-at 0 line)))
18542 (princ
18543 (org-encode-for-stdout
18544 (mapconcat 'org-agenda-export-csv-mapper
18545 '(org-category txt type todo tags date time-of-day extra
18546 priority-letter priority agenda-day)
18547 ",")))
18548 (princ "\n"))))))
18550 (defun org-fix-agenda-info (props)
18551 "Make sure all properties on an agenda item have a canonical form,
18552 so the the export commands caneasily use it."
18553 (let (tmp re)
18554 (when (setq tmp (plist-get props 'tags))
18555 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
18556 (when (setq tmp (plist-get props 'date))
18557 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18558 (let ((calendar-date-display-form '(year "-" month "-" day)))
18559 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
18561 (setq tmp (calendar-date-string tmp)))
18562 (setq props (plist-put props 'date tmp)))
18563 (when (setq tmp (plist-get props 'day))
18564 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18565 (let ((calendar-date-display-form '(year "-" month "-" day)))
18566 (setq tmp (calendar-date-string tmp)))
18567 (setq props (plist-put props 'day tmp))
18568 (setq props (plist-put props 'agenda-day tmp)))
18569 (when (setq tmp (plist-get props 'txt))
18570 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
18571 (plist-put props 'priority-letter (match-string 1 tmp))
18572 (setq tmp (replace-match "" t t tmp)))
18573 (when (and (setq re (plist-get props 'org-todo-regexp))
18574 (setq re (concat "\\`\\.*" re " ?"))
18575 (string-match re tmp))
18576 (plist-put props 'todo (match-string 1 tmp))
18577 (setq tmp (replace-match "" t t tmp)))
18578 (plist-put props 'txt tmp)))
18579 props)
18581 (defun org-agenda-export-csv-mapper (prop)
18582 (let ((res (plist-get org-agenda-info prop)))
18583 (setq res
18584 (cond
18585 ((not res) "")
18586 ((stringp res) res)
18587 (t (prin1-to-string res))))
18588 (while (string-match "," res)
18589 (setq res (replace-match ";" t t res)))
18590 (org-trim res)))
18593 ;;;###autoload
18594 (defun org-store-agenda-views (&rest parameters)
18595 (interactive)
18596 (eval (list 'org-batch-store-agenda-views)))
18598 ;; FIXME, why is this a macro?????
18599 ;;;###autoload
18600 (defmacro org-batch-store-agenda-views (&rest parameters)
18601 "Run all custom agenda commands that have a file argument."
18602 (let ((cmds org-agenda-custom-commands)
18603 (pop-up-frames nil)
18604 (dir default-directory)
18605 pars cmd thiscmdkey files opts)
18606 (while parameters
18607 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18608 (setq pars (reverse pars))
18609 (save-window-excursion
18610 (while cmds
18611 (setq cmd (pop cmds)
18612 thiscmdkey (car cmd)
18613 opts (nth 3 cmd)
18614 files (nth 4 cmd))
18615 (if (stringp files) (setq files (list files)))
18616 (when files
18617 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18618 (list 'org-agenda nil thiscmdkey)))
18619 (set-buffer org-agenda-buffer-name)
18620 (while files
18621 (eval (list 'let (append org-agenda-exporter-settings opts pars)
18622 (list 'org-write-agenda
18623 (expand-file-name (pop files) dir) t))))
18624 (and (get-buffer org-agenda-buffer-name)
18625 (kill-buffer org-agenda-buffer-name)))))))
18627 (defun org-write-agenda (file &optional nosettings)
18628 "Write the current buffer (an agenda view) as a file.
18629 Depending on the extension of the file name, plain text (.txt),
18630 HTML (.html or .htm) or Postscript (.ps) is produced.
18631 If NOSETTINGS is given, do not scope the settings of
18632 `org-agenda-exporter-settings' into the export commands. This is used when
18633 the settings have already been scoped and we do not wish to overrule other,
18634 higher priority settings."
18635 (interactive "FWrite agenda to file: ")
18636 (if (not (file-writable-p file))
18637 (error "Cannot write agenda to file %s" file))
18638 (cond
18639 ((string-match "\\.html?\\'" file) (require 'htmlize))
18640 ((string-match "\\.ps\\'" file) (require 'ps-print)))
18641 (org-let (if nosettings nil org-agenda-exporter-settings)
18642 '(save-excursion
18643 (save-window-excursion
18644 (cond
18645 ((string-match "\\.html?\\'" file)
18646 (set-buffer (htmlize-buffer (current-buffer)))
18648 (when (and org-agenda-export-html-style
18649 (string-match "<style>" org-agenda-export-html-style))
18650 ;; replace <style> section with org-agenda-export-html-style
18651 (goto-char (point-min))
18652 (kill-region (- (search-forward "<style") 6)
18653 (search-forward "</style>"))
18654 (insert org-agenda-export-html-style))
18655 (write-file file)
18656 (kill-buffer (current-buffer))
18657 (message "HTML written to %s" file))
18658 ((string-match "\\.ps\\'" file)
18659 (ps-print-buffer-with-faces file)
18660 (message "Postscript written to %s" file))
18662 (let ((bs (buffer-string)))
18663 (find-file file)
18664 (insert bs)
18665 (save-buffer 0)
18666 (kill-buffer (current-buffer))
18667 (message "Plain text written to %s" file))))))
18668 (set-buffer org-agenda-buffer-name)))
18670 (defmacro org-no-read-only (&rest body)
18671 "Inhibit read-only for BODY."
18672 `(let ((inhibit-read-only t)) ,@body))
18674 (defun org-check-for-org-mode ()
18675 "Make sure current buffer is in org-mode. Error if not."
18676 (or (org-mode-p)
18677 (error "Cannot execute org-mode agenda command on buffer in %s."
18678 major-mode)))
18680 (defun org-fit-agenda-window ()
18681 "Fit the window to the buffer size."
18682 (and (memq org-agenda-window-setup '(reorganize-frame))
18683 (fboundp 'fit-window-to-buffer)
18684 (fit-window-to-buffer
18686 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
18687 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
18689 ;;; Agenda file list
18691 (defun org-agenda-files (&optional unrestricted)
18692 "Get the list of agenda files.
18693 Optional UNRESTRICTED means return the full list even if a restriction
18694 is currently in place."
18695 (let ((files
18696 (cond
18697 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18698 ((stringp org-agenda-files) (org-read-agenda-file-list))
18699 ((listp org-agenda-files) org-agenda-files)
18700 (t (error "Invalid value of `org-agenda-files'")))))
18701 (setq files (apply 'append
18702 (mapcar (lambda (f)
18703 (if (file-directory-p f)
18704 (directory-files f t "\\.org\\'")
18705 (list f)))
18706 files)))
18707 (if org-agenda-skip-unavailable-files
18708 (delq nil
18709 (mapcar (function
18710 (lambda (file)
18711 (and (file-readable-p file) file)))
18712 files))
18713 files))) ; `org-check-agenda-file' will remove them from the list
18715 (defun org-edit-agenda-file-list ()
18716 "Edit the list of agenda files.
18717 Depending on setup, this either uses customize to edit the variable
18718 `org-agenda-files', or it visits the file that is holding the list. In the
18719 latter case, the buffer is set up in a way that saving it automatically kills
18720 the buffer and restores the previous window configuration."
18721 (interactive)
18722 (if (stringp org-agenda-files)
18723 (let ((cw (current-window-configuration)))
18724 (find-file org-agenda-files)
18725 (org-set-local 'org-window-configuration cw)
18726 (org-add-hook 'after-save-hook
18727 (lambda ()
18728 (set-window-configuration
18729 (prog1 org-window-configuration
18730 (kill-buffer (current-buffer))))
18731 (org-install-agenda-files-menu)
18732 (message "New agenda file list installed"))
18733 nil 'local)
18734 (message (substitute-command-keys
18735 "Edit list and finish with \\[save-buffer]")))
18736 (customize-variable 'org-agenda-files)))
18738 (defun org-store-new-agenda-file-list (list)
18739 "Set new value for the agenda file list and save it correcly."
18740 (if (stringp org-agenda-files)
18741 (let ((f org-agenda-files) b)
18742 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
18743 (with-temp-file f
18744 (insert (mapconcat 'identity list "\n") "\n")))
18745 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
18746 (setq org-agenda-files list)
18747 (customize-save-variable 'org-agenda-files org-agenda-files))))
18749 (defun org-read-agenda-file-list ()
18750 "Read the list of agenda files from a file."
18751 (when (stringp org-agenda-files)
18752 (with-temp-buffer
18753 (insert-file-contents org-agenda-files)
18754 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
18757 ;;;###autoload
18758 (defun org-cycle-agenda-files ()
18759 "Cycle through the files in `org-agenda-files'.
18760 If the current buffer visits an agenda file, find the next one in the list.
18761 If the current buffer does not, find the first agenda file."
18762 (interactive)
18763 (let* ((fs (org-agenda-files t))
18764 (files (append fs (list (car fs))))
18765 (tcf (if buffer-file-name (file-truename buffer-file-name)))
18766 file)
18767 (unless files (error "No agenda files"))
18768 (catch 'exit
18769 (while (setq file (pop files))
18770 (if (equal (file-truename file) tcf)
18771 (when (car files)
18772 (find-file (car files))
18773 (throw 'exit t))))
18774 (find-file (car fs)))
18775 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
18777 (defun org-agenda-file-to-front (&optional to-end)
18778 "Move/add the current file to the top of the agenda file list.
18779 If the file is not present in the list, it is added to the front. If it is
18780 present, it is moved there. With optional argument TO-END, add/move to the
18781 end of the list."
18782 (interactive "P")
18783 (let ((org-agenda-skip-unavailable-files nil)
18784 (file-alist (mapcar (lambda (x)
18785 (cons (file-truename x) x))
18786 (org-agenda-files t)))
18787 (ctf (file-truename buffer-file-name))
18788 x had)
18789 (setq x (assoc ctf file-alist) had x)
18791 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18792 (if to-end
18793 (setq file-alist (append (delq x file-alist) (list x)))
18794 (setq file-alist (cons x (delq x file-alist))))
18795 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18796 (org-install-agenda-files-menu)
18797 (message "File %s to %s of agenda file list"
18798 (if had "moved" "added") (if to-end "end" "front"))))
18800 (defun org-remove-file (&optional file)
18801 "Remove current file from the list of files in variable `org-agenda-files'.
18802 These are the files which are being checked for agenda entries.
18803 Optional argument FILE means, use this file instead of the current."
18804 (interactive)
18805 (let* ((org-agenda-skip-unavailable-files nil)
18806 (file (or file buffer-file-name))
18807 (true-file (file-truename file))
18808 (afile (abbreviate-file-name file))
18809 (files (delq nil (mapcar
18810 (lambda (x)
18811 (if (equal true-file
18812 (file-truename x))
18813 nil x))
18814 (org-agenda-files t)))))
18815 (if (not (= (length files) (length (org-agenda-files t))))
18816 (progn
18817 (org-store-new-agenda-file-list files)
18818 (org-install-agenda-files-menu)
18819 (message "Removed file: %s" afile))
18820 (message "File was not in list: %s" afile))))
18822 (defun org-file-menu-entry (file)
18823 (vector file (list 'find-file file) t))
18825 (defun org-check-agenda-file (file)
18826 "Make sure FILE exists. If not, ask user what to do."
18827 (when (not (file-exists-p file))
18828 (message "non-existent file %s. [R]emove from list or [A]bort?"
18829 (abbreviate-file-name file))
18830 (let ((r (downcase (read-char-exclusive))))
18831 (cond
18832 ((equal r ?r)
18833 (org-remove-file file)
18834 (throw 'nextfile t))
18835 (t (error "Abort"))))))
18837 ;;; Agenda prepare and finalize
18839 (defvar org-agenda-multi nil) ; dynammically scoped
18840 (defvar org-agenda-buffer-name "*Org Agenda*")
18841 (defvar org-pre-agenda-window-conf nil)
18842 (defvar org-agenda-name nil)
18843 (defun org-prepare-agenda (&optional name)
18844 (setq org-todo-keywords-for-agenda nil)
18845 (setq org-done-keywords-for-agenda nil)
18846 (if org-agenda-multi
18847 (progn
18848 (setq buffer-read-only nil)
18849 (goto-char (point-max))
18850 (unless (or (bobp) org-agenda-compact-blocks)
18851 (insert "\n" (make-string (window-width) ?=) "\n"))
18852 (narrow-to-region (point) (point-max)))
18853 (org-agenda-maybe-reset-markers 'force)
18854 (org-prepare-agenda-buffers (org-agenda-files))
18855 (setq org-todo-keywords-for-agenda
18856 (org-uniquify org-todo-keywords-for-agenda))
18857 (setq org-done-keywords-for-agenda
18858 (org-uniquify org-done-keywords-for-agenda))
18859 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
18860 (awin (get-buffer-window abuf)))
18861 (cond
18862 ((equal (current-buffer) abuf) nil)
18863 (awin (select-window awin))
18864 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
18865 ((equal org-agenda-window-setup 'current-window)
18866 (switch-to-buffer abuf))
18867 ((equal org-agenda-window-setup 'other-window)
18868 (org-switch-to-buffer-other-window abuf))
18869 ((equal org-agenda-window-setup 'other-frame)
18870 (switch-to-buffer-other-frame abuf))
18871 ((equal org-agenda-window-setup 'reorganize-frame)
18872 (delete-other-windows)
18873 (org-switch-to-buffer-other-window abuf))))
18874 (setq buffer-read-only nil)
18875 (erase-buffer)
18876 (org-agenda-mode)
18877 (and name (not org-agenda-name)
18878 (org-set-local 'org-agenda-name name)))
18879 (setq buffer-read-only nil))
18881 (defun org-finalize-agenda ()
18882 "Finishing touch for the agenda buffer, called just before displaying it."
18883 (unless org-agenda-multi
18884 (save-excursion
18885 (let ((inhibit-read-only t))
18886 (goto-char (point-min))
18887 (while (org-activate-bracket-links (point-max))
18888 (add-text-properties (match-beginning 0) (match-end 0)
18889 '(face org-link)))
18890 (org-agenda-align-tags)
18891 (unless org-agenda-with-colors
18892 (remove-text-properties (point-min) (point-max) '(face nil))))
18893 (if (and (boundp 'org-overriding-columns-format)
18894 org-overriding-columns-format)
18895 (org-set-local 'org-overriding-columns-format
18896 org-overriding-columns-format))
18897 (if (and (boundp 'org-agenda-view-columns-initially)
18898 org-agenda-view-columns-initially)
18899 (org-agenda-columns))
18900 (when org-agenda-fontify-priorities
18901 (org-fontify-priorities))
18902 (run-hooks 'org-finalize-agenda-hook))))
18904 (defun org-fontify-priorities ()
18905 "Make highest priority lines bold, and lowest italic."
18906 (interactive)
18907 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
18908 (org-delete-overlay o)))
18909 (overlays-in (point-min) (point-max)))
18910 (save-excursion
18911 (let ((ovs (org-overlays-in (point-min) (point-max)))
18912 (inhibit-read-only t)
18913 b e p ov h l)
18914 (goto-char (point-min))
18915 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
18916 (setq h (or (get-char-property (point) 'org-highest-priority)
18917 org-highest-priority)
18918 l (or (get-char-property (point) 'org-lowest-priority)
18919 org-lowest-priority)
18920 p (string-to-char (match-string 1))
18921 b (match-beginning 0) e (line-end-position)
18922 ov (org-make-overlay b e))
18923 (org-overlay-put
18924 ov 'face
18925 (cond ((listp org-agenda-fontify-priorities)
18926 (cdr (assoc p org-agenda-fontify-priorities)))
18927 ((equal p l) 'italic)
18928 ((equal p h) 'bold)))
18929 (org-overlay-put ov 'org-type 'org-priority)))))
18931 (defun org-prepare-agenda-buffers (files)
18932 "Create buffers for all agenda files, protect archived trees and comments."
18933 (interactive)
18934 (let ((pa '(:org-archived t))
18935 (pc '(:org-comment t))
18936 (pall '(:org-archived t :org-comment t))
18937 (inhibit-read-only t)
18938 (rea (concat ":" org-archive-tag ":"))
18939 bmp file re)
18940 (save-excursion
18941 (save-restriction
18942 (while (setq file (pop files))
18943 (org-check-agenda-file file)
18944 (set-buffer (org-get-agenda-file-buffer file))
18945 (widen)
18946 (setq bmp (buffer-modified-p))
18947 (org-refresh-category-properties)
18948 (setq org-todo-keywords-for-agenda
18949 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18950 (setq org-done-keywords-for-agenda
18951 (append org-done-keywords-for-agenda org-done-keywords))
18952 (save-excursion
18953 (remove-text-properties (point-min) (point-max) pall)
18954 (when org-agenda-skip-archived-trees
18955 (goto-char (point-min))
18956 (while (re-search-forward rea nil t)
18957 (if (org-on-heading-p t)
18958 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18959 (goto-char (point-min))
18960 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
18961 (while (re-search-forward re nil t)
18962 (add-text-properties
18963 (match-beginning 0) (org-end-of-subtree t) pc)))
18964 (set-buffer-modified-p bmp))))))
18966 (defvar org-agenda-skip-function nil
18967 "Function to be called at each match during agenda construction.
18968 If this function returns nil, the current match should not be skipped.
18969 Otherwise, the function must return a position from where the search
18970 should be continued.
18971 This may also be a Lisp form, it will be evaluated.
18972 Never set this variable using `setq' or so, because then it will apply
18973 to all future agenda commands. Instead, bind it with `let' to scope
18974 it dynamically into the agenda-constructing command. A good way to set
18975 it is through options in org-agenda-custom-commands.")
18977 (defun org-agenda-skip ()
18978 "Throw to `:skip' in places that should be skipped.
18979 Also moves point to the end of the skipped region, so that search can
18980 continue from there."
18981 (let ((p (point-at-bol)) to fp)
18982 (and org-agenda-skip-archived-trees
18983 (get-text-property p :org-archived)
18984 (org-end-of-subtree t)
18985 (throw :skip t))
18986 (and (get-text-property p :org-comment)
18987 (org-end-of-subtree t)
18988 (throw :skip t))
18989 (if (equal (char-after p) ?#) (throw :skip t))
18990 (when (and (or (setq fp (functionp org-agenda-skip-function))
18991 (consp org-agenda-skip-function))
18992 (setq to (save-excursion
18993 (save-match-data
18994 (if fp
18995 (funcall org-agenda-skip-function)
18996 (eval org-agenda-skip-function))))))
18997 (goto-char to)
18998 (throw :skip t))))
19000 (defvar org-agenda-markers nil
19001 "List of all currently active markers created by `org-agenda'.")
19002 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19003 "Creation time of the last agenda marker.")
19005 (defun org-agenda-new-marker (&optional pos)
19006 "Return a new agenda marker.
19007 Org-mode keeps a list of these markers and resets them when they are
19008 no longer in use."
19009 (let ((m (copy-marker (or pos (point)))))
19010 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19011 (push m org-agenda-markers)
19014 (defun org-agenda-maybe-reset-markers (&optional force)
19015 "Reset markers created by `org-agenda'. But only if they are old enough."
19016 (if (or (and force (not org-agenda-multi))
19017 (> (- (time-to-seconds (current-time))
19018 org-agenda-last-marker-time)
19020 (while org-agenda-markers
19021 (move-marker (pop org-agenda-markers) nil))))
19023 (defvar org-agenda-new-buffers nil
19024 "Buffers created to visit agenda files.")
19026 (defun org-get-agenda-file-buffer (file)
19027 "Get a buffer visiting FILE. If the buffer needs to be created, add
19028 it to the list of buffers which might be released later."
19029 (let ((buf (org-find-base-buffer-visiting file)))
19030 (if buf
19031 buf ; just return it
19032 ;; Make a new buffer and remember it
19033 (setq buf (find-file-noselect file))
19034 (if buf (push buf org-agenda-new-buffers))
19035 buf)))
19037 (defun org-release-buffers (blist)
19038 "Release all buffers in list, asking the user for confirmation when needed.
19039 When a buffer is unmodified, it is just killed. When modified, it is saved
19040 \(if the user agrees) and then killed."
19041 (let (buf file)
19042 (while (setq buf (pop blist))
19043 (setq file (buffer-file-name buf))
19044 (when (and (buffer-modified-p buf)
19045 file
19046 (y-or-n-p (format "Save file %s? " file)))
19047 (with-current-buffer buf (save-buffer)))
19048 (kill-buffer buf))))
19050 (defun org-get-category (&optional pos)
19051 "Get the category applying to position POS."
19052 (get-text-property (or pos (point)) 'org-category))
19054 ;;; Agenda timeline
19056 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19058 (defun org-timeline (&optional include-all)
19059 "Show a time-sorted view of the entries in the current org file.
19060 Only entries with a time stamp of today or later will be listed. With
19061 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19062 under the current date.
19063 If the buffer contains an active region, only check the region for
19064 dates."
19065 (interactive "P")
19066 (require 'calendar)
19067 (org-compile-prefix-format 'timeline)
19068 (org-set-sorting-strategy 'timeline)
19069 (let* ((dopast t)
19070 (dotodo include-all)
19071 (doclosed org-agenda-show-log)
19072 (entry buffer-file-name)
19073 (date (calendar-current-date))
19074 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19075 (end (if (org-region-active-p) (region-end) (point-max)))
19076 (day-numbers (org-get-all-dates beg end 'no-ranges
19077 t doclosed ; always include today
19078 org-timeline-show-empty-dates))
19079 (org-deadline-warning-days 0)
19080 (org-agenda-only-exact-dates t)
19081 (today (time-to-days (current-time)))
19082 (past t)
19083 args
19084 s e rtn d emptyp)
19085 (setq org-agenda-redo-command
19086 (list 'progn
19087 (list 'org-switch-to-buffer-other-window (current-buffer))
19088 (list 'org-timeline (list 'quote include-all))))
19089 (if (not dopast)
19090 ;; Remove past dates from the list of dates.
19091 (setq day-numbers (delq nil (mapcar (lambda(x)
19092 (if (>= x today) x nil))
19093 day-numbers))))
19094 (org-prepare-agenda (concat "Timeline "
19095 (file-name-nondirectory buffer-file-name)))
19096 (if doclosed (push :closed args))
19097 (push :timestamp args)
19098 (push :deadline args)
19099 (push :scheduled args)
19100 (push :sexp args)
19101 (if dotodo (push :todo args))
19102 (while (setq d (pop day-numbers))
19103 (if (and (listp d) (eq (car d) :omitted))
19104 (progn
19105 (setq s (point))
19106 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19107 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19108 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19109 (if (and (>= d today)
19110 dopast
19111 past)
19112 (progn
19113 (setq past nil)
19114 (insert (make-string 79 ?-) "\n")))
19115 (setq date (calendar-gregorian-from-absolute d))
19116 (setq s (point))
19117 (setq rtn (and (not emptyp)
19118 (apply 'org-agenda-get-day-entries entry
19119 date args)))
19120 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19121 (progn
19122 (insert
19123 (if (stringp org-agenda-format-date)
19124 (format-time-string org-agenda-format-date
19125 (org-time-from-absolute date))
19126 (funcall org-agenda-format-date date))
19127 "\n")
19128 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19129 (put-text-property s (1- (point)) 'org-date-line t)
19130 (if (equal d today)
19131 (put-text-property s (1- (point)) 'org-today t))
19132 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19133 (put-text-property s (1- (point)) 'day d)))))
19134 (goto-char (point-min))
19135 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19136 (point-min)))
19137 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19138 (org-finalize-agenda)
19139 (setq buffer-read-only t)))
19141 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19142 "Return a list of all relevant day numbers from BEG to END buffer positions.
19143 If NO-RANGES is non-nil, include only the start and end dates of a range,
19144 not every single day in the range. If FORCE-TODAY is non-nil, make
19145 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19146 inactive time stamps (those in square brackets) are included.
19147 When EMPTY is non-nil, also include days without any entries."
19148 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19149 dates dates1 date day day1 day2 ts1 ts2)
19150 (if force-today
19151 (setq dates (list (time-to-days (current-time)))))
19152 (save-excursion
19153 (goto-char beg)
19154 (while (re-search-forward re end t)
19155 (setq day (time-to-days (org-time-string-to-time
19156 (substring (match-string 1) 0 10))))
19157 (or (memq day dates) (push day dates)))
19158 (unless no-ranges
19159 (goto-char beg)
19160 (while (re-search-forward org-tr-regexp end t)
19161 (setq ts1 (substring (match-string 1) 0 10)
19162 ts2 (substring (match-string 2) 0 10)
19163 day1 (time-to-days (org-time-string-to-time ts1))
19164 day2 (time-to-days (org-time-string-to-time ts2)))
19165 (while (< (setq day1 (1+ day1)) day2)
19166 (or (memq day1 dates) (push day1 dates)))))
19167 (setq dates (sort dates '<))
19168 (when empty
19169 (while (setq day (pop dates))
19170 (setq day2 (car dates))
19171 (push day dates1)
19172 (when (and day2 empty)
19173 (if (or (eq empty t)
19174 (and (numberp empty) (<= (- day2 day) empty)))
19175 (while (< (setq day (1+ day)) day2)
19176 (push (list day) dates1))
19177 (push (cons :omitted (- day2 day)) dates1))))
19178 (setq dates (nreverse dates1)))
19179 dates)))
19181 ;;; Agenda Daily/Weekly
19183 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19184 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19185 (defvar org-agenda-last-arguments nil
19186 "The arguments of the previous call to org-agenda")
19187 (defvar org-starting-day nil) ; local variable in the agenda buffer
19188 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19189 (defvar org-include-all-loc nil) ; local variable
19190 (defvar org-agenda-remove-date nil) ; dynamically scoped
19192 ;;;###autoload
19193 (defun org-agenda-list (&optional include-all start-day ndays)
19194 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
19195 The view will be for the current day or week, but from the overview buffer
19196 you will be able to go to other days/weeks.
19198 With one \\[universal-argument] prefix argument INCLUDE-ALL,
19199 all unfinished TODO items will also be shown, before the agenda.
19200 This feature is considered obsolete, please use the TODO list or a block
19201 agenda instead.
19203 With a numeric prefix argument in an interactive call, the agenda will
19204 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
19205 the number of days. NDAYS defaults to `org-agenda-ndays'.
19207 START-DAY defaults to TODAY, or to the most recent match for the weekday
19208 given in `org-agenda-start-on-weekday'."
19209 (interactive "P")
19210 (if (and (integerp include-all) (> include-all 0))
19211 (setq ndays include-all include-all nil))
19212 (setq ndays (or ndays org-agenda-ndays)
19213 start-day (or start-day org-agenda-start-day))
19214 (if org-agenda-overriding-arguments
19215 (setq include-all (car org-agenda-overriding-arguments)
19216 start-day (nth 1 org-agenda-overriding-arguments)
19217 ndays (nth 2 org-agenda-overriding-arguments)))
19218 (if (stringp start-day)
19219 ;; Convert to an absolute day number
19220 (setq start-day (time-to-days (org-read-date nil t start-day))))
19221 (setq org-agenda-last-arguments (list include-all start-day ndays))
19222 (org-compile-prefix-format 'agenda)
19223 (org-set-sorting-strategy 'agenda)
19224 (require 'calendar)
19225 (let* ((org-agenda-start-on-weekday
19226 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19227 org-agenda-start-on-weekday nil))
19228 (thefiles (org-agenda-files))
19229 (files thefiles)
19230 (today (time-to-days (current-time)))
19231 (sd (or start-day today))
19232 (start (if (or (null org-agenda-start-on-weekday)
19233 (< org-agenda-ndays 7))
19235 (let* ((nt (calendar-day-of-week
19236 (calendar-gregorian-from-absolute sd)))
19237 (n1 org-agenda-start-on-weekday)
19238 (d (- nt n1)))
19239 (- sd (+ (if (< d 0) 7 0) d)))))
19240 (day-numbers (list start))
19241 (day-cnt 0)
19242 (inhibit-redisplay (not debug-on-error))
19243 s e rtn rtnall file date d start-pos end-pos todayp nd)
19244 (setq org-agenda-redo-command
19245 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19246 ;; Make the list of days
19247 (setq ndays (or ndays org-agenda-ndays)
19248 nd ndays)
19249 (while (> ndays 1)
19250 (push (1+ (car day-numbers)) day-numbers)
19251 (setq ndays (1- ndays)))
19252 (setq day-numbers (nreverse day-numbers))
19253 (org-prepare-agenda "Day/Week")
19254 (org-set-local 'org-starting-day (car day-numbers))
19255 (org-set-local 'org-include-all-loc include-all)
19256 (org-set-local 'org-agenda-span
19257 (org-agenda-ndays-to-span nd))
19258 (when (and (or include-all org-agenda-include-all-todo)
19259 (member today day-numbers))
19260 (setq files thefiles
19261 rtnall nil)
19262 (while (setq file (pop files))
19263 (catch 'nextfile
19264 (org-check-agenda-file file)
19265 (setq date (calendar-gregorian-from-absolute today)
19266 rtn (org-agenda-get-day-entries
19267 file date :todo))
19268 (setq rtnall (append rtnall rtn))))
19269 (when rtnall
19270 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19271 (add-text-properties (point-min) (1- (point))
19272 (list 'face 'org-agenda-structure))
19273 (insert (org-finalize-agenda-entries rtnall) "\n")))
19274 (unless org-agenda-compact-blocks
19275 (setq s (point))
19276 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19277 "-agenda:\n")
19278 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19279 'org-date-line t)))
19280 (while (setq d (pop day-numbers))
19281 (setq date (calendar-gregorian-from-absolute d)
19282 s (point))
19283 (if (or (setq todayp (= d today))
19284 (and (not start-pos) (= d sd)))
19285 (setq start-pos (point))
19286 (if (and start-pos (not end-pos))
19287 (setq end-pos (point))))
19288 (setq files thefiles
19289 rtnall nil)
19290 (while (setq file (pop files))
19291 (catch 'nextfile
19292 (org-check-agenda-file file)
19293 (if org-agenda-show-log
19294 (setq rtn (org-agenda-get-day-entries
19295 file date
19296 :deadline :scheduled :timestamp :sexp :closed))
19297 (setq rtn (org-agenda-get-day-entries
19298 file date
19299 :deadline :scheduled :sexp :timestamp)))
19300 (setq rtnall (append rtnall rtn))))
19301 (if org-agenda-include-diary
19302 (progn
19303 (require 'diary-lib)
19304 (setq rtn (org-get-entries-from-diary date))
19305 (setq rtnall (append rtnall rtn))))
19306 (if (or rtnall org-agenda-show-all-dates)
19307 (progn
19308 (setq day-cnt (1+ day-cnt))
19309 (insert
19310 (if (stringp org-agenda-format-date)
19311 (format-time-string org-agenda-format-date
19312 (org-time-from-absolute date))
19313 (funcall org-agenda-format-date date))
19314 "\n")
19315 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19316 (put-text-property s (1- (point)) 'org-date-line t)
19317 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19318 (if todayp (put-text-property s (1- (point)) 'org-today t))
19319 (if rtnall (insert
19320 (org-finalize-agenda-entries
19321 (org-agenda-add-time-grid-maybe
19322 rtnall nd todayp))
19323 "\n"))
19324 (put-text-property s (1- (point)) 'day d)
19325 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19326 (goto-char (point-min))
19327 (org-fit-agenda-window)
19328 (unless (and (pos-visible-in-window-p (point-min))
19329 (pos-visible-in-window-p (point-max)))
19330 (goto-char (1- (point-max)))
19331 (recenter -1)
19332 (if (not (pos-visible-in-window-p (or start-pos 1)))
19333 (progn
19334 (goto-char (or start-pos 1))
19335 (recenter 1))))
19336 (goto-char (or start-pos 1))
19337 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19338 (org-finalize-agenda)
19339 (setq buffer-read-only t)
19340 (message "")))
19342 (defun org-agenda-ndays-to-span (n)
19343 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
19345 ;;; Agenda TODO list
19347 (defvar org-select-this-todo-keyword nil)
19348 (defvar org-last-arg nil)
19350 ;;;###autoload
19351 (defun org-todo-list (arg)
19352 "Show all TODO entries from all agenda file in a single list.
19353 The prefix arg can be used to select a specific TODO keyword and limit
19354 the list to these. When using \\[universal-argument], you will be prompted
19355 for a keyword. A numeric prefix directly selects the Nth keyword in
19356 `org-todo-keywords-1'."
19357 (interactive "P")
19358 (require 'calendar)
19359 (org-compile-prefix-format 'todo)
19360 (org-set-sorting-strategy 'todo)
19361 (org-prepare-agenda "TODO")
19362 (let* ((today (time-to-days (current-time)))
19363 (date (calendar-gregorian-from-absolute today))
19364 (kwds org-todo-keywords-for-agenda)
19365 (completion-ignore-case t)
19366 (org-select-this-todo-keyword
19367 (if (stringp arg) arg
19368 (and arg (integerp arg) (> arg 0)
19369 (nth (1- arg) kwds))))
19370 rtn rtnall files file pos)
19371 (when (equal arg '(4))
19372 (setq org-select-this-todo-keyword
19373 (completing-read "Keyword (or KWD1|K2D2|...): "
19374 (mapcar 'list kwds) nil nil)))
19375 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
19376 (org-set-local 'org-last-arg arg)
19377 (setq org-agenda-redo-command
19378 '(org-todo-list (or current-prefix-arg org-last-arg)))
19379 (setq files (org-agenda-files)
19380 rtnall nil)
19381 (while (setq file (pop files))
19382 (catch 'nextfile
19383 (org-check-agenda-file file)
19384 (setq rtn (org-agenda-get-day-entries file date :todo))
19385 (setq rtnall (append rtnall rtn))))
19386 (if org-agenda-overriding-header
19387 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19388 nil 'face 'org-agenda-structure) "\n")
19389 (insert "Global list of TODO items of type: ")
19390 (add-text-properties (point-min) (1- (point))
19391 (list 'face 'org-agenda-structure))
19392 (setq pos (point))
19393 (insert (or org-select-this-todo-keyword "ALL") "\n")
19394 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19395 (setq pos (point))
19396 (unless org-agenda-multi
19397 (insert "Available with `N r': (0)ALL")
19398 (let ((n 0) s)
19399 (mapc (lambda (x)
19400 (setq s (format "(%d)%s" (setq n (1+ n)) x))
19401 (if (> (+ (current-column) (string-width s) 1) (frame-width))
19402 (insert "\n "))
19403 (insert " " s))
19404 kwds))
19405 (insert "\n"))
19406 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19407 (when rtnall
19408 (insert (org-finalize-agenda-entries rtnall) "\n"))
19409 (goto-char (point-min))
19410 (org-fit-agenda-window)
19411 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
19412 (org-finalize-agenda)
19413 (setq buffer-read-only t)))
19415 ;;; Agenda tags match
19417 ;;;###autoload
19418 (defun org-tags-view (&optional todo-only match)
19419 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
19420 The prefix arg TODO-ONLY limits the search to TODO entries."
19421 (interactive "P")
19422 (org-compile-prefix-format 'tags)
19423 (org-set-sorting-strategy 'tags)
19424 (let* ((org-tags-match-list-sublevels
19425 (if todo-only t org-tags-match-list-sublevels))
19426 (completion-ignore-case t)
19427 rtn rtnall files file pos matcher
19428 buffer)
19429 (setq matcher (org-make-tags-matcher match)
19430 match (car matcher) matcher (cdr matcher))
19431 (org-prepare-agenda (concat "TAGS " match))
19432 (setq org-agenda-redo-command
19433 (list 'org-tags-view (list 'quote todo-only)
19434 (list 'if 'current-prefix-arg nil match)))
19435 (setq files (org-agenda-files)
19436 rtnall nil)
19437 (while (setq file (pop files))
19438 (catch 'nextfile
19439 (org-check-agenda-file file)
19440 (setq buffer (if (file-exists-p file)
19441 (org-get-agenda-file-buffer file)
19442 (error "No such file %s" file)))
19443 (if (not buffer)
19444 ;; If file does not exist, merror message to agenda
19445 (setq rtn (list
19446 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19447 rtnall (append rtnall rtn))
19448 (with-current-buffer buffer
19449 (unless (org-mode-p)
19450 (error "Agenda file %s is not in `org-mode'" file))
19451 (save-excursion
19452 (save-restriction
19453 (if org-agenda-restrict
19454 (narrow-to-region org-agenda-restrict-begin
19455 org-agenda-restrict-end)
19456 (widen))
19457 (setq rtn (org-scan-tags 'agenda matcher todo-only))
19458 (setq rtnall (append rtnall rtn))))))))
19459 (if org-agenda-overriding-header
19460 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19461 nil 'face 'org-agenda-structure) "\n")
19462 (insert "Headlines with TAGS match: ")
19463 (add-text-properties (point-min) (1- (point))
19464 (list 'face 'org-agenda-structure))
19465 (setq pos (point))
19466 (insert match "\n")
19467 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19468 (setq pos (point))
19469 (unless org-agenda-multi
19470 (insert "Press `C-u r' to search again with new search string\n"))
19471 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19472 (when rtnall
19473 (insert (org-finalize-agenda-entries rtnall) "\n"))
19474 (goto-char (point-min))
19475 (org-fit-agenda-window)
19476 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
19477 (org-finalize-agenda)
19478 (setq buffer-read-only t)))
19480 ;;; Agenda Finding stuck projects
19482 (defvar org-agenda-skip-regexp nil
19483 "Regular expression used in skipping subtrees for the agenda.
19484 This is basically a temporary global variable that can be set and then
19485 used by user-defined selections using `org-agenda-skip-function'.")
19487 (defvar org-agenda-overriding-header nil
19488 "When this is set during todo and tags searches, will replace header.")
19490 (defun org-agenda-skip-subtree-when-regexp-matches ()
19491 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
19492 If yes, it returns the end position of this tree, causing agenda commands
19493 to skip this subtree. This is a function that can be put into
19494 `org-agenda-skip-function' for the duration of a command."
19495 (let ((end (save-excursion (org-end-of-subtree t)))
19496 skip)
19497 (save-excursion
19498 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
19499 (and skip end)))
19501 (defun org-agenda-skip-entry-if (&rest conditions)
19502 "Skip entry if any of CONDITIONS is true.
19503 See `org-agenda-skip-if for details."
19504 (org-agenda-skip-if nil conditions))
19505 (defun org-agenda-skip-subtree-if (&rest conditions)
19506 "Skip entry if any of CONDITIONS is true.
19507 See `org-agenda-skip-if for details."
19508 (org-agenda-skip-if t conditions))
19510 (defun org-agenda-skip-if (subtree conditions)
19511 "Checks current entity for CONDITIONS.
19512 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
19513 the entry, i.e. the text before the next heading is checked.
19515 CONDITIONS is a list of symbols, boolean OR is used to combine the results
19516 from different tests. Valid conditions are:
19518 scheduled Check if there is a scheduled cookie
19519 notscheduled Check if there is no scheduled cookie
19520 deadline Check if there is a deadline
19521 notdeadline Check if there is no deadline
19522 regexp Check if regexp matches
19523 notregexp Check if regexp does not match.
19525 The regexp is taken from the conditions list, it must com right after the
19526 `regexp' of `notregexp' element.
19528 If any of these conditions is met, this function returns the end point of
19529 the entity, causing the search to continue from there. This is a function
19530 that can be put into `org-agenda-skip-function' for the duration of a command."
19531 (let (beg end m r)
19532 (org-back-to-heading t)
19533 (setq beg (point)
19534 end (if subtree
19535 (progn (org-end-of-subtree t) (point))
19536 (progn (outline-next-heading) (1- (point)))))
19537 (goto-char beg)
19538 (and
19540 (and (memq 'scheduled conditions)
19541 (re-search-forward org-scheduled-time-regexp end t))
19542 (and (memq 'notscheduled conditions)
19543 (not (re-search-forward org-scheduled-time-regexp end t)))
19544 (and (memq 'deadline conditions)
19545 (re-search-forward org-deadline-time-regexp end t))
19546 (and (memq 'notdeadline conditions)
19547 (not (re-search-forward org-deadline-time-regexp end t)))
19548 (and (setq m (memq 'regexp conditions))
19549 (stringp (setq r (nth 1 m)))
19550 (re-search-forward (nth 1 m) end t))
19551 (and (setq m (memq 'notregexp conditions))
19552 (stringp (setq r (nth 1 m)))
19553 (not (re-search-forward (nth 1 m) end t))))
19554 end)))
19556 (defun org-agenda-list-stuck-projects (&rest ignore)
19557 "Create agenda view for projects that are stuck.
19558 Stuck projects are project that have no next actions. For the definitions
19559 of what a project is and how to check if it stuck, customize the variable
19560 `org-stuck-projects'.
19561 MATCH is being ignored."
19562 (interactive)
19563 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
19564 ;; FIXME: we could have used org-agenda-skip-if here.
19565 (org-agenda-overriding-header "List of stuck projects: ")
19566 (matcher (nth 0 org-stuck-projects))
19567 (todo (nth 1 org-stuck-projects))
19568 (todo-wds (if (member "*" todo)
19569 (progn
19570 (org-prepare-agenda-buffers (org-agenda-files))
19571 (org-delete-all
19572 org-done-keywords-for-agenda
19573 (copy-sequence org-todo-keywords-for-agenda)))
19574 todo))
19575 (todo-re (concat "^\\*+[ \t]+\\("
19576 (mapconcat 'identity todo-wds "\\|")
19577 "\\)\\>"))
19578 (tags (nth 2 org-stuck-projects))
19579 (tags-re (if (member "*" tags)
19580 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
19581 (concat "^\\*+ .*:\\("
19582 (mapconcat 'identity tags "\\|")
19583 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
19584 (gen-re (nth 3 org-stuck-projects))
19585 (re-list
19586 (delq nil
19587 (list
19588 (if todo todo-re)
19589 (if tags tags-re)
19590 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
19591 gen-re)))))
19592 (setq org-agenda-skip-regexp
19593 (if re-list
19594 (mapconcat 'identity re-list "\\|")
19595 (error "No information how to identify unstuck projects")))
19596 (org-tags-view nil matcher)
19597 (with-current-buffer org-agenda-buffer-name
19598 (setq org-agenda-redo-command
19599 '(org-agenda-list-stuck-projects
19600 (or current-prefix-arg org-last-arg))))))
19602 ;;; Diary integration
19604 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
19606 (defun org-get-entries-from-diary (date)
19607 "Get the (Emacs Calendar) diary entries for DATE."
19608 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
19609 (diary-display-hook '(fancy-diary-display))
19610 (pop-up-frames nil)
19611 (list-diary-entries-hook
19612 (cons 'org-diary-default-entry list-diary-entries-hook))
19613 (diary-file-name-prefix-function nil) ; turn this feature off
19614 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
19615 entries
19616 (org-disable-agenda-to-diary t))
19617 (save-excursion
19618 (save-window-excursion
19619 (funcall (if (fboundp 'diary-list-entries)
19620 'diary-list-entries 'list-diary-entries)
19621 date 1)))
19622 (if (not (get-buffer fancy-diary-buffer))
19623 (setq entries nil)
19624 (with-current-buffer fancy-diary-buffer
19625 (setq buffer-read-only nil)
19626 (if (zerop (buffer-size))
19627 ;; No entries
19628 (setq entries nil)
19629 ;; Omit the date and other unnecessary stuff
19630 (org-agenda-cleanup-fancy-diary)
19631 ;; Add prefix to each line and extend the text properties
19632 (if (zerop (buffer-size))
19633 (setq entries nil)
19634 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
19635 (set-buffer-modified-p nil)
19636 (kill-buffer fancy-diary-buffer)))
19637 (when entries
19638 (setq entries (org-split-string entries "\n"))
19639 (setq entries
19640 (mapcar
19641 (lambda (x)
19642 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
19643 ;; Extend the text properties to the beginning of the line
19644 (org-add-props x (text-properties-at (1- (length x)) x)
19645 'type "diary" 'date date))
19646 entries)))))
19648 (defun org-agenda-cleanup-fancy-diary ()
19649 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
19650 This gets rid of the date, the underline under the date, and
19651 the dummy entry installed by `org-mode' to ensure non-empty diary for each
19652 date. It also removes lines that contain only whitespace."
19653 (goto-char (point-min))
19654 (if (looking-at ".*?:[ \t]*")
19655 (progn
19656 (replace-match "")
19657 (re-search-forward "\n=+$" nil t)
19658 (replace-match "")
19659 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
19660 (re-search-forward "\n=+$" nil t)
19661 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
19662 (goto-char (point-min))
19663 (while (re-search-forward "^ +\n" nil t)
19664 (replace-match ""))
19665 (goto-char (point-min))
19666 (if (re-search-forward "^Org-mode dummy\n?" nil t)
19667 (replace-match "")))
19669 ;; Make sure entries from the diary have the right text properties.
19670 (eval-after-load "diary-lib"
19671 '(if (boundp 'diary-modify-entry-list-string-function)
19672 ;; We can rely on the hook, nothing to do
19674 ;; Hook not avaiable, must use advice to make this work
19675 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
19676 "Make the position visible."
19677 (if (and org-disable-agenda-to-diary ;; called from org-agenda
19678 (stringp string)
19679 buffer-file-name)
19680 (setq string (org-modify-diary-entry-string string))))))
19682 (defun org-modify-diary-entry-string (string)
19683 "Add text properties to string, allowing org-mode to act on it."
19684 (org-add-props string nil
19685 'mouse-face 'highlight
19686 'keymap org-agenda-keymap
19687 'help-echo (if buffer-file-name
19688 (format "mouse-2 or RET jump to diary file %s"
19689 (abbreviate-file-name buffer-file-name))
19691 'org-agenda-diary-link t
19692 'org-marker (org-agenda-new-marker (point-at-bol))))
19694 (defun org-diary-default-entry ()
19695 "Add a dummy entry to the diary.
19696 Needed to avoid empty dates which mess up holiday display."
19697 ;; Catch the error if dealing with the new add-to-diary-alist
19698 (when org-disable-agenda-to-diary
19699 (condition-case nil
19700 (add-to-diary-list original-date "Org-mode dummy" "")
19701 (error
19702 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
19704 ;;;###autoload
19705 (defun org-diary (&rest args)
19706 "Return diary information from org-files.
19707 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
19708 It accesses org files and extracts information from those files to be
19709 listed in the diary. The function accepts arguments specifying what
19710 items should be listed. The following arguments are allowed:
19712 :timestamp List the headlines of items containing a date stamp or
19713 date range matching the selected date. Deadlines will
19714 also be listed, on the expiration day.
19716 :sexp List entries resulting from diary-like sexps.
19718 :deadline List any deadlines past due, or due within
19719 `org-deadline-warning-days'. The listing occurs only
19720 in the diary for *today*, not at any other date. If
19721 an entry is marked DONE, it is no longer listed.
19723 :scheduled List all items which are scheduled for the given date.
19724 The diary for *today* also contains items which were
19725 scheduled earlier and are not yet marked DONE.
19727 :todo List all TODO items from the org-file. This may be a
19728 long list - so this is not turned on by default.
19729 Like deadlines, these entries only show up in the
19730 diary for *today*, not at any other date.
19732 The call in the diary file should look like this:
19734 &%%(org-diary) ~/path/to/some/orgfile.org
19736 Use a separate line for each org file to check. Or, if you omit the file name,
19737 all files listed in `org-agenda-files' will be checked automatically:
19739 &%%(org-diary)
19741 If you don't give any arguments (as in the example above), the default
19742 arguments (:deadline :scheduled :timestamp :sexp) are used.
19743 So the example above may also be written as
19745 &%%(org-diary :deadline :timestamp :sexp :scheduled)
19747 The function expects the lisp variables `entry' and `date' to be provided
19748 by the caller, because this is how the calendar works. Don't use this
19749 function from a program - use `org-agenda-get-day-entries' instead."
19750 (org-agenda-maybe-reset-markers)
19751 (org-compile-prefix-format 'agenda)
19752 (org-set-sorting-strategy 'agenda)
19753 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19754 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
19755 (list entry)
19756 (org-agenda-files t)))
19757 file rtn results)
19758 (org-prepare-agenda-buffers files)
19759 ;; If this is called during org-agenda, don't return any entries to
19760 ;; the calendar. Org Agenda will list these entries itself.
19761 (if org-disable-agenda-to-diary (setq files nil))
19762 (while (setq file (pop files))
19763 (setq rtn (apply 'org-agenda-get-day-entries file date args))
19764 (setq results (append results rtn)))
19765 (if results
19766 (concat (org-finalize-agenda-entries results) "\n"))))
19768 ;;; Agenda entry finders
19770 (defun org-agenda-get-day-entries (file date &rest args)
19771 "Does the work for `org-diary' and `org-agenda'.
19772 FILE is the path to a file to be checked for entries. DATE is date like
19773 the one returned by `calendar-current-date'. ARGS are symbols indicating
19774 which kind of entries should be extracted. For details about these, see
19775 the documentation of `org-diary'."
19776 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
19777 (let* ((org-startup-folded nil)
19778 (org-startup-align-all-tables nil)
19779 (buffer (if (file-exists-p file)
19780 (org-get-agenda-file-buffer file)
19781 (error "No such file %s" file)))
19782 arg results rtn)
19783 (if (not buffer)
19784 ;; If file does not exist, make sure an error message ends up in diary
19785 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19786 (with-current-buffer buffer
19787 (unless (org-mode-p)
19788 (error "Agenda file %s is not in `org-mode'" file))
19789 (let ((case-fold-search nil))
19790 (save-excursion
19791 (save-restriction
19792 (if org-agenda-restrict
19793 (narrow-to-region org-agenda-restrict-begin
19794 org-agenda-restrict-end)
19795 (widen))
19796 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
19797 (while (setq arg (pop args))
19798 (cond
19799 ((and (eq arg :todo)
19800 (equal date (calendar-current-date)))
19801 (setq rtn (org-agenda-get-todos))
19802 (setq results (append results rtn)))
19803 ((eq arg :timestamp)
19804 (setq rtn (org-agenda-get-blocks))
19805 (setq results (append results rtn))
19806 (setq rtn (org-agenda-get-timestamps))
19807 (setq results (append results rtn)))
19808 ((eq arg :sexp)
19809 (setq rtn (org-agenda-get-sexps))
19810 (setq results (append results rtn)))
19811 ((eq arg :scheduled)
19812 (setq rtn (org-agenda-get-scheduled))
19813 (setq results (append results rtn)))
19814 ((eq arg :closed)
19815 (setq rtn (org-agenda-get-closed))
19816 (setq results (append results rtn)))
19817 ((eq arg :deadline)
19818 (setq rtn (org-agenda-get-deadlines))
19819 (setq results (append results rtn))))))))
19820 results))))
19822 ;; FIXME: this works only if the cursor is *not* at the
19823 ;; beginning of the entry
19824 ;(defun org-entry-is-done-p ()
19825 ; "Is the current entry marked DONE?"
19826 ; (save-excursion
19827 ; (and (re-search-backward "[\r\n]\\*+ " nil t)
19828 ; (looking-at org-nl-done-regexp))))
19830 (defun org-entry-is-todo-p ()
19831 (member (org-get-todo-state) org-not-done-keywords))
19833 (defun org-entry-is-done-p ()
19834 (member (org-get-todo-state) org-done-keywords))
19836 (defun org-get-todo-state ()
19837 (save-excursion
19838 (org-back-to-heading t)
19839 (and (looking-at org-todo-line-regexp)
19840 (match-end 2)
19841 (match-string 2))))
19843 (defun org-at-date-range-p (&optional inactive-ok)
19844 "Is the cursor inside a date range?"
19845 (interactive)
19846 (save-excursion
19847 (catch 'exit
19848 (let ((pos (point)))
19849 (skip-chars-backward "^[<\r\n")
19850 (skip-chars-backward "<[")
19851 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19852 (>= (match-end 0) pos)
19853 (throw 'exit t))
19854 (skip-chars-backward "^<[\r\n")
19855 (skip-chars-backward "<[")
19856 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
19857 (>= (match-end 0) pos)
19858 (throw 'exit t)))
19859 nil)))
19861 (defun org-agenda-get-todos ()
19862 "Return the TODO information for agenda display."
19863 (let* ((props (list 'face nil
19864 'done-face 'org-done
19865 'org-not-done-regexp org-not-done-regexp
19866 'org-todo-regexp org-todo-regexp
19867 'mouse-face 'highlight
19868 'keymap org-agenda-keymap
19869 'help-echo
19870 (format "mouse-2 or RET jump to org file %s"
19871 (abbreviate-file-name buffer-file-name))))
19872 ;; FIXME: get rid of the \n at some point but watch out
19873 (regexp (concat "^\\*+[ \t]+\\("
19874 (if org-select-this-todo-keyword
19875 (if (equal org-select-this-todo-keyword "*")
19876 org-todo-regexp
19877 (concat "\\<\\("
19878 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
19879 "\\)\\>"))
19880 org-not-done-regexp)
19881 "[^\n\r]*\\)"))
19882 marker priority category tags
19883 ee txt beg end)
19884 (goto-char (point-min))
19885 (while (re-search-forward regexp nil t)
19886 (catch :skip
19887 (save-match-data
19888 (beginning-of-line)
19889 (setq beg (point) end (progn (outline-next-heading) (point)))
19890 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
19891 (re-search-forward org-ts-regexp end t))
19892 (and org-agenda-todo-ignore-scheduled (goto-char beg)
19893 (re-search-forward org-scheduled-time-regexp end t))
19894 (and org-agenda-todo-ignore-deadlines (goto-char beg)
19895 (re-search-forward org-deadline-time-regexp end t)
19896 (org-deadline-close (match-string 1))))
19897 (goto-char (1+ beg))
19898 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
19899 (throw :skip nil)))
19900 (goto-char beg)
19901 (org-agenda-skip)
19902 (goto-char (match-beginning 1))
19903 (setq marker (org-agenda-new-marker (match-beginning 0))
19904 category (org-get-category)
19905 tags (org-get-tags-at (point))
19906 txt (org-format-agenda-item "" (match-string 1) category tags)
19907 priority (1+ (org-get-priority txt)))
19908 (org-add-props txt props
19909 'org-marker marker 'org-hd-marker marker
19910 'priority priority 'org-category category
19911 'type "todo")
19912 (push txt ee)
19913 (if org-agenda-todo-list-sublevels
19914 (goto-char (match-end 1))
19915 (org-end-of-subtree 'invisible))))
19916 (nreverse ee)))
19918 (defconst org-agenda-no-heading-message
19919 "No heading for this item in buffer or region.")
19921 (defun org-agenda-get-timestamps ()
19922 "Return the date stamp information for agenda display."
19923 (let* ((props (list 'face nil
19924 'org-not-done-regexp org-not-done-regexp
19925 'org-todo-regexp org-todo-regexp
19926 'mouse-face 'highlight
19927 'keymap org-agenda-keymap
19928 'help-echo
19929 (format "mouse-2 or RET jump to org file %s"
19930 (abbreviate-file-name buffer-file-name))))
19931 (d1 (calendar-absolute-from-gregorian date))
19932 (remove-re
19933 (concat
19934 (regexp-quote
19935 (format-time-string
19936 "<%Y-%m-%d"
19937 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
19938 ".*?>"))
19939 (regexp
19940 (concat
19941 (regexp-quote
19942 (substring
19943 (format-time-string
19944 (car org-time-stamp-formats)
19945 (apply 'encode-time ; DATE bound by calendar
19946 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
19947 0 11))
19948 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
19949 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
19950 marker hdmarker deadlinep scheduledp donep tmp priority category
19951 ee txt timestr tags b0 b3 e3)
19952 (goto-char (point-min))
19953 (while (re-search-forward regexp nil t)
19954 (setq b0 (match-beginning 0)
19955 b3 (match-beginning 3) e3 (match-end 3))
19956 (catch :skip
19957 (and (org-at-date-range-p) (throw :skip nil))
19958 (org-agenda-skip)
19959 (if (and (match-end 1)
19960 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
19961 (throw :skip nil))
19962 (if (and e3
19963 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
19964 (throw :skip nil))
19965 (setq marker (org-agenda-new-marker b0)
19966 category (org-get-category b0)
19967 tmp (buffer-substring (max (point-min)
19968 (- b0 org-ds-keyword-length))
19970 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
19971 deadlinep (string-match org-deadline-regexp tmp)
19972 scheduledp (string-match org-scheduled-regexp tmp)
19973 donep (org-entry-is-done-p))
19974 (if (or scheduledp deadlinep) (throw :skip t))
19975 (if (string-match ">" timestr)
19976 ;; substring should only run to end of time stamp
19977 (setq timestr (substring timestr 0 (match-end 0))))
19978 (save-excursion
19979 (if (re-search-backward "^\\*+ " nil t)
19980 (progn
19981 (goto-char (match-beginning 0))
19982 (setq hdmarker (org-agenda-new-marker)
19983 tags (org-get-tags-at))
19984 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
19985 (setq txt (org-format-agenda-item
19986 nil (match-string 1) category tags timestr nil
19987 remove-re)))
19988 (setq txt org-agenda-no-heading-message))
19989 (setq priority (org-get-priority txt))
19990 (org-add-props txt props
19991 'org-marker marker 'org-hd-marker hdmarker)
19992 (org-add-props txt nil 'priority priority
19993 'org-category category 'date date
19994 'type "timestamp")
19995 (push txt ee))
19996 (outline-next-heading)))
19997 (nreverse ee)))
19999 (defun org-agenda-get-sexps ()
20000 "Return the sexp information for agenda display."
20001 (require 'diary-lib)
20002 (let* ((props (list 'face nil
20003 'mouse-face 'highlight
20004 'keymap org-agenda-keymap
20005 'help-echo
20006 (format "mouse-2 or RET jump to org file %s"
20007 (abbreviate-file-name buffer-file-name))))
20008 (regexp "^&?%%(")
20009 marker category ee txt tags entry result beg b sexp sexp-entry)
20010 (goto-char (point-min))
20011 (while (re-search-forward regexp nil t)
20012 (catch :skip
20013 (org-agenda-skip)
20014 (setq beg (match-beginning 0))
20015 (goto-char (1- (match-end 0)))
20016 (setq b (point))
20017 (forward-sexp 1)
20018 (setq sexp (buffer-substring b (point)))
20019 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20020 (org-trim (match-string 1))
20021 ""))
20022 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20023 (when result
20024 (setq marker (org-agenda-new-marker beg)
20025 category (org-get-category beg))
20027 (if (string-match "\\S-" result)
20028 (setq txt result)
20029 (setq txt "SEXP entry returned empty string"))
20031 (setq txt (org-format-agenda-item
20032 "" txt category tags 'time))
20033 (org-add-props txt props 'org-marker marker)
20034 (org-add-props txt nil
20035 'org-category category 'date date
20036 'type "sexp")
20037 (push txt ee))))
20038 (nreverse ee)))
20040 (defun org-agenda-get-closed ()
20041 "Return the logged TODO entries for agenda display."
20042 (let* ((props (list 'mouse-face 'highlight
20043 'org-not-done-regexp org-not-done-regexp
20044 'org-todo-regexp org-todo-regexp
20045 'keymap org-agenda-keymap
20046 'help-echo
20047 (format "mouse-2 or RET jump to org file %s"
20048 (abbreviate-file-name buffer-file-name))))
20049 (regexp (concat
20050 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20051 (regexp-quote
20052 (substring
20053 (format-time-string
20054 (car org-time-stamp-formats)
20055 (apply 'encode-time ; DATE bound by calendar
20056 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20057 1 11))))
20058 marker hdmarker priority category tags closedp
20059 ee txt timestr)
20060 (goto-char (point-min))
20061 (while (re-search-forward regexp nil t)
20062 (catch :skip
20063 (org-agenda-skip)
20064 (setq marker (org-agenda-new-marker (match-beginning 0))
20065 closedp (equal (match-string 1) org-closed-string)
20066 category (org-get-category (match-beginning 0))
20067 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20068 ;; donep (org-entry-is-done-p)
20070 (if (string-match "\\]" timestr)
20071 ;; substring should only run to end of time stamp
20072 (setq timestr (substring timestr 0 (match-end 0))))
20073 (save-excursion
20074 (if (re-search-backward "^\\*+ " nil t)
20075 (progn
20076 (goto-char (match-beginning 0))
20077 (setq hdmarker (org-agenda-new-marker)
20078 tags (org-get-tags-at))
20079 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20080 (setq txt (org-format-agenda-item
20081 (if closedp "Closed: " "Clocked: ")
20082 (match-string 1) category tags timestr)))
20083 (setq txt org-agenda-no-heading-message))
20084 (setq priority 100000)
20085 (org-add-props txt props
20086 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20087 'priority priority 'org-category category
20088 'type "closed" 'date date
20089 'undone-face 'org-warning 'done-face 'org-done)
20090 (push txt ee))
20091 (outline-next-heading)))
20092 (nreverse ee)))
20094 (defun org-agenda-get-deadlines ()
20095 "Return the deadline information for agenda display."
20096 (let* ((props (list 'mouse-face 'highlight
20097 'org-not-done-regexp org-not-done-regexp
20098 'org-todo-regexp org-todo-regexp
20099 'keymap org-agenda-keymap
20100 'help-echo
20101 (format "mouse-2 or RET jump to org file %s"
20102 (abbreviate-file-name buffer-file-name))))
20103 (regexp org-deadline-time-regexp)
20104 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20105 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20106 d2 diff dfrac wdays pos pos1 category tags
20107 ee txt head face s upcomingp donep timestr)
20108 (goto-char (point-min))
20109 (while (re-search-forward regexp nil t)
20110 (catch :skip
20111 (org-agenda-skip)
20112 (setq s (match-string 1)
20113 pos (1- (match-beginning 1))
20114 d2 (org-time-string-to-absolute (match-string 1) d1)
20115 diff (- d2 d1)
20116 wdays (org-get-wdays s)
20117 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20118 upcomingp (and todayp (> diff 0)))
20119 ;; When to show a deadline in the calendar:
20120 ;; If the expiration is within wdays warning time.
20121 ;; Past-due deadlines are only shown on the current date
20122 (if (or (and (<= diff wdays)
20123 (and todayp (not org-agenda-only-exact-dates)))
20124 (= diff 0))
20125 (save-excursion
20126 (setq category (org-get-category))
20127 (if (re-search-backward "^\\*+[ \t]+" nil t)
20128 (progn
20129 (goto-char (match-end 0))
20130 (setq pos1 (match-beginning 0))
20131 (setq tags (org-get-tags-at pos1))
20132 (setq head (buffer-substring-no-properties
20133 (point)
20134 (progn (skip-chars-forward "^\r\n")
20135 (point))))
20136 (setq donep (string-match org-looking-at-done-regexp head))
20137 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20138 (setq timestr
20139 (concat (substring s (match-beginning 1)) " "))
20140 (setq timestr 'time))
20141 (if (and donep
20142 (or org-agenda-skip-deadline-if-done
20143 (not (= diff 0))))
20144 (setq txt nil)
20145 (setq txt (org-format-agenda-item
20146 (if (= diff 0)
20147 (car org-agenda-deadline-leaders)
20148 (format (nth 1 org-agenda-deadline-leaders)
20149 diff))
20150 head category tags timestr))))
20151 (setq txt org-agenda-no-heading-message))
20152 (when txt
20153 (setq face (org-agenda-deadline-face dfrac))
20154 (org-add-props txt props
20155 'org-marker (org-agenda-new-marker pos)
20156 'org-hd-marker (org-agenda-new-marker pos1)
20157 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20158 (org-get-priority txt))
20159 'org-category category
20160 'type (if upcomingp "upcoming-deadline" "deadline")
20161 'date (if upcomingp date d2)
20162 'face (if donep 'org-done face)
20163 'undone-face face 'done-face 'org-done)
20164 (push txt ee))))))
20165 (nreverse ee)))
20167 (defun org-agenda-deadline-face (fraction)
20168 "Return the face to displaying a deadline item.
20169 FRACTION is what fraction of the head-warning time has passed."
20170 (let ((faces org-agenda-deadline-faces) f)
20171 (catch 'exit
20172 (while (setq f (pop faces))
20173 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20175 (defun org-agenda-get-scheduled ()
20176 "Return the scheduled information for agenda display."
20177 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20178 'org-todo-regexp org-todo-regexp
20179 'done-face 'org-done
20180 'mouse-face 'highlight
20181 'keymap org-agenda-keymap
20182 'help-echo
20183 (format "mouse-2 or RET jump to org file %s"
20184 (abbreviate-file-name buffer-file-name))))
20185 (regexp org-scheduled-time-regexp)
20186 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20187 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20188 d2 diff pos pos1 category tags
20189 ee txt head pastschedp donep face timestr s)
20190 (goto-char (point-min))
20191 (while (re-search-forward regexp nil t)
20192 (catch :skip
20193 (org-agenda-skip)
20194 (setq s (match-string 1)
20195 pos (1- (match-beginning 1))
20196 d2 (org-time-string-to-absolute (match-string 1) d1)
20197 diff (- d2 d1))
20198 (setq pastschedp (and todayp (< diff 0)))
20199 ;; When to show a scheduled item in the calendar:
20200 ;; If it is on or past the date.
20201 (if (or (and (< diff 0)
20202 (and todayp (not org-agenda-only-exact-dates)))
20203 (= diff 0))
20204 (save-excursion
20205 (setq category (org-get-category))
20206 (if (re-search-backward "^\\*+[ \t]+" nil t)
20207 (progn
20208 (goto-char (match-end 0))
20209 (setq pos1 (match-beginning 0))
20210 (setq tags (org-get-tags-at))
20211 (setq head (buffer-substring-no-properties
20212 (point)
20213 (progn (skip-chars-forward "^\r\n") (point))))
20214 (setq donep (string-match org-looking-at-done-regexp head))
20215 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20216 (setq timestr
20217 (concat (substring s (match-beginning 1)) " "))
20218 (setq timestr 'time))
20219 (if (and donep
20220 (or org-agenda-skip-scheduled-if-done
20221 (not (= diff 0))))
20222 (setq txt nil)
20223 (setq txt (org-format-agenda-item
20224 (if (= diff 0)
20225 (car org-agenda-scheduled-leaders)
20226 (format (nth 1 org-agenda-scheduled-leaders)
20227 (- 1 diff)))
20228 head category tags timestr))))
20229 (setq txt org-agenda-no-heading-message))
20230 (when txt
20231 (setq face (if pastschedp
20232 'org-scheduled-previously
20233 'org-scheduled-today))
20234 (org-add-props txt props
20235 'undone-face face
20236 'face (if donep 'org-done face)
20237 'org-marker (org-agenda-new-marker pos)
20238 'org-hd-marker (org-agenda-new-marker pos1)
20239 'type (if pastschedp "past-scheduled" "scheduled")
20240 'date (if pastschedp d2 date)
20241 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20242 'org-category category)
20243 (push txt ee))))))
20244 (nreverse ee)))
20246 (defun org-agenda-get-blocks ()
20247 "Return the date-range information for agenda display."
20248 (let* ((props (list 'face nil
20249 'org-not-done-regexp org-not-done-regexp
20250 'org-todo-regexp org-todo-regexp
20251 'mouse-face 'highlight
20252 'keymap org-agenda-keymap
20253 'help-echo
20254 (format "mouse-2 or RET jump to org file %s"
20255 (abbreviate-file-name buffer-file-name))))
20256 (regexp org-tr-regexp)
20257 (d0 (calendar-absolute-from-gregorian date))
20258 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
20259 (goto-char (point-min))
20260 (while (re-search-forward regexp nil t)
20261 (catch :skip
20262 (org-agenda-skip)
20263 (setq pos (point))
20264 (setq timestr (match-string 0)
20265 s1 (match-string 1)
20266 s2 (match-string 2)
20267 d1 (time-to-days (org-time-string-to-time s1))
20268 d2 (time-to-days (org-time-string-to-time s2)))
20269 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20270 ;; Only allow days between the limits, because the normal
20271 ;; date stamps will catch the limits.
20272 (save-excursion
20273 (setq marker (org-agenda-new-marker (point)))
20274 (setq category (org-get-category))
20275 (if (re-search-backward "^\\*+ " nil t)
20276 (progn
20277 (goto-char (match-beginning 0))
20278 (setq hdmarker (org-agenda-new-marker (point)))
20279 (setq tags (org-get-tags-at))
20280 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20281 (setq txt (org-format-agenda-item
20282 (format (if (= d1 d2) "" "(%d/%d): ")
20283 (1+ (- d0 d1)) (1+ (- d2 d1)))
20284 (match-string 1) category tags
20285 (if (= d0 d1) timestr))))
20286 (setq txt org-agenda-no-heading-message))
20287 (org-add-props txt props
20288 'org-marker marker 'org-hd-marker hdmarker
20289 'type "block" 'date date
20290 'priority (org-get-priority txt) 'org-category category)
20291 (push txt ee)))
20292 (goto-char pos)))
20293 ;; Sort the entries by expiration date.
20294 (nreverse ee)))
20296 ;;; Agenda presentation and sorting
20298 (defconst org-plain-time-of-day-regexp
20299 (concat
20300 "\\(\\<[012]?[0-9]"
20301 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20302 "\\(--?"
20303 "\\(\\<[012]?[0-9]"
20304 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20305 "\\)?")
20306 "Regular expression to match a plain time or time range.
20307 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20308 groups carry important information:
20309 0 the full match
20310 1 the first time, range or not
20311 8 the second time, if it is a range.")
20313 (defconst org-plain-time-extension-regexp
20314 (concat
20315 "\\(\\<[012]?[0-9]"
20316 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20317 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20318 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20319 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20320 groups carry important information:
20321 0 the full match
20322 7 hours of duration
20323 9 minutes of duration")
20325 (defconst org-stamp-time-of-day-regexp
20326 (concat
20327 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20328 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20329 "\\(--?"
20330 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20331 "Regular expression to match a timestamp time or time range.
20332 After a match, the following groups carry important information:
20333 0 the full match
20334 1 date plus weekday, for backreferencing to make sure both times on same day
20335 2 the first time, range or not
20336 4 the second time, if it is a range.")
20338 (defvar org-prefix-has-time nil
20339 "A flag, set by `org-compile-prefix-format'.
20340 The flag is set if the currently compiled format contains a `%t'.")
20341 (defvar org-prefix-has-tag nil
20342 "A flag, set by `org-compile-prefix-format'.
20343 The flag is set if the currently compiled format contains a `%T'.")
20345 (defun org-format-agenda-item (extra txt &optional category tags dotime
20346 noprefix remove-re)
20347 "Format TXT to be inserted into the agenda buffer.
20348 In particular, it adds the prefix and corresponding text properties. EXTRA
20349 must be a string and replaces the `%s' specifier in the prefix format.
20350 CATEGORY (string, symbol or nil) may be used to overrule the default
20351 category taken from local variable or file name. It will replace the `%c'
20352 specifier in the format. DOTIME, when non-nil, indicates that a
20353 time-of-day should be extracted from TXT for sorting of this entry, and for
20354 the `%t' specifier in the format. When DOTIME is a string, this string is
20355 searched for a time before TXT is. NOPREFIX is a flag and indicates that
20356 only the correctly processes TXT should be returned - this is used by
20357 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
20358 Any match of REMOVE-RE will be removed from TXT."
20359 (save-match-data
20360 ;; Diary entries sometimes have extra whitespace at the beginning
20361 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
20362 (let* ((category (or category
20363 org-category
20364 (if buffer-file-name
20365 (file-name-sans-extension
20366 (file-name-nondirectory buffer-file-name))
20367 "")))
20368 (tag (if tags (nth (1- (length tags)) tags) ""))
20369 time ; time and tag are needed for the eval of the prefix format
20370 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
20371 (time-of-day (and dotime (org-get-time-of-day ts)))
20372 stamp plain s0 s1 s2 rtn srp)
20373 (when (and dotime time-of-day org-prefix-has-time)
20374 ;; Extract starting and ending time and move them to prefix
20375 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
20376 (setq plain (string-match org-plain-time-of-day-regexp ts)))
20377 (setq s0 (match-string 0 ts)
20378 srp (and stamp (match-end 3))
20379 s1 (match-string (if plain 1 2) ts)
20380 s2 (match-string (if plain 8 (if srp 4 6)) ts))
20382 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
20383 ;; them, we might want to remove them there to avoid duplication.
20384 ;; The user can turn this off with a variable.
20385 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
20386 (string-match (concat (regexp-quote s0) " *") txt)
20387 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
20388 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
20389 (= (match-beginning 0) 0)
20391 (setq txt (replace-match "" nil nil txt))))
20392 ;; Normalize the time(s) to 24 hour
20393 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
20394 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
20396 (when (and s1 (not s2) org-agenda-default-appointment-duration
20397 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
20398 (let ((m (+ (string-to-number (match-string 2 s1))
20399 (* 60 (string-to-number (match-string 1 s1)))
20400 org-agenda-default-appointment-duration))
20402 (setq h (/ m 60) m (- m (* h 60)))
20403 (setq s2 (format "%02d:%02d" h m))))
20405 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20406 txt)
20407 ;; Tags are in the string
20408 (if (or (eq org-agenda-remove-tags t)
20409 (and org-agenda-remove-tags
20410 org-prefix-has-tag))
20411 (setq txt (replace-match "" t t txt))
20412 (setq txt (replace-match
20413 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
20414 (match-string 2 txt))
20415 t t txt))))
20417 (when remove-re
20418 (while (string-match remove-re txt)
20419 (setq txt (replace-match "" t t txt))))
20421 ;; Create the final string
20422 (if noprefix
20423 (setq rtn txt)
20424 ;; Prepare the variables needed in the eval of the compiled format
20425 (setq time (cond (s2 (concat s1 "-" s2))
20426 (s1 (concat s1 "......"))
20427 (t ""))
20428 extra (or extra "")
20429 category (if (symbolp category) (symbol-name category) category))
20430 ;; Evaluate the compiled format
20431 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
20433 ;; And finally add the text properties
20434 (org-add-props rtn nil
20435 'org-category (downcase category) 'tags tags
20436 'org-highest-priority org-highest-priority
20437 'org-lowest-priority org-lowest-priority
20438 'prefix-length (- (length rtn) (length txt))
20439 'time-of-day time-of-day
20440 'txt txt
20441 'time time
20442 'extra extra
20443 'dotime dotime))))
20445 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
20446 (defvar org-agenda-sorting-strategy-selected nil)
20448 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
20449 (catch 'exit
20450 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
20451 ((and todayp (member 'today (car org-agenda-time-grid))))
20452 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
20453 ((member 'weekly (car org-agenda-time-grid)))
20454 (t (throw 'exit list)))
20455 (let* ((have (delq nil (mapcar
20456 (lambda (x) (get-text-property 1 'time-of-day x))
20457 list)))
20458 (string (nth 1 org-agenda-time-grid))
20459 (gridtimes (nth 2 org-agenda-time-grid))
20460 (req (car org-agenda-time-grid))
20461 (remove (member 'remove-match req))
20462 new time)
20463 (if (and (member 'require-timed req) (not have))
20464 ;; don't show empty grid
20465 (throw 'exit list))
20466 (while (setq time (pop gridtimes))
20467 (unless (and remove (member time have))
20468 (setq time (int-to-string time))
20469 (push (org-format-agenda-item
20470 nil string "" nil
20471 (concat (substring time 0 -2) ":" (substring time -2)))
20472 new)
20473 (put-text-property
20474 1 (length (car new)) 'face 'org-time-grid (car new))))
20475 (if (member 'time-up org-agenda-sorting-strategy-selected)
20476 (append new list)
20477 (append list new)))))
20479 (defun org-compile-prefix-format (key)
20480 "Compile the prefix format into a Lisp form that can be evaluated.
20481 The resulting form is returned and stored in the variable
20482 `org-prefix-format-compiled'."
20483 (setq org-prefix-has-time nil org-prefix-has-tag nil)
20484 (let ((s (cond
20485 ((stringp org-agenda-prefix-format)
20486 org-agenda-prefix-format)
20487 ((assq key org-agenda-prefix-format)
20488 (cdr (assq key org-agenda-prefix-format)))
20489 (t " %-12:c%?-12t% s")))
20490 (start 0)
20491 varform vars var e c f opt)
20492 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
20493 s start)
20494 (setq var (cdr (assoc (match-string 4 s)
20495 '(("c" . category) ("t" . time) ("s" . extra)
20496 ("T" . tag))))
20497 c (or (match-string 3 s) "")
20498 opt (match-beginning 1)
20499 start (1+ (match-beginning 0)))
20500 (if (equal var 'time) (setq org-prefix-has-time t))
20501 (if (equal var 'tag) (setq org-prefix-has-tag t))
20502 (setq f (concat "%" (match-string 2 s) "s"))
20503 (if opt
20504 (setq varform
20505 `(if (equal "" ,var)
20507 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
20508 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
20509 (setq s (replace-match "%s" t nil s))
20510 (push varform vars))
20511 (setq vars (nreverse vars))
20512 (setq org-prefix-format-compiled `(format ,s ,@vars))))
20514 (defun org-set-sorting-strategy (key)
20515 (if (symbolp (car org-agenda-sorting-strategy))
20516 ;; the old format
20517 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
20518 (setq org-agenda-sorting-strategy-selected
20519 (or (cdr (assq key org-agenda-sorting-strategy))
20520 (cdr (assq 'agenda org-agenda-sorting-strategy))
20521 '(time-up category-keep priority-down)))))
20523 (defun org-get-time-of-day (s &optional string mod24)
20524 "Check string S for a time of day.
20525 If found, return it as a military time number between 0 and 2400.
20526 If not found, return nil.
20527 The optional STRING argument forces conversion into a 5 character wide string
20528 HH:MM."
20529 (save-match-data
20530 (when
20531 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
20532 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
20533 (let* ((h (string-to-number (match-string 1 s)))
20534 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
20535 (ampm (if (match-end 4) (downcase (match-string 4 s))))
20536 (am-p (equal ampm "am"))
20537 (h1 (cond ((not ampm) h)
20538 ((= h 12) (if am-p 0 12))
20539 (t (+ h (if am-p 0 12)))))
20540 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
20541 (mod h1 24) h1))
20542 (t0 (+ (* 100 h2) m))
20543 (t1 (concat (if (>= h1 24) "+" " ")
20544 (if (< t0 100) "0" "")
20545 (if (< t0 10) "0" "")
20546 (int-to-string t0))))
20547 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
20549 (defun org-finalize-agenda-entries (list &optional nosort)
20550 "Sort and concatenate the agenda items."
20551 (setq list (mapcar 'org-agenda-highlight-todo list))
20552 (if nosort
20553 list
20554 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
20556 (defun org-agenda-highlight-todo (x)
20557 (let (re pl)
20558 (if (eq x 'line)
20559 (save-excursion
20560 (beginning-of-line 1)
20561 (setq re (get-text-property (point) 'org-todo-regexp))
20562 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
20563 (and (looking-at (concat "[ \t]*\\.*" re))
20564 (add-text-properties (match-beginning 0) (match-end 0)
20565 (list 'face (org-get-todo-face 0)))))
20566 (setq re (concat (get-text-property 0 'org-todo-regexp x))
20567 pl (get-text-property 0 'prefix-length x))
20568 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
20569 (add-text-properties
20570 (or (match-end 1) (match-end 0)) (match-end 0)
20571 (list 'face (org-get-todo-face (match-string 2 x)))
20573 x)))
20575 (defsubst org-cmp-priority (a b)
20576 "Compare the priorities of string A and B."
20577 (let ((pa (or (get-text-property 1 'priority a) 0))
20578 (pb (or (get-text-property 1 'priority b) 0)))
20579 (cond ((> pa pb) +1)
20580 ((< pa pb) -1)
20581 (t nil))))
20583 (defsubst org-cmp-category (a b)
20584 "Compare the string values of categories of strings A and B."
20585 (let ((ca (or (get-text-property 1 'org-category a) ""))
20586 (cb (or (get-text-property 1 'org-category b) "")))
20587 (cond ((string-lessp ca cb) -1)
20588 ((string-lessp cb ca) +1)
20589 (t nil))))
20591 (defsubst org-cmp-tag (a b)
20592 "Compare the string values of categories of strings A and B."
20593 (let ((ta (car (last (get-text-property 1 'tags a))))
20594 (tb (car (last (get-text-property 1 'tags b)))))
20595 (cond ((not ta) +1)
20596 ((not tb) -1)
20597 ((string-lessp ta tb) -1)
20598 ((string-lessp tb ta) +1)
20599 (t nil))))
20601 (defsubst org-cmp-time (a b)
20602 "Compare the time-of-day values of strings A and B."
20603 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
20604 (ta (or (get-text-property 1 'time-of-day a) def))
20605 (tb (or (get-text-property 1 'time-of-day b) def)))
20606 (cond ((< ta tb) -1)
20607 ((< tb ta) +1)
20608 (t nil))))
20610 (defun org-entries-lessp (a b)
20611 "Predicate for sorting agenda entries."
20612 ;; The following variables will be used when the form is evaluated.
20613 ;; So even though the compiler complains, keep them.
20614 (let* ((time-up (org-cmp-time a b))
20615 (time-down (if time-up (- time-up) nil))
20616 (priority-up (org-cmp-priority a b))
20617 (priority-down (if priority-up (- priority-up) nil))
20618 (category-up (org-cmp-category a b))
20619 (category-down (if category-up (- category-up) nil))
20620 (category-keep (if category-up +1 nil))
20621 (tag-up (org-cmp-tag a b))
20622 (tag-down (if tag-up (- tag-up) nil)))
20623 (cdr (assoc
20624 (eval (cons 'or org-agenda-sorting-strategy-selected))
20625 '((-1 . t) (1 . nil) (nil . nil))))))
20627 ;;; Agenda commands
20629 (defun org-agenda-check-type (error &rest types)
20630 "Check if agenda buffer is of allowed type.
20631 If ERROR is non-nil, throw an error, otherwise just return nil."
20632 (if (memq org-agenda-type types)
20634 (if error
20635 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
20636 nil)))
20638 (defun org-agenda-quit ()
20639 "Exit agenda by removing the window or the buffer."
20640 (interactive)
20641 (let ((buf (current-buffer)))
20642 (if (not (one-window-p)) (delete-window))
20643 (kill-buffer buf)
20644 (org-agenda-maybe-reset-markers 'force)
20645 (org-columns-remove-overlays))
20646 ;; Maybe restore the pre-agenda window configuration.
20647 (and org-agenda-restore-windows-after-quit
20648 (not (eq org-agenda-window-setup 'other-frame))
20649 org-pre-agenda-window-conf
20650 (set-window-configuration org-pre-agenda-window-conf)))
20652 (defun org-agenda-exit ()
20653 "Exit agenda by removing the window or the buffer.
20654 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
20655 Org-mode buffers visited directly by the user will not be touched."
20656 (interactive)
20657 (org-release-buffers org-agenda-new-buffers)
20658 (setq org-agenda-new-buffers nil)
20659 (org-agenda-quit))
20661 (defun org-save-all-org-buffers ()
20662 "Save all Org-mode buffers without user confirmation."
20663 (interactive)
20664 (message "Saving all Org-mode buffers...")
20665 (save-some-buffers t 'org-mode-p)
20666 (message "Saving all Org-mode buffers... done"))
20668 (defun org-agenda-redo ()
20669 "Rebuild Agenda.
20670 When this is the global TODO list, a prefix argument will be interpreted."
20671 (interactive)
20672 (let* ((org-agenda-keep-modes t)
20673 (line (org-current-line))
20674 (window-line (- line (org-current-line (window-start))))
20675 (lprops (get 'org-agenda-redo-command 'org-lprops)))
20676 (message "Rebuilding agenda buffer...")
20677 (org-let lprops '(eval org-agenda-redo-command))
20678 (setq org-agenda-undo-list nil
20679 org-agenda-pending-undo-list nil)
20680 (message "Rebuilding agenda buffer...done")
20681 (goto-line line)
20682 (recenter window-line)))
20684 (defun org-agenda-goto-date (date)
20685 "Jump to DATE in agenda."
20686 (interactive (list (org-read-date)))
20687 (org-agenda-list nil date))
20689 (defun org-agenda-goto-today ()
20690 "Go to today."
20691 (interactive)
20692 (org-agenda-check-type t 'timeline 'agenda)
20693 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
20694 (cond
20695 (tdpos (goto-char tdpos))
20696 ((eq org-agenda-type 'agenda)
20697 (let* ((sd (time-to-days (current-time)))
20698 (comp (org-agenda-compute-time-span sd org-agenda-span))
20699 (org-agenda-overriding-arguments org-agenda-last-arguments))
20700 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
20701 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
20702 (org-agenda-redo)
20703 (org-agenda-find-same-or-today-or-agenda)))
20704 (t (error "Cannot find today")))))
20706 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
20707 (goto-char
20708 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
20709 (text-property-any (point-min) (point-max) 'org-today t)
20710 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
20711 (point-min))))
20713 (defun org-agenda-later (arg)
20714 "Go forward in time by thee current span.
20715 With prefix ARG, go forward that many times the current span."
20716 (interactive "p")
20717 (org-agenda-check-type t 'agenda)
20718 (let* ((span org-agenda-span)
20719 (sd org-starting-day)
20720 (greg (calendar-gregorian-from-absolute sd))
20721 (cnt (get-text-property (point) 'org-day-cnt))
20722 greg2 nd)
20723 (cond
20724 ((eq span 'day)
20725 (setq sd (+ arg sd) nd 1))
20726 ((eq span 'week)
20727 (setq sd (+ (* 7 arg) sd) nd 7))
20728 ((eq span 'month)
20729 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
20730 sd (calendar-absolute-from-gregorian greg2))
20731 (setcar greg2 (1+ (car greg2)))
20732 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
20733 ((eq span 'year)
20734 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
20735 sd (calendar-absolute-from-gregorian greg2))
20736 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
20737 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
20738 (let ((org-agenda-overriding-arguments
20739 (list (car org-agenda-last-arguments) sd nd t)))
20740 (org-agenda-redo)
20741 (org-agenda-find-same-or-today-or-agenda cnt))))
20743 (defun org-agenda-earlier (arg)
20744 "Go backward in time by the current span.
20745 With prefix ARG, go backward that many times the current span."
20746 (interactive "p")
20747 (org-agenda-later (- arg)))
20749 (defun org-agenda-day-view ()
20750 "Switch to daily view for agenda."
20751 (interactive)
20752 (setq org-agenda-ndays 1)
20753 (org-agenda-change-time-span 'day))
20754 (defun org-agenda-week-view ()
20755 "Switch to daily view for agenda."
20756 (interactive)
20757 (setq org-agenda-ndays 7)
20758 (org-agenda-change-time-span 'week))
20759 (defun org-agenda-month-view ()
20760 "Switch to daily view for agenda."
20761 (interactive)
20762 (org-agenda-change-time-span 'month))
20763 (defun org-agenda-year-view ()
20764 "Switch to daily view for agenda."
20765 (interactive)
20766 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
20767 (org-agenda-change-time-span 'year)
20768 (error "Abort")))
20770 (defun org-agenda-change-time-span (span)
20771 "Change the agenda view to SPAN.
20772 SPAN may be `day', `week', `month', `year'."
20773 (org-agenda-check-type t 'agenda)
20774 (if (equal org-agenda-span span)
20775 (error "Viewing span is already \"%s\"" span))
20776 (let* ((sd (or (get-text-property (point) 'day)
20777 org-starting-day))
20778 (computed (org-agenda-compute-time-span sd span))
20779 (org-agenda-overriding-arguments
20780 (list (car org-agenda-last-arguments)
20781 (car computed) (cdr computed) t)))
20782 (org-agenda-redo)
20783 (org-agenda-find-same-or-today-or-agenda))
20784 (org-agenda-set-mode-name)
20785 (message "Switched to %s view" span))
20787 (defun org-agenda-compute-time-span (sd span)
20788 "Compute starting date and number of days for agenda.
20789 SPAN may be `day', `week', `month', `year'. The return value
20790 is a cons cell with the starting date and the number of days,
20791 so that the date SD will be in that range."
20792 (let* ((greg (calendar-gregorian-from-absolute sd))
20794 (cond
20795 ((eq span 'day)
20796 (setq nd 1))
20797 ((eq span 'week)
20798 (let* ((nt (calendar-day-of-week
20799 (calendar-gregorian-from-absolute sd)))
20800 (d (if org-agenda-start-on-weekday
20801 (- nt org-agenda-start-on-weekday)
20802 0)))
20803 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
20804 (setq nd 7)))
20805 ((eq span 'month)
20806 (setq sd (calendar-absolute-from-gregorian
20807 (list (car greg) 1 (nth 2 greg)))
20808 nd (- (calendar-absolute-from-gregorian
20809 (list (1+ (car greg)) 1 (nth 2 greg)))
20810 sd)))
20811 ((eq span 'year)
20812 (setq sd (calendar-absolute-from-gregorian
20813 (list 1 1 (nth 2 greg)))
20814 nd (- (calendar-absolute-from-gregorian
20815 (list 1 1 (1+ (nth 2 greg))))
20816 sd))))
20817 (cons sd nd)))
20819 ;; FIXME: does not work if user makes date format that starts with a blank
20820 (defun org-agenda-next-date-line (&optional arg)
20821 "Jump to the next line indicating a date in agenda buffer."
20822 (interactive "p")
20823 (org-agenda-check-type t 'agenda 'timeline)
20824 (beginning-of-line 1)
20825 (if (looking-at "^\\S-") (forward-char 1))
20826 (if (not (re-search-forward "^\\S-" nil t arg))
20827 (progn
20828 (backward-char 1)
20829 (error "No next date after this line in this buffer")))
20830 (goto-char (match-beginning 0)))
20832 (defun org-agenda-previous-date-line (&optional arg)
20833 "Jump to the previous line indicating a date in agenda buffer."
20834 (interactive "p")
20835 (org-agenda-check-type t 'agenda 'timeline)
20836 (beginning-of-line 1)
20837 (if (not (re-search-backward "^\\S-" nil t arg))
20838 (error "No previous date before this line in this buffer")))
20840 ;; Initialize the highlight
20841 (defvar org-hl (org-make-overlay 1 1))
20842 (org-overlay-put org-hl 'face 'highlight)
20844 (defun org-highlight (begin end &optional buffer)
20845 "Highlight a region with overlay."
20846 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
20847 org-hl begin end (or buffer (current-buffer))))
20849 (defun org-unhighlight ()
20850 "Detach overlay INDEX."
20851 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
20853 ;; FIXME this is currently not used.
20854 (defun org-highlight-until-next-command (beg end &optional buffer)
20855 (org-highlight beg end buffer)
20856 (add-hook 'pre-command-hook 'org-unhighlight-once))
20857 (defun org-unhighlight-once ()
20858 (remove-hook 'pre-command-hook 'org-unhighlight-once)
20859 (org-unhighlight))
20861 (defun org-agenda-follow-mode ()
20862 "Toggle follow mode in an agenda buffer."
20863 (interactive)
20864 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
20865 (org-agenda-set-mode-name)
20866 (message "Follow mode is %s"
20867 (if org-agenda-follow-mode "on" "off")))
20869 (defun org-agenda-log-mode ()
20870 "Toggle log mode in an agenda buffer."
20871 (interactive)
20872 (org-agenda-check-type t 'agenda 'timeline)
20873 (setq org-agenda-show-log (not org-agenda-show-log))
20874 (org-agenda-set-mode-name)
20875 (org-agenda-redo)
20876 (message "Log mode is %s"
20877 (if org-agenda-show-log "on" "off")))
20879 (defun org-agenda-toggle-diary ()
20880 "Toggle diary inclusion in an agenda buffer."
20881 (interactive)
20882 (org-agenda-check-type t 'agenda)
20883 (setq org-agenda-include-diary (not org-agenda-include-diary))
20884 (org-agenda-redo)
20885 (org-agenda-set-mode-name)
20886 (message "Diary inclusion turned %s"
20887 (if org-agenda-include-diary "on" "off")))
20889 (defun org-agenda-toggle-time-grid ()
20890 "Toggle time grid in an agenda buffer."
20891 (interactive)
20892 (org-agenda-check-type t 'agenda)
20893 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
20894 (org-agenda-redo)
20895 (org-agenda-set-mode-name)
20896 (message "Time-grid turned %s"
20897 (if org-agenda-use-time-grid "on" "off")))
20899 (defun org-agenda-set-mode-name ()
20900 "Set the mode name to indicate all the small mode settings."
20901 (setq mode-name
20902 (concat "Org-Agenda"
20903 (if (equal org-agenda-ndays 1) " Day" "")
20904 (if (equal org-agenda-ndays 7) " Week" "")
20905 (if org-agenda-follow-mode " Follow" "")
20906 (if org-agenda-include-diary " Diary" "")
20907 (if org-agenda-use-time-grid " Grid" "")
20908 (if org-agenda-show-log " Log" "")))
20909 (force-mode-line-update))
20911 (defun org-agenda-post-command-hook ()
20912 (and (eolp) (not (bolp)) (backward-char 1))
20913 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20914 (if (and org-agenda-follow-mode
20915 (get-text-property (point) 'org-marker))
20916 (org-agenda-show)))
20918 (defun org-agenda-show-priority ()
20919 "Show the priority of the current item.
20920 This priority is composed of the main priority given with the [#A] cookies,
20921 and by additional input from the age of a schedules or deadline entry."
20922 (interactive)
20923 (let* ((pri (get-text-property (point-at-bol) 'priority)))
20924 (message "Priority is %d" (if pri pri -1000))))
20926 (defun org-agenda-show-tags ()
20927 "Show the tags applicable to the current item."
20928 (interactive)
20929 (let* ((tags (get-text-property (point-at-bol) 'tags)))
20930 (if tags
20931 (message "Tags are :%s:"
20932 (org-no-properties (mapconcat 'identity tags ":")))
20933 (message "No tags associated with this line"))))
20935 (defun org-agenda-goto (&optional highlight)
20936 "Go to the Org-mode file which contains the item at point."
20937 (interactive)
20938 (let* ((marker (or (get-text-property (point) 'org-marker)
20939 (org-agenda-error)))
20940 (buffer (marker-buffer marker))
20941 (pos (marker-position marker)))
20942 (switch-to-buffer-other-window buffer)
20943 (widen)
20944 (goto-char pos)
20945 (when (org-mode-p)
20946 (org-show-context 'agenda)
20947 (save-excursion
20948 (and (outline-next-heading)
20949 (org-flag-heading nil)))) ; show the next heading
20950 (run-hooks 'org-agenda-after-show-hook)
20951 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
20953 (defvar org-agenda-after-show-hook nil
20954 "Normal hook run after an item has been shown from the agenda.
20955 Point is in the buffer where the item originated.")
20957 (defun org-agenda-kill ()
20958 "Kill the entry or subtree belonging to the current agenda entry."
20959 (interactive)
20960 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20961 (let* ((marker (or (get-text-property (point) 'org-marker)
20962 (org-agenda-error)))
20963 (buffer (marker-buffer marker))
20964 (pos (marker-position marker))
20965 (type (get-text-property (point) 'type))
20966 dbeg dend (n 0) conf)
20967 (org-with-remote-undo buffer
20968 (with-current-buffer buffer
20969 (save-excursion
20970 (goto-char pos)
20971 (if (and (org-mode-p) (not (member type '("sexp"))))
20972 (setq dbeg (progn (org-back-to-heading t) (point))
20973 dend (org-end-of-subtree t t))
20974 (setq dbeg (point-at-bol)
20975 dend (min (point-max) (1+ (point-at-eol)))))
20976 (goto-char dbeg)
20977 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
20978 (setq conf (or (eq t org-agenda-confirm-kill)
20979 (and (numberp org-agenda-confirm-kill)
20980 (> n org-agenda-confirm-kill))))
20981 (and conf
20982 (not (y-or-n-p
20983 (format "Delete entry with %d lines in buffer \"%s\"? "
20984 n (buffer-name buffer))))
20985 (error "Abort"))
20986 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
20987 (with-current-buffer buffer (delete-region dbeg dend))
20988 (message "Agenda item and source killed"))))
20990 (defun org-agenda-archive ()
20991 "Kill the entry or subtree belonging to the current agenda entry."
20992 (interactive)
20993 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
20994 (let* ((marker (or (get-text-property (point) 'org-marker)
20995 (org-agenda-error)))
20996 (buffer (marker-buffer marker))
20997 (pos (marker-position marker)))
20998 (org-with-remote-undo buffer
20999 (with-current-buffer buffer
21000 (if (org-mode-p)
21001 (save-excursion
21002 (goto-char pos)
21003 (org-remove-subtree-entries-from-agenda)
21004 (org-back-to-heading t)
21005 (org-archive-subtree))
21006 (error "Archiving works only in Org-mode files"))))))
21008 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
21009 "Remove all lines in the agenda that correspond to a given subtree.
21010 The subtree is the one in buffer BUF, starting at BEG and ending at END.
21011 If this information is not given, the function uses the tree at point."
21012 (let ((buf (or buf (current-buffer))) m p)
21013 (save-excursion
21014 (unless (and beg end)
21015 (org-back-to-heading t)
21016 (setq beg (point))
21017 (org-end-of-subtree t)
21018 (setq end (point)))
21019 (set-buffer (get-buffer org-agenda-buffer-name))
21020 (save-excursion
21021 (goto-char (point-max))
21022 (beginning-of-line 1)
21023 (while (not (bobp))
21024 (when (and (setq m (get-text-property (point) 'org-marker))
21025 (equal buf (marker-buffer m))
21026 (setq p (marker-position m))
21027 (>= p beg)
21028 (<= p end))
21029 (let ((inhibit-read-only t))
21030 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21031 (beginning-of-line 0))))))
21033 (defun org-agenda-open-link ()
21034 "Follow the link in the current line, if any."
21035 (interactive)
21036 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21037 (save-excursion
21038 (save-restriction
21039 (narrow-to-region (point-at-bol) (point-at-eol))
21040 (org-open-at-point))))
21042 (defun org-agenda-copy-local-variable (var)
21043 "Get a variable from a referenced buffer and install it here."
21044 (let ((m (get-text-property (point) 'org-marker)))
21045 (when (and m (buffer-live-p (marker-buffer m)))
21046 (org-set-local var (with-current-buffer (marker-buffer m)
21047 (symbol-value var))))))
21049 (defun org-agenda-switch-to (&optional delete-other-windows)
21050 "Go to the Org-mode file which contains the item at point."
21051 (interactive)
21052 (let* ((marker (or (get-text-property (point) 'org-marker)
21053 (org-agenda-error)))
21054 (buffer (marker-buffer marker))
21055 (pos (marker-position marker)))
21056 (switch-to-buffer buffer)
21057 (and delete-other-windows (delete-other-windows))
21058 (widen)
21059 (goto-char pos)
21060 (when (org-mode-p)
21061 (org-show-context 'agenda)
21062 (save-excursion
21063 (and (outline-next-heading)
21064 (org-flag-heading nil)))))) ; show the next heading
21066 (defun org-agenda-goto-mouse (ev)
21067 "Go to the Org-mode file which contains the item at the mouse click."
21068 (interactive "e")
21069 (mouse-set-point ev)
21070 (org-agenda-goto))
21072 (defun org-agenda-show ()
21073 "Display the Org-mode file which contains the item at point."
21074 (interactive)
21075 (let ((win (selected-window)))
21076 (org-agenda-goto t)
21077 (select-window win)))
21079 (defun org-agenda-recenter (arg)
21080 "Display the Org-mode file which contains the item at point and recenter."
21081 (interactive "P")
21082 (let ((win (selected-window)))
21083 (org-agenda-goto t)
21084 (recenter arg)
21085 (select-window win)))
21087 (defun org-agenda-show-mouse (ev)
21088 "Display the Org-mode file which contains the item at the mouse click."
21089 (interactive "e")
21090 (mouse-set-point ev)
21091 (org-agenda-show))
21093 (defun org-agenda-check-no-diary ()
21094 "Check if the entry is a diary link and abort if yes."
21095 (if (get-text-property (point) 'org-agenda-diary-link)
21096 (org-agenda-error)))
21098 (defun org-agenda-error ()
21099 (error "Command not allowed in this line"))
21101 (defun org-agenda-tree-to-indirect-buffer ()
21102 "Show the subtree corresponding to the current entry in an indirect buffer.
21103 This calls the command `org-tree-to-indirect-buffer' from the original
21104 Org-mode buffer.
21105 With numerical prefix arg ARG, go up to this level and then take that tree.
21106 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21107 dedicated frame)."
21108 (interactive)
21109 (org-agenda-check-no-diary)
21110 (let* ((marker (or (get-text-property (point) 'org-marker)
21111 (org-agenda-error)))
21112 (buffer (marker-buffer marker))
21113 (pos (marker-position marker)))
21114 (with-current-buffer buffer
21115 (save-excursion
21116 (goto-char pos)
21117 (call-interactively 'org-tree-to-indirect-buffer)))))
21119 (defvar org-last-heading-marker (make-marker)
21120 "Marker pointing to the headline that last changed its TODO state
21121 by a remote command from the agenda.")
21123 (defun org-agenda-todo-nextset ()
21124 "Switch TODO entry to next sequence."
21125 (interactive)
21126 (org-agenda-todo 'nextset))
21128 (defun org-agenda-todo-previousset ()
21129 "Switch TODO entry to previous sequence."
21130 (interactive)
21131 (org-agenda-todo 'previousset))
21133 (defun org-agenda-todo (&optional arg)
21134 "Cycle TODO state of line at point, also in Org-mode file.
21135 This changes the line at point, all other lines in the agenda referring to
21136 the same tree node, and the headline of the tree node in the Org-mode file."
21137 (interactive "P")
21138 (org-agenda-check-no-diary)
21139 (let* ((col (current-column))
21140 (marker (or (get-text-property (point) 'org-marker)
21141 (org-agenda-error)))
21142 (buffer (marker-buffer marker))
21143 (pos (marker-position marker))
21144 (hdmarker (get-text-property (point) 'org-hd-marker))
21145 (inhibit-read-only t)
21146 newhead)
21147 (org-with-remote-undo buffer
21148 (with-current-buffer buffer
21149 (widen)
21150 (goto-char pos)
21151 (org-show-context 'agenda)
21152 (save-excursion
21153 (and (outline-next-heading)
21154 (org-flag-heading nil))) ; show the next heading
21155 (org-todo arg)
21156 (and (bolp) (forward-char 1))
21157 (setq newhead (org-get-heading))
21158 (save-excursion
21159 (org-back-to-heading)
21160 (move-marker org-last-heading-marker (point))))
21161 (beginning-of-line 1)
21162 (save-excursion
21163 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21164 (move-to-column col))))
21166 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21167 "Change all lines in the agenda buffer which match HDMARKER.
21168 The new content of the line will be NEWHEAD (as modified by
21169 `org-format-agenda-item'). HDMARKER is checked with
21170 `equal' against all `org-hd-marker' text properties in the file.
21171 If FIXFACE is non-nil, the face of each item is modified acording to
21172 the new TODO state."
21173 (let* ((inhibit-read-only t)
21174 props m pl undone-face done-face finish new dotime cat tags)
21175 (save-excursion
21176 (goto-char (point-max))
21177 (beginning-of-line 1)
21178 (while (not finish)
21179 (setq finish (bobp))
21180 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21181 (equal m hdmarker))
21182 (setq props (text-properties-at (point))
21183 dotime (get-text-property (point) 'dotime)
21184 cat (get-text-property (point) 'org-category)
21185 tags (get-text-property (point) 'tags)
21186 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21187 pl (get-text-property (point) 'prefix-length)
21188 undone-face (get-text-property (point) 'undone-face)
21189 done-face (get-text-property (point) 'done-face))
21190 (move-to-column pl)
21191 (cond
21192 ((equal new "")
21193 (beginning-of-line 1)
21194 (and (looking-at ".*\n?") (replace-match "")))
21195 ((looking-at ".*")
21196 (replace-match new t t)
21197 (beginning-of-line 1)
21198 (add-text-properties (point-at-bol) (point-at-eol) props)
21199 (when fixface
21200 (add-text-properties
21201 (point-at-bol) (point-at-eol)
21202 (list 'face
21203 (if org-last-todo-state-is-todo
21204 undone-face done-face))))
21205 (org-agenda-highlight-todo 'line)
21206 (beginning-of-line 1))
21207 (t (error "Line update did not work"))))
21208 (beginning-of-line 0)))
21209 (org-finalize-agenda)))
21211 (defun org-agenda-align-tags (&optional line)
21212 "Align all tags in agenda items to `org-agenda-tags-column'."
21213 (let ((inhibit-read-only t) l c)
21214 (save-excursion
21215 (goto-char (if line (point-at-bol) (point-min)))
21216 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21217 (if line (point-at-eol) nil) t)
21218 (add-text-properties
21219 (match-beginning 2) (match-end 2)
21220 (list 'face (list 'org-tag (get-text-property
21221 (match-beginning 2) 'face))))
21222 (setq l (- (match-end 2) (match-beginning 2))
21223 c (if (< org-agenda-tags-column 0)
21224 (- (abs org-agenda-tags-column) l)
21225 org-agenda-tags-column))
21226 (delete-region (match-beginning 1) (match-end 1))
21227 (goto-char (match-beginning 1))
21228 (insert (org-add-props
21229 (make-string (max 1 (- c (current-column))) ?\ )
21230 (text-properties-at (point))))))))
21232 (defun org-agenda-priority-up ()
21233 "Increase the priority of line at point, also in Org-mode file."
21234 (interactive)
21235 (org-agenda-priority 'up))
21237 (defun org-agenda-priority-down ()
21238 "Decrease the priority of line at point, also in Org-mode file."
21239 (interactive)
21240 (org-agenda-priority 'down))
21242 (defun org-agenda-priority (&optional force-direction)
21243 "Set the priority of line at point, also in Org-mode file.
21244 This changes the line at point, all other lines in the agenda referring to
21245 the same tree node, and the headline of the tree node in the Org-mode file."
21246 (interactive)
21247 (org-agenda-check-no-diary)
21248 (let* ((marker (or (get-text-property (point) 'org-marker)
21249 (org-agenda-error)))
21250 (hdmarker (get-text-property (point) 'org-hd-marker))
21251 (buffer (marker-buffer hdmarker))
21252 (pos (marker-position hdmarker))
21253 (inhibit-read-only t)
21254 newhead)
21255 (org-with-remote-undo buffer
21256 (with-current-buffer buffer
21257 (widen)
21258 (goto-char pos)
21259 (org-show-context 'agenda)
21260 (save-excursion
21261 (and (outline-next-heading)
21262 (org-flag-heading nil))) ; show the next heading
21263 (funcall 'org-priority force-direction)
21264 (end-of-line 1)
21265 (setq newhead (org-get-heading)))
21266 (org-agenda-change-all-lines newhead hdmarker)
21267 (beginning-of-line 1))))
21269 (defun org-get-tags-at (&optional pos)
21270 "Get a list of all headline tags applicable at POS.
21271 POS defaults to point. If tags are inherited, the list contains
21272 the targets in the same sequence as the headlines appear, i.e.
21273 the tags of the current headline come last."
21274 (interactive)
21275 (let (tags lastpos)
21276 (save-excursion
21277 (save-restriction
21278 (widen)
21279 (goto-char (or pos (point)))
21280 (save-match-data
21281 (org-back-to-heading t)
21282 (condition-case nil
21283 (while (not (equal lastpos (point)))
21284 (setq lastpos (point))
21285 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
21286 (setq tags (append (org-split-string
21287 (org-match-string-no-properties 1) ":")
21288 tags)))
21289 (or org-use-tag-inheritance (error ""))
21290 (org-up-heading-all 1))
21291 (error nil))))
21292 tags)))
21294 ;; FIXME: should fix the tags property of the agenda line.
21295 (defun org-agenda-set-tags ()
21296 "Set tags for the current headline."
21297 (interactive)
21298 (org-agenda-check-no-diary)
21299 (if (and (org-region-active-p) (interactive-p))
21300 (call-interactively 'org-change-tag-in-region)
21301 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21302 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21303 (org-agenda-error)))
21304 (buffer (marker-buffer hdmarker))
21305 (pos (marker-position hdmarker))
21306 (inhibit-read-only t)
21307 newhead)
21308 (org-with-remote-undo buffer
21309 (with-current-buffer buffer
21310 (widen)
21311 (goto-char pos)
21312 (save-excursion
21313 (org-show-context 'agenda))
21314 (save-excursion
21315 (and (outline-next-heading)
21316 (org-flag-heading nil))) ; show the next heading
21317 (goto-char pos)
21318 (call-interactively 'org-set-tags)
21319 (end-of-line 1)
21320 (setq newhead (org-get-heading)))
21321 (org-agenda-change-all-lines newhead hdmarker)
21322 (beginning-of-line 1)))))
21324 (defun org-agenda-toggle-archive-tag ()
21325 "Toggle the archive tag for the current entry."
21326 (interactive)
21327 (org-agenda-check-no-diary)
21328 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21329 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21330 (org-agenda-error)))
21331 (buffer (marker-buffer hdmarker))
21332 (pos (marker-position hdmarker))
21333 (inhibit-read-only t)
21334 newhead)
21335 (org-with-remote-undo buffer
21336 (with-current-buffer buffer
21337 (widen)
21338 (goto-char pos)
21339 (org-show-context 'agenda)
21340 (save-excursion
21341 (and (outline-next-heading)
21342 (org-flag-heading nil))) ; show the next heading
21343 (call-interactively 'org-toggle-archive-tag)
21344 (end-of-line 1)
21345 (setq newhead (org-get-heading)))
21346 (org-agenda-change-all-lines newhead hdmarker)
21347 (beginning-of-line 1))))
21349 (defun org-agenda-date-later (arg &optional what)
21350 "Change the date of this item to one day later."
21351 (interactive "p")
21352 (org-agenda-check-type t 'agenda 'timeline)
21353 (org-agenda-check-no-diary)
21354 (let* ((marker (or (get-text-property (point) 'org-marker)
21355 (org-agenda-error)))
21356 (buffer (marker-buffer marker))
21357 (pos (marker-position marker)))
21358 (org-with-remote-undo buffer
21359 (with-current-buffer buffer
21360 (widen)
21361 (goto-char pos)
21362 (if (not (org-at-timestamp-p))
21363 (error "Cannot find time stamp"))
21364 (org-timestamp-change arg (or what 'day)))
21365 (org-agenda-show-new-time marker org-last-changed-timestamp))
21366 (message "Time stamp changed to %s" org-last-changed-timestamp)))
21368 (defun org-agenda-date-earlier (arg &optional what)
21369 "Change the date of this item to one day earlier."
21370 (interactive "p")
21371 (org-agenda-date-later (- arg) what))
21373 (defun org-agenda-show-new-time (marker stamp &optional prefix)
21374 "Show new date stamp via text properties."
21375 ;; We use text properties to make this undoable
21376 (let ((inhibit-read-only t))
21377 (setq stamp (concat " " prefix " => " stamp))
21378 (save-excursion
21379 (goto-char (point-max))
21380 (while (not (bobp))
21381 (when (equal marker (get-text-property (point) 'org-marker))
21382 (move-to-column (- (window-width) (length stamp)) t)
21383 (if (featurep 'xemacs)
21384 ;; Use `duplicable' property to trigger undo recording
21385 (let ((ex (make-extent nil nil))
21386 (gl (make-glyph stamp)))
21387 (set-glyph-face gl 'secondary-selection)
21388 (set-extent-properties
21389 ex (list 'invisible t 'end-glyph gl 'duplicable t))
21390 (insert-extent ex (1- (point)) (point-at-eol)))
21391 (add-text-properties
21392 (1- (point)) (point-at-eol)
21393 (list 'display (org-add-props stamp nil
21394 'face 'secondary-selection))))
21395 (beginning-of-line 1))
21396 (beginning-of-line 0)))))
21398 (defun org-agenda-date-prompt (arg)
21399 "Change the date of this item. Date is prompted for, with default today.
21400 The prefix ARG is passed to the `org-time-stamp' command and can therefore
21401 be used to request time specification in the time stamp."
21402 (interactive "P")
21403 (org-agenda-check-type t 'agenda 'timeline)
21404 (org-agenda-check-no-diary)
21405 (let* ((marker (or (get-text-property (point) 'org-marker)
21406 (org-agenda-error)))
21407 (buffer (marker-buffer marker))
21408 (pos (marker-position marker)))
21409 (org-with-remote-undo buffer
21410 (with-current-buffer buffer
21411 (widen)
21412 (goto-char pos)
21413 (if (not (org-at-timestamp-p))
21414 (error "Cannot find time stamp"))
21415 (org-time-stamp arg)
21416 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
21418 (defun org-agenda-schedule (arg)
21419 "Schedule the item at point."
21420 (interactive "P")
21421 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21422 (org-agenda-check-no-diary)
21423 (let* ((marker (or (get-text-property (point) 'org-marker)
21424 (org-agenda-error)))
21425 (buffer (marker-buffer marker))
21426 (pos (marker-position marker))
21427 (org-insert-labeled-timestamps-at-point nil)
21429 (org-with-remote-undo buffer
21430 (with-current-buffer buffer
21431 (widen)
21432 (goto-char pos)
21433 (setq ts (org-schedule arg)))
21434 (org-agenda-show-new-time marker ts "S"))
21435 (message "Item scheduled for %s" ts)))
21437 (defun org-agenda-deadline (arg)
21438 "Schedule the item at point."
21439 (interactive "P")
21440 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21441 (org-agenda-check-no-diary)
21442 (let* ((marker (or (get-text-property (point) 'org-marker)
21443 (org-agenda-error)))
21444 (buffer (marker-buffer marker))
21445 (pos (marker-position marker))
21446 (org-insert-labeled-timestamps-at-point nil)
21448 (org-with-remote-undo buffer
21449 (with-current-buffer buffer
21450 (widen)
21451 (goto-char pos)
21452 (setq ts (org-deadline arg)))
21453 (org-agenda-show-new-time marker ts "S"))
21454 (message "Deadline for this item set to %s" ts)))
21456 (defun org-get-heading (&optional no-tags)
21457 "Return the heading of the current entry, without the stars."
21458 (save-excursion
21459 (org-back-to-heading t)
21460 (if (looking-at
21461 (if no-tags
21462 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
21463 "\\*+[ \t]+\\([^\r\n]*\\)"))
21464 (match-string 1) "")))
21466 (defun org-agenda-clock-in (&optional arg)
21467 "Start the clock on the currently selected item."
21468 (interactive "P")
21469 (org-agenda-check-no-diary)
21470 (let* ((marker (or (get-text-property (point) 'org-marker)
21471 (org-agenda-error)))
21472 (pos (marker-position marker)))
21473 (org-with-remote-undo (marker-buffer marker)
21474 (with-current-buffer (marker-buffer marker)
21475 (widen)
21476 (goto-char pos)
21477 (org-clock-in)))))
21479 (defun org-agenda-clock-out (&optional arg)
21480 "Stop the currently running clock."
21481 (interactive "P")
21482 (unless (marker-buffer org-clock-marker)
21483 (error "No running clock"))
21484 (org-with-remote-undo (marker-buffer org-clock-marker)
21485 (org-clock-out)))
21487 (defun org-agenda-clock-cancel (&optional arg)
21488 "Cancel the currently running clock."
21489 (interactive "P")
21490 (unless (marker-buffer org-clock-marker)
21491 (error "No running clock"))
21492 (org-with-remote-undo (marker-buffer org-clock-marker)
21493 (org-clock-cancel)))
21495 (defun org-agenda-diary-entry ()
21496 "Make a diary entry, like the `i' command from the calendar.
21497 All the standard commands work: block, weekly etc."
21498 (interactive)
21499 (org-agenda-check-type t 'agenda 'timeline)
21500 (require 'diary-lib)
21501 (let* ((char (progn
21502 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
21503 (read-char-exclusive)))
21504 (cmd (cdr (assoc char
21505 '((?d . insert-diary-entry)
21506 (?w . insert-weekly-diary-entry)
21507 (?m . insert-monthly-diary-entry)
21508 (?y . insert-yearly-diary-entry)
21509 (?a . insert-anniversary-diary-entry)
21510 (?b . insert-block-diary-entry)
21511 (?c . insert-cyclic-diary-entry)))))
21512 (oldf (symbol-function 'calendar-cursor-to-date))
21513 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
21514 (point (point))
21515 (mark (or (mark t) (point))))
21516 (unless cmd
21517 (error "No command associated with <%c>" char))
21518 (unless (and (get-text-property point 'day)
21519 (or (not (equal ?b char))
21520 (get-text-property mark 'day)))
21521 (error "Don't know which date to use for diary entry"))
21522 ;; We implement this by hacking the `calendar-cursor-to-date' function
21523 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
21524 (let ((calendar-mark-ring
21525 (list (calendar-gregorian-from-absolute
21526 (or (get-text-property mark 'day)
21527 (get-text-property point 'day))))))
21528 (unwind-protect
21529 (progn
21530 (fset 'calendar-cursor-to-date
21531 (lambda (&optional error)
21532 (calendar-gregorian-from-absolute
21533 (get-text-property point 'day))))
21534 (call-interactively cmd))
21535 (fset 'calendar-cursor-to-date oldf)))))
21538 (defun org-agenda-execute-calendar-command (cmd)
21539 "Execute a calendar command from the agenda, with the date associated to
21540 the cursor position."
21541 (org-agenda-check-type t 'agenda 'timeline)
21542 (require 'diary-lib)
21543 (unless (get-text-property (point) 'day)
21544 (error "Don't know which date to use for calendar command"))
21545 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
21546 (point (point))
21547 (date (calendar-gregorian-from-absolute
21548 (get-text-property point 'day)))
21549 ;; the following 3 vars are needed in the calendar
21550 (displayed-day (extract-calendar-day date))
21551 (displayed-month (extract-calendar-month date))
21552 (displayed-year (extract-calendar-year date)))
21553 (unwind-protect
21554 (progn
21555 (fset 'calendar-cursor-to-date
21556 (lambda (&optional error)
21557 (calendar-gregorian-from-absolute
21558 (get-text-property point 'day))))
21559 (call-interactively cmd))
21560 (fset 'calendar-cursor-to-date oldf))))
21562 (defun org-agenda-phases-of-moon ()
21563 "Display the phases of the moon for the 3 months around the cursor date."
21564 (interactive)
21565 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
21567 (defun org-agenda-holidays ()
21568 "Display the holidays for the 3 months around the cursor date."
21569 (interactive)
21570 (org-agenda-execute-calendar-command 'list-calendar-holidays))
21572 (defun org-agenda-sunrise-sunset (arg)
21573 "Display sunrise and sunset for the cursor date.
21574 Latitude and longitude can be specified with the variables
21575 `calendar-latitude' and `calendar-longitude'. When called with prefix
21576 argument, latitude and longitude will be prompted for."
21577 (interactive "P")
21578 (let ((calendar-longitude (if arg nil calendar-longitude))
21579 (calendar-latitude (if arg nil calendar-latitude))
21580 (calendar-location-name
21581 (if arg "the given coordinates" calendar-location-name)))
21582 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
21584 (defun org-agenda-goto-calendar ()
21585 "Open the Emacs calendar with the date at the cursor."
21586 (interactive)
21587 (org-agenda-check-type t 'agenda 'timeline)
21588 (let* ((day (or (get-text-property (point) 'day)
21589 (error "Don't know which date to open in calendar")))
21590 (date (calendar-gregorian-from-absolute day))
21591 (calendar-move-hook nil)
21592 (view-calendar-holidays-initially nil)
21593 (view-diary-entries-initially nil))
21594 (calendar)
21595 (calendar-goto-date date)))
21597 (defun org-calendar-goto-agenda ()
21598 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
21599 This is a command that has to be installed in `calendar-mode-map'."
21600 (interactive)
21601 (org-agenda-list nil (calendar-absolute-from-gregorian
21602 (calendar-cursor-to-date))
21603 nil))
21605 (defun org-agenda-convert-date ()
21606 (interactive)
21607 (org-agenda-check-type t 'agenda 'timeline)
21608 (let ((day (get-text-property (point) 'day))
21609 date s)
21610 (unless day
21611 (error "Don't know which date to convert"))
21612 (setq date (calendar-gregorian-from-absolute day))
21613 (setq s (concat
21614 "Gregorian: " (calendar-date-string date) "\n"
21615 "ISO: " (calendar-iso-date-string date) "\n"
21616 "Day of Yr: " (calendar-day-of-year-string date) "\n"
21617 "Julian: " (calendar-julian-date-string date) "\n"
21618 "Astron. JD: " (calendar-astro-date-string date)
21619 " (Julian date number at noon UTC)\n"
21620 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
21621 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
21622 "French: " (calendar-french-date-string date) "\n"
21623 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
21624 "Mayan: " (calendar-mayan-date-string date) "\n"
21625 "Coptic: " (calendar-coptic-date-string date) "\n"
21626 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
21627 "Persian: " (calendar-persian-date-string date) "\n"
21628 "Chinese: " (calendar-chinese-date-string date) "\n"))
21629 (with-output-to-temp-buffer "*Dates*"
21630 (princ s))
21631 (if (fboundp 'fit-window-to-buffer)
21632 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
21635 ;;;; Embedded LaTeX
21637 (defvar org-cdlatex-mode-map (make-sparse-keymap)
21638 "Keymap for the minor `org-cdlatex-mode'.")
21640 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
21641 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
21642 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
21643 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
21644 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
21646 (defvar org-cdlatex-texmathp-advice-is-done nil
21647 "Flag remembering if we have applied the advice to texmathp already.")
21649 (define-minor-mode org-cdlatex-mode
21650 "Toggle the minor `org-cdlatex-mode'.
21651 This mode supports entering LaTeX environment and math in LaTeX fragments
21652 in Org-mode.
21653 \\{org-cdlatex-mode-map}"
21654 nil " OCDL" nil
21655 (when org-cdlatex-mode (require 'cdlatex))
21656 (unless org-cdlatex-texmathp-advice-is-done
21657 (setq org-cdlatex-texmathp-advice-is-done t)
21658 (defadvice texmathp (around org-math-always-on activate)
21659 "Always return t in org-mode buffers.
21660 This is because we want to insert math symbols without dollars even outside
21661 the LaTeX math segments. If Orgmode thinks that point is actually inside
21662 en embedded LaTeX fragement, let texmathp do its job.
21663 \\[org-cdlatex-mode-map]"
21664 (interactive)
21665 (let (p)
21666 (cond
21667 ((not (org-mode-p)) ad-do-it)
21668 ((eq this-command 'cdlatex-math-symbol)
21669 (setq ad-return-value t
21670 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
21672 (let ((p (org-inside-LaTeX-fragment-p)))
21673 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
21674 (setq ad-return-value t
21675 texmathp-why '("Org-mode embedded math" . 0))
21676 (if p ad-do-it)))))))))
21678 (defun turn-on-org-cdlatex ()
21679 "Unconditionally turn on `org-cdlatex-mode'."
21680 (org-cdlatex-mode 1))
21682 (defun org-inside-LaTeX-fragment-p ()
21683 "Test if point is inside a LaTeX fragment.
21684 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
21685 sequence appearing also before point.
21686 Even though the matchers for math are configurable, this function assumes
21687 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
21688 delimiters are skipped when they have been removed by customization.
21689 The return value is nil, or a cons cell with the delimiter and
21690 and the position of this delimiter.
21692 This function does a reasonably good job, but can locally be fooled by
21693 for example currency specifications. For example it will assume being in
21694 inline math after \"$22.34\". The LaTeX fragment formatter will only format
21695 fragments that are properly closed, but during editing, we have to live
21696 with the uncertainty caused by missing closing delimiters. This function
21697 looks only before point, not after."
21698 (catch 'exit
21699 (let ((pos (point))
21700 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
21701 (lim (progn
21702 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
21703 (point)))
21704 dd-on str (start 0) m re)
21705 (goto-char pos)
21706 (when dodollar
21707 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
21708 re (nth 1 (assoc "$" org-latex-regexps)))
21709 (while (string-match re str start)
21710 (cond
21711 ((= (match-end 0) (length str))
21712 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
21713 ((= (match-end 0) (- (length str) 5))
21714 (throw 'exit nil))
21715 (t (setq start (match-end 0))))))
21716 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
21717 (goto-char pos)
21718 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
21719 (and (match-beginning 2) (throw 'exit nil))
21720 ;; count $$
21721 (while (re-search-backward "\\$\\$" lim t)
21722 (setq dd-on (not dd-on)))
21723 (goto-char pos)
21724 (if dd-on (cons "$$" m))))))
21727 (defun org-try-cdlatex-tab ()
21728 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
21729 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
21730 - inside a LaTeX fragment, or
21731 - after the first word in a line, where an abbreviation expansion could
21732 insert a LaTeX environment."
21733 (when org-cdlatex-mode
21734 (cond
21735 ((save-excursion
21736 (skip-chars-backward "a-zA-Z0-9*")
21737 (skip-chars-backward " \t")
21738 (bolp))
21739 (cdlatex-tab) t)
21740 ((org-inside-LaTeX-fragment-p)
21741 (cdlatex-tab) t)
21742 (t nil))))
21744 (defun org-cdlatex-underscore-caret (&optional arg)
21745 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
21746 Revert to the normal definition outside of these fragments."
21747 (interactive "P")
21748 (if (org-inside-LaTeX-fragment-p)
21749 (call-interactively 'cdlatex-sub-superscript)
21750 (let (org-cdlatex-mode)
21751 (call-interactively (key-binding (vector last-input-event))))))
21753 (defun org-cdlatex-math-modify (&optional arg)
21754 "Execute `cdlatex-math-modify' in LaTeX fragments.
21755 Revert to the normal definition outside of these fragments."
21756 (interactive "P")
21757 (if (org-inside-LaTeX-fragment-p)
21758 (call-interactively 'cdlatex-math-modify)
21759 (let (org-cdlatex-mode)
21760 (call-interactively (key-binding (vector last-input-event))))))
21762 (defvar org-latex-fragment-image-overlays nil
21763 "List of overlays carrying the images of latex fragments.")
21764 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
21766 (defun org-remove-latex-fragment-image-overlays ()
21767 "Remove all overlays with LaTeX fragment images in current buffer."
21768 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
21769 (setq org-latex-fragment-image-overlays nil))
21771 (defun org-preview-latex-fragment (&optional subtree)
21772 "Preview the LaTeX fragment at point, or all locally or globally.
21773 If the cursor is in a LaTeX fragment, create the image and overlay
21774 it over the source code. If there is no fragment at point, display
21775 all fragments in the current text, from one headline to the next. With
21776 prefix SUBTREE, display all fragments in the current subtree. With a
21777 double prefix `C-u C-u', or when the cursor is before the first headline,
21778 display all fragments in the buffer.
21779 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
21780 (interactive "P")
21781 (org-remove-latex-fragment-image-overlays)
21782 (save-excursion
21783 (save-restriction
21784 (let (beg end at msg)
21785 (cond
21786 ((or (equal subtree '(16))
21787 (not (save-excursion
21788 (re-search-backward (concat "^" outline-regexp) nil t))))
21789 (setq beg (point-min) end (point-max)
21790 msg "Creating images for buffer...%s"))
21791 ((equal subtree '(4))
21792 (org-back-to-heading)
21793 (setq beg (point) end (org-end-of-subtree t)
21794 msg "Creating images for subtree...%s"))
21796 (if (setq at (org-inside-LaTeX-fragment-p))
21797 (goto-char (max (point-min) (- (cdr at) 2)))
21798 (org-back-to-heading))
21799 (setq beg (point) end (progn (outline-next-heading) (point))
21800 msg (if at "Creating image...%s"
21801 "Creating images for entry...%s"))))
21802 (message msg "")
21803 (narrow-to-region beg end)
21804 (goto-char beg)
21805 (org-format-latex
21806 (concat "ltxpng/" (file-name-sans-extension
21807 (file-name-nondirectory
21808 buffer-file-name)))
21809 default-directory 'overlays msg at 'forbuffer)
21810 (message msg "done. Use `C-c C-c' to remove images.")))))
21812 (defvar org-latex-regexps
21813 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
21814 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
21815 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
21816 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
21817 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
21818 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
21819 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
21820 "Regular expressions for matching embedded LaTeX.")
21822 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
21823 "Replace LaTeX fragments with links to an image, and produce images."
21824 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
21825 (let* ((prefixnodir (file-name-nondirectory prefix))
21826 (absprefix (expand-file-name prefix dir))
21827 (todir (file-name-directory absprefix))
21828 (opt org-format-latex-options)
21829 (matchers (plist-get opt :matchers))
21830 (re-list org-latex-regexps)
21831 (cnt 0) txt link beg end re e checkdir
21832 m n block linkfile movefile ov)
21833 ;; Check if there are old images files with this prefix, and remove them
21834 (when (file-directory-p todir)
21835 (mapc 'delete-file
21836 (directory-files
21837 todir 'full
21838 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
21839 ;; Check the different regular expressions
21840 (while (setq e (pop re-list))
21841 (setq m (car e) re (nth 1 e) n (nth 2 e)
21842 block (if (nth 3 e) "\n\n" ""))
21843 (when (member m matchers)
21844 (goto-char (point-min))
21845 (while (re-search-forward re nil t)
21846 (when (or (not at) (equal (cdr at) (match-beginning n)))
21847 (setq txt (match-string n)
21848 beg (match-beginning n) end (match-end n)
21849 cnt (1+ cnt)
21850 linkfile (format "%s_%04d.png" prefix cnt)
21851 movefile (format "%s_%04d.png" absprefix cnt)
21852 link (concat block "[[file:" linkfile "]]" block))
21853 (if msg (message msg cnt))
21854 (goto-char beg)
21855 (unless checkdir ; make sure the directory exists
21856 (setq checkdir t)
21857 (or (file-directory-p todir) (make-directory todir)))
21858 (org-create-formula-image
21859 txt movefile opt forbuffer)
21860 (if overlays
21861 (progn
21862 (setq ov (org-make-overlay beg end))
21863 (if (featurep 'xemacs)
21864 (progn
21865 (org-overlay-put ov 'invisible t)
21866 (org-overlay-put
21867 ov 'end-glyph
21868 (make-glyph (vector 'png :file movefile))))
21869 (org-overlay-put
21870 ov 'display
21871 (list 'image :type 'png :file movefile :ascent 'center)))
21872 (push ov org-latex-fragment-image-overlays)
21873 (goto-char end))
21874 (delete-region beg end)
21875 (insert link))))))))
21877 ;; This function borrows from Ganesh Swami's latex2png.el
21878 (defun org-create-formula-image (string tofile options buffer)
21879 (let* ((tmpdir (if (featurep 'xemacs)
21880 (temp-directory)
21881 temporary-file-directory))
21882 (texfilebase (make-temp-name
21883 (expand-file-name "orgtex" tmpdir)))
21884 (texfile (concat texfilebase ".tex"))
21885 (dvifile (concat texfilebase ".dvi"))
21886 (pngfile (concat texfilebase ".png"))
21887 (fnh (face-attribute 'default :height nil))
21888 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
21889 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
21890 (fg (or (plist-get options (if buffer :foreground :html-foreground))
21891 "Black"))
21892 (bg (or (plist-get options (if buffer :background :html-background))
21893 "Transparent")))
21894 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
21895 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
21896 (with-temp-file texfile
21897 (insert org-format-latex-header
21898 "\n\\begin{document}\n" string "\n\\end{document}\n"))
21899 (let ((dir default-directory))
21900 (condition-case nil
21901 (progn
21902 (cd tmpdir)
21903 (call-process "latex" nil nil nil texfile))
21904 (error nil))
21905 (cd dir))
21906 (if (not (file-exists-p dvifile))
21907 (progn (message "Failed to create dvi file from %s" texfile) nil)
21908 (call-process "dvipng" nil nil nil
21909 "-E" "-fg" fg "-bg" bg
21910 "-D" dpi
21911 ;;"-x" scale "-y" scale
21912 "-T" "tight"
21913 "-o" pngfile
21914 dvifile)
21915 (if (not (file-exists-p pngfile))
21916 (progn (message "Failed to create png file from %s" texfile) nil)
21917 ;; Use the requested file name and clean up
21918 (copy-file pngfile tofile 'replace)
21919 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
21920 (delete-file (concat texfilebase e)))
21921 pngfile))))
21923 (defun org-dvipng-color (attr)
21924 "Return an rgb color specification for dvipng."
21925 (apply 'format "rgb %s %s %s"
21926 (mapcar 'org-normalize-color
21927 (color-values (face-attribute 'default attr nil)))))
21929 (defun org-normalize-color (value)
21930 "Return string to be used as color value for an RGB component."
21931 (format "%g" (/ value 65535.0)))
21933 ;;;; Exporting
21935 ;;; Variables, constants, and parameter plists
21937 (defconst org-level-max 20)
21939 (defvar org-export-html-preamble nil
21940 "Preamble, to be inserted just after <body>. Set by publishing functions.")
21941 (defvar org-export-html-postamble nil
21942 "Preamble, to be inserted just before </body>. Set by publishing functions.")
21943 (defvar org-export-html-auto-preamble t
21944 "Should default preamble be inserted? Set by publishing functions.")
21945 (defvar org-export-html-auto-postamble t
21946 "Should default postamble be inserted? Set by publishing functions.")
21947 (defvar org-current-export-file nil) ; dynamically scoped parameter
21948 (defvar org-current-export-dir nil) ; dynamically scoped parameter
21951 (defconst org-export-plist-vars
21952 '((:language . org-export-default-language)
21953 (:customtime . org-display-custom-times)
21954 (:headline-levels . org-export-headline-levels)
21955 (:section-numbers . org-export-with-section-numbers)
21956 (:table-of-contents . org-export-with-toc)
21957 (:preserve-breaks . org-export-preserve-breaks)
21958 (:archived-trees . org-export-with-archived-trees)
21959 (:emphasize . org-export-with-emphasize)
21960 (:sub-superscript . org-export-with-sub-superscripts)
21961 (:footnotes . org-export-with-footnotes)
21962 (:drawers . org-export-with-drawers)
21963 (:tags . org-export-with-tags)
21964 (:TeX-macros . org-export-with-TeX-macros)
21965 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
21966 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
21967 (:fixed-width . org-export-with-fixed-width)
21968 (:timestamps . org-export-with-timestamps)
21969 (:author-info . org-export-author-info)
21970 (:time-stamp-file . org-export-time-stamp-file)
21971 (:tables . org-export-with-tables)
21972 (:table-auto-headline . org-export-highlight-first-table-line)
21973 (:style . org-export-html-style)
21974 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
21975 (:convert-org-links . org-export-html-link-org-files-as-html)
21976 (:inline-images . org-export-html-inline-images)
21977 (:html-extension . org-export-html-extension)
21978 (:expand-quoted-html . org-export-html-expand)
21979 (:timestamp . org-export-html-with-timestamp)
21980 (:publishing-directory . org-export-publishing-directory)
21981 (:preamble . org-export-html-preamble)
21982 (:postamble . org-export-html-postamble)
21983 (:auto-preamble . org-export-html-auto-preamble)
21984 (:auto-postamble . org-export-html-auto-postamble)
21985 (:author . user-full-name)
21986 (:email . user-mail-address)))
21988 (defun org-default-export-plist ()
21989 "Return the property list with default settings for the export variables."
21990 (let ((l org-export-plist-vars) rtn e)
21991 (while (setq e (pop l))
21992 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
21993 rtn))
21995 (defun org-infile-export-plist ()
21996 "Return the property list with file-local settings for export."
21997 (save-excursion
21998 (goto-char 0)
21999 (let ((re (org-make-options-regexp
22000 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
22001 p key val text options)
22002 (while (re-search-forward re nil t)
22003 (setq key (org-match-string-no-properties 1)
22004 val (org-match-string-no-properties 2))
22005 (cond
22006 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
22007 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
22008 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
22009 ((string-equal key "DATE") (setq p (plist-put p :date val)))
22010 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
22011 ((string-equal key "TEXT")
22012 (setq text (if text (concat text "\n" val) val)))
22013 ((string-equal key "OPTIONS") (setq options val))))
22014 (setq p (plist-put p :text text))
22015 (when options
22016 (let ((op '(("H" . :headline-levels)
22017 ("num" . :section-numbers)
22018 ("toc" . :table-of-contents)
22019 ("\\n" . :preserve-breaks)
22020 ("@" . :expand-quoted-html)
22021 (":" . :fixed-width)
22022 ("|" . :tables)
22023 ("^" . :sub-superscript)
22024 ("f" . :footnotes)
22025 ("d" . :drawers)
22026 ("tags" . :tags)
22027 ("*" . :emphasize)
22028 ("TeX" . :TeX-macros)
22029 ("LaTeX" . :LaTeX-fragments)
22030 ("skip" . :skip-before-1st-heading)
22031 ("author" . :author-info)
22032 ("timestamp" . :time-stamp-file)))
22034 (while (setq o (pop op))
22035 (if (string-match (concat (regexp-quote (car o))
22036 ":\\([^ \t\n\r;,.]*\\)")
22037 options)
22038 (setq p (plist-put p (cdr o)
22039 (car (read-from-string
22040 (match-string 1 options)))))))))
22041 p)))
22043 (defun org-export-directory (type plist)
22044 (let* ((val (plist-get plist :publishing-directory))
22045 (dir (if (listp val)
22046 (or (cdr (assoc type val)) ".")
22047 val)))
22048 dir))
22050 (defun org-skip-comments (lines)
22051 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22052 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22053 (re2 "^\\(\\*+\\)[ \t\n\r]")
22054 (case-fold-search nil)
22055 rtn line level)
22056 (while (setq line (pop lines))
22057 (cond
22058 ((and (string-match re1 line)
22059 (setq level (- (match-end 1) (match-beginning 1))))
22060 ;; Beginning of a COMMENT subtree. Skip it.
22061 (while (and (setq line (pop lines))
22062 (or (not (string-match re2 line))
22063 (> (- (match-end 1) (match-beginning 1)) level))))
22064 (setq lines (cons line lines)))
22065 ((string-match "^#" line)
22066 ;; an ordinary comment line
22068 ((and org-export-table-remove-special-lines
22069 (string-match "^[ \t]*|" line)
22070 (or (string-match "^[ \t]*| *[!_^] *|" line)
22071 (and (string-match "| *<[0-9]+> *|" line)
22072 (not (string-match "| *[^ <|]" line)))))
22073 ;; a special table line that should be removed
22075 (t (setq rtn (cons line rtn)))))
22076 (nreverse rtn)))
22078 (defun org-export (&optional arg)
22079 (interactive)
22080 (let ((help "[t] insert the export option template
22081 \[v] limit export to visible part of outline tree
22083 \[a] export as ASCII
22085 \[h] export as HTML
22086 \[H] export as HTML to temporary buffer
22087 \[R] export region as HTML
22088 \[b] export as HTML and browse immediately
22089 \[x] export as XOXO
22091 \[l] export as LaTeX
22092 \[L] export as LaTeX to temporary buffer
22094 \[i] export current file as iCalendar file
22095 \[I] export all agenda files as iCalendar files
22096 \[c] export agenda files into combined iCalendar file
22098 \[F] publish current file
22099 \[P] publish current project
22100 \[X] publish... (project will be prompted for)
22101 \[A] publish all projects")
22102 (cmds
22103 '((?t . org-insert-export-options-template)
22104 (?v . org-export-visible)
22105 (?a . org-export-as-ascii)
22106 (?h . org-export-as-html)
22107 (?b . org-export-as-html-and-open)
22108 (?H . org-export-as-html-to-buffer)
22109 (?R . org-export-region-as-html)
22110 (?x . org-export-as-xoxo)
22111 (?l . org-export-as-latex)
22112 (?L . org-export-as-latex-to-buffer)
22113 (?i . org-export-icalendar-this-file)
22114 (?I . org-export-icalendar-all-agenda-files)
22115 (?c . org-export-icalendar-combine-agenda-files)
22116 (?F . org-publish-current-file)
22117 (?P . org-publish-current-project)
22118 (?X . org-publish)
22119 (?A . org-publish-all)))
22120 r1 r2 ass)
22121 (save-window-excursion
22122 (delete-other-windows)
22123 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22124 (princ help))
22125 (message "Select command: ")
22126 (setq r1 (read-char-exclusive)))
22127 (setq r2 (if (< r1 27) (+ r1 96) r1))
22128 (if (setq ass (assq r2 cmds))
22129 (call-interactively (cdr ass))
22130 (error "No command associated with key %c" r1))))
22132 (defconst org-html-entities
22133 '(("nbsp")
22134 ("iexcl")
22135 ("cent")
22136 ("pound")
22137 ("curren")
22138 ("yen")
22139 ("brvbar")
22140 ("vert" . "&#124;")
22141 ("sect")
22142 ("uml")
22143 ("copy")
22144 ("ordf")
22145 ("laquo")
22146 ("not")
22147 ("shy")
22148 ("reg")
22149 ("macr")
22150 ("deg")
22151 ("plusmn")
22152 ("sup2")
22153 ("sup3")
22154 ("acute")
22155 ("micro")
22156 ("para")
22157 ("middot")
22158 ("odot"."o")
22159 ("star"."*")
22160 ("cedil")
22161 ("sup1")
22162 ("ordm")
22163 ("raquo")
22164 ("frac14")
22165 ("frac12")
22166 ("frac34")
22167 ("iquest")
22168 ("Agrave")
22169 ("Aacute")
22170 ("Acirc")
22171 ("Atilde")
22172 ("Auml")
22173 ("Aring") ("AA"."&Aring;")
22174 ("AElig")
22175 ("Ccedil")
22176 ("Egrave")
22177 ("Eacute")
22178 ("Ecirc")
22179 ("Euml")
22180 ("Igrave")
22181 ("Iacute")
22182 ("Icirc")
22183 ("Iuml")
22184 ("ETH")
22185 ("Ntilde")
22186 ("Ograve")
22187 ("Oacute")
22188 ("Ocirc")
22189 ("Otilde")
22190 ("Ouml")
22191 ("times")
22192 ("Oslash")
22193 ("Ugrave")
22194 ("Uacute")
22195 ("Ucirc")
22196 ("Uuml")
22197 ("Yacute")
22198 ("THORN")
22199 ("szlig")
22200 ("agrave")
22201 ("aacute")
22202 ("acirc")
22203 ("atilde")
22204 ("auml")
22205 ("aring")
22206 ("aelig")
22207 ("ccedil")
22208 ("egrave")
22209 ("eacute")
22210 ("ecirc")
22211 ("euml")
22212 ("igrave")
22213 ("iacute")
22214 ("icirc")
22215 ("iuml")
22216 ("eth")
22217 ("ntilde")
22218 ("ograve")
22219 ("oacute")
22220 ("ocirc")
22221 ("otilde")
22222 ("ouml")
22223 ("divide")
22224 ("oslash")
22225 ("ugrave")
22226 ("uacute")
22227 ("ucirc")
22228 ("uuml")
22229 ("yacute")
22230 ("thorn")
22231 ("yuml")
22232 ("fnof")
22233 ("Alpha")
22234 ("Beta")
22235 ("Gamma")
22236 ("Delta")
22237 ("Epsilon")
22238 ("Zeta")
22239 ("Eta")
22240 ("Theta")
22241 ("Iota")
22242 ("Kappa")
22243 ("Lambda")
22244 ("Mu")
22245 ("Nu")
22246 ("Xi")
22247 ("Omicron")
22248 ("Pi")
22249 ("Rho")
22250 ("Sigma")
22251 ("Tau")
22252 ("Upsilon")
22253 ("Phi")
22254 ("Chi")
22255 ("Psi")
22256 ("Omega")
22257 ("alpha")
22258 ("beta")
22259 ("gamma")
22260 ("delta")
22261 ("epsilon")
22262 ("varepsilon"."&epsilon;")
22263 ("zeta")
22264 ("eta")
22265 ("theta")
22266 ("iota")
22267 ("kappa")
22268 ("lambda")
22269 ("mu")
22270 ("nu")
22271 ("xi")
22272 ("omicron")
22273 ("pi")
22274 ("rho")
22275 ("sigmaf") ("varsigma"."&sigmaf;")
22276 ("sigma")
22277 ("tau")
22278 ("upsilon")
22279 ("phi")
22280 ("chi")
22281 ("psi")
22282 ("omega")
22283 ("thetasym") ("vartheta"."&thetasym;")
22284 ("upsih")
22285 ("piv")
22286 ("bull") ("bullet"."&bull;")
22287 ("hellip") ("dots"."&hellip;")
22288 ("prime")
22289 ("Prime")
22290 ("oline")
22291 ("frasl")
22292 ("weierp")
22293 ("image")
22294 ("real")
22295 ("trade")
22296 ("alefsym")
22297 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
22298 ("uarr") ("uparrow"."&uarr;")
22299 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
22300 ("darr")("downarrow"."&darr;")
22301 ("harr") ("leftrightarrow"."&harr;")
22302 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
22303 ("lArr") ("Leftarrow"."&lArr;")
22304 ("uArr") ("Uparrow"."&uArr;")
22305 ("rArr") ("Rightarrow"."&rArr;")
22306 ("dArr") ("Downarrow"."&dArr;")
22307 ("hArr") ("Leftrightarrow"."&hArr;")
22308 ("forall")
22309 ("part") ("partial"."&part;")
22310 ("exist") ("exists"."&exist;")
22311 ("empty") ("emptyset"."&empty;")
22312 ("nabla")
22313 ("isin") ("in"."&isin;")
22314 ("notin")
22315 ("ni")
22316 ("prod")
22317 ("sum")
22318 ("minus")
22319 ("lowast") ("ast"."&lowast;")
22320 ("radic")
22321 ("prop") ("proptp"."&prop;")
22322 ("infin") ("infty"."&infin;")
22323 ("ang") ("angle"."&ang;")
22324 ("and") ("vee"."&and;")
22325 ("or") ("wedge"."&or;")
22326 ("cap")
22327 ("cup")
22328 ("int")
22329 ("there4")
22330 ("sim")
22331 ("cong") ("simeq"."&cong;")
22332 ("asymp")("approx"."&asymp;")
22333 ("ne") ("neq"."&ne;")
22334 ("equiv")
22335 ("le")
22336 ("ge")
22337 ("sub") ("subset"."&sub;")
22338 ("sup") ("supset"."&sup;")
22339 ("nsub")
22340 ("sube")
22341 ("supe")
22342 ("oplus")
22343 ("otimes")
22344 ("perp")
22345 ("sdot") ("cdot"."&sdot;")
22346 ("lceil")
22347 ("rceil")
22348 ("lfloor")
22349 ("rfloor")
22350 ("lang")
22351 ("rang")
22352 ("loz") ("Diamond"."&loz;")
22353 ("spades") ("spadesuit"."&spades;")
22354 ("clubs") ("clubsuit"."&clubs;")
22355 ("hearts") ("diamondsuit"."&hearts;")
22356 ("diams") ("diamondsuit"."&diams;")
22357 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
22358 ("quot")
22359 ("amp")
22360 ("lt")
22361 ("gt")
22362 ("OElig")
22363 ("oelig")
22364 ("Scaron")
22365 ("scaron")
22366 ("Yuml")
22367 ("circ")
22368 ("tilde")
22369 ("ensp")
22370 ("emsp")
22371 ("thinsp")
22372 ("zwnj")
22373 ("zwj")
22374 ("lrm")
22375 ("rlm")
22376 ("ndash")
22377 ("mdash")
22378 ("lsquo")
22379 ("rsquo")
22380 ("sbquo")
22381 ("ldquo")
22382 ("rdquo")
22383 ("bdquo")
22384 ("dagger")
22385 ("Dagger")
22386 ("permil")
22387 ("lsaquo")
22388 ("rsaquo")
22389 ("euro")
22391 ("arccos"."arccos")
22392 ("arcsin"."arcsin")
22393 ("arctan"."arctan")
22394 ("arg"."arg")
22395 ("cos"."cos")
22396 ("cosh"."cosh")
22397 ("cot"."cot")
22398 ("coth"."coth")
22399 ("csc"."csc")
22400 ("deg"."deg")
22401 ("det"."det")
22402 ("dim"."dim")
22403 ("exp"."exp")
22404 ("gcd"."gcd")
22405 ("hom"."hom")
22406 ("inf"."inf")
22407 ("ker"."ker")
22408 ("lg"."lg")
22409 ("lim"."lim")
22410 ("liminf"."liminf")
22411 ("limsup"."limsup")
22412 ("ln"."ln")
22413 ("log"."log")
22414 ("max"."max")
22415 ("min"."min")
22416 ("Pr"."Pr")
22417 ("sec"."sec")
22418 ("sin"."sin")
22419 ("sinh"."sinh")
22420 ("sup"."sup")
22421 ("tan"."tan")
22422 ("tanh"."tanh")
22424 "Entities for TeX->HTML translation.
22425 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
22426 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
22427 In that case, \"\\ent\" will be translated to \"&other;\".
22428 The list contains HTML entities for Latin-1, Greek and other symbols.
22429 It is supplemented by a number of commonly used TeX macros with appropriate
22430 translations. There is currently no way for users to extend this.")
22432 ;;; General functions for all backends
22434 (defun org-cleaned-string-for-export (string &rest parameters)
22435 "Cleanup a buffer STRING so that links can be created safely."
22436 (interactive)
22437 (let* ((re-radio (and org-target-link-regexp
22438 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
22439 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
22440 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
22441 (re-archive (concat ":" org-archive-tag ":"))
22442 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
22443 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
22444 (htmlp (plist-get parameters :for-html))
22445 (asciip (plist-get parameters :for-ascii))
22446 (latexp (plist-get parameters :for-LaTeX))
22447 (commentsp (plist-get parameters :comments))
22448 (archived-trees (plist-get parameters :archived-trees))
22449 (inhibit-read-only t)
22450 (outline-regexp "\\*+ ")
22451 a b xx
22452 rtn p)
22453 (with-current-buffer (get-buffer-create " org-mode-tmp")
22454 (erase-buffer)
22455 (insert string)
22456 ;; Remove license-to-kill stuff
22457 (while (setq p (text-property-any (point-min) (point-max)
22458 :org-license-to-kill t))
22459 (delete-region p (next-single-property-change p :org-license-to-kill)))
22461 (let ((org-inhibit-startup t)) (org-mode))
22462 (untabify (point-min) (point-max))
22464 ;; Get the correct stuff before the first headline
22465 (when (plist-get parameters :skip-before-1st-heading)
22466 (goto-char (point-min))
22467 (when (re-search-forward "^\\*+[ \t]" nil t)
22468 (delete-region (point-min) (match-beginning 0))
22469 (goto-char (point-min))
22470 (insert "\n")))
22471 (when (plist-get parameters :add-text)
22472 (goto-char (point-min))
22473 (insert (plist-get parameters :add-text) "\n"))
22475 ;; Get rid of archived trees
22476 (when (not (eq archived-trees t))
22477 (goto-char (point-min))
22478 (while (re-search-forward re-archive nil t)
22479 (if (not (org-on-heading-p t))
22480 (org-end-of-subtree t)
22481 (beginning-of-line 1)
22482 (setq a (if archived-trees
22483 (1+ (point-at-eol)) (point))
22484 b (org-end-of-subtree t))
22485 (if (> b a) (delete-region a b)))))
22487 ;; Get rid of drawers
22488 (unless (eq t org-export-with-drawers)
22489 (goto-char (point-min))
22490 (let ((re (concat "^[ \t]*:\\("
22491 (mapconcat 'identity
22492 (if (listp org-export-with-drawers)
22493 org-export-with-drawers
22494 org-drawers)
22495 "\\|")
22496 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
22497 (while (re-search-forward re nil t)
22498 (replace-match ""))))
22500 ;; Find targets in comments and move them out of comments,
22501 ;; but mark them as targets that should be invisible
22502 (goto-char (point-min))
22503 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
22504 (replace-match "\\1(INVISIBLE)"))
22506 ;; Protect backend specific stuff, throw away the others.
22507 (goto-char (point-min))
22508 (let ((formatters
22509 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
22510 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
22511 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
22512 fmt)
22513 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
22514 (add-text-properties (match-beginning 0) (match-end 0)
22515 '(org-protected t)))
22516 (while formatters
22517 (setq fmt (pop formatters))
22518 (when (car fmt)
22519 (goto-char (point-min))
22520 (while (re-search-forward (concat "^#\\+" (cadr fmt)
22521 ":[ \t]*\\(.*\\)") nil t)
22522 (replace-match "\\1" t)
22523 (add-text-properties
22524 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
22525 '(org-protected t))))
22526 (goto-char (point-min))
22527 (while (re-search-forward
22528 (concat "^#\\+"
22529 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
22530 (cadddr fmt) "\\>.*\n?") nil t)
22531 (if (car fmt)
22532 (add-text-properties (match-beginning 1) (1+ (match-end 1))
22533 '(org-protected t))
22534 (delete-region (match-beginning 0) (match-end 0))))))
22536 ;; Protect quoted subtrees
22537 (goto-char (point-min))
22538 (while (re-search-forward re-quote nil t)
22539 (goto-char (match-beginning 0))
22540 (end-of-line 1)
22541 (add-text-properties (point) (org-end-of-subtree t)
22542 '(org-protected t)))
22544 ;; Remove subtrees that are commented
22545 (goto-char (point-min))
22546 (while (re-search-forward re-commented nil t)
22547 (goto-char (match-beginning 0))
22548 (delete-region (point) (org-end-of-subtree t)))
22550 ;; Remove special table lines
22551 (when org-export-table-remove-special-lines
22552 (goto-char (point-min))
22553 (while (re-search-forward "^[ \t]*|" nil t)
22554 (beginning-of-line 1)
22555 (if (or (looking-at "[ \t]*| *[!_^] *|")
22556 (and (looking-at ".*?| *<[0-9]+> *|")
22557 (not (looking-at ".*?| *[^ <|]"))))
22558 (delete-region (max (point-min) (1- (point-at-bol)))
22559 (point-at-eol))
22560 (end-of-line 1))))
22562 ;; Specific LaTeX stuff
22563 (when latexp
22564 (require 'org-export-latex nil)
22565 (org-export-latex-cleaned-string))
22567 ;; Specific HTML stuff
22568 (when htmlp
22569 ;; Convert LaTeX fragments to images
22570 (when (plist-get parameters :LaTeX-fragments)
22571 (org-format-latex
22572 (concat "ltxpng/" (file-name-sans-extension
22573 (file-name-nondirectory
22574 org-current-export-file)))
22575 org-current-export-dir nil "Creating LaTeX image %s"))
22576 (message "Exporting..."))
22578 ;; Remove or replace comments
22579 (goto-char (point-min))
22580 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
22581 (if commentsp
22582 (progn (add-text-properties
22583 (match-beginning 0) (match-end 0) '(org-protected t))
22584 (replace-match (format commentsp (match-string 1)) t t))
22585 (replace-match "")))
22587 ;; Find matches for radio targets and turn them into internal links
22588 (goto-char (point-min))
22589 (when re-radio
22590 (while (re-search-forward re-radio nil t)
22591 (org-if-unprotected
22592 (replace-match "\\1[[\\2]]"))))
22594 ;; Find all links that contain a newline and put them into a single line
22595 (goto-char (point-min))
22596 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
22597 (org-if-unprotected
22598 (replace-match "\\1 \\3")
22599 (goto-char (match-beginning 0))))
22602 ;; Normalize links: Convert angle and plain links into bracket links
22603 ;; Expand link abbreviations
22604 (goto-char (point-min))
22605 (while (re-search-forward re-plain-link nil t)
22606 (goto-char (1- (match-end 0)))
22607 (org-if-unprotected
22608 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22609 ":" (match-string 3) "]]")))
22610 ;; added 'org-link face to links
22611 (put-text-property 0 (length s) 'face 'org-link s)
22612 (replace-match s t t))))
22613 (goto-char (point-min))
22614 (while (re-search-forward re-angle-link nil t)
22615 (goto-char (1- (match-end 0)))
22616 (org-if-unprotected
22617 (let* ((s (concat (match-string 1) "[[" (match-string 2)
22618 ":" (match-string 3) "]]")))
22619 (put-text-property 0 (length s) 'face 'org-link s)
22620 (replace-match s t t))))
22621 (goto-char (point-min))
22622 (while (re-search-forward org-bracket-link-regexp nil t)
22623 (org-if-unprotected
22624 (let* ((s (concat "[[" (setq xx (save-match-data
22625 (org-link-expand-abbrev (match-string 1))))
22627 (if (match-end 3)
22628 (match-string 2)
22629 (concat "[" xx "]"))
22630 "]")))
22631 (put-text-property 0 (length s) 'face 'org-link s)
22632 (replace-match s t t))))
22634 ;; Find multiline emphasis and put them into single line
22635 (when (plist-get parameters :emph-multiline)
22636 (goto-char (point-min))
22637 (while (re-search-forward org-emph-re nil t)
22638 (if (not (= (char-after (match-beginning 3))
22639 (char-after (match-beginning 4))))
22640 (org-if-unprotected
22641 (subst-char-in-region (match-beginning 0) (match-end 0)
22642 ?\n ?\ t)
22643 (goto-char (1- (match-end 0))))
22644 (goto-char (1+ (match-beginning 0))))))
22646 (setq rtn (buffer-string)))
22647 (kill-buffer " org-mode-tmp")
22648 rtn))
22650 (defun org-export-grab-title-from-buffer ()
22651 "Get a title for the current document, from looking at the buffer."
22652 (let ((inhibit-read-only t))
22653 (save-excursion
22654 (goto-char (point-min))
22655 (let ((end (save-excursion (outline-next-heading) (point))))
22656 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
22657 ;; Mark the line so that it will not be exported as normal text.
22658 (org-unmodified
22659 (add-text-properties (match-beginning 0) (match-end 0)
22660 (list :org-license-to-kill t)))
22661 ;; Return the title string
22662 (org-trim (match-string 0)))))))
22664 (defun org-export-get-title-from-subtree ()
22665 "Return subtree title and exclude it from export."
22666 (let (title (m (mark)))
22667 (save-excursion
22668 (goto-char (region-beginning))
22669 (when (and (org-at-heading-p)
22670 (>= (org-end-of-subtree t t) (region-end)))
22671 ;; This is a subtree, we take the title from the first heading
22672 (goto-char (region-beginning))
22673 (looking-at org-todo-line-regexp)
22674 (setq title (match-string 3))
22675 (org-unmodified
22676 (add-text-properties (point) (1+ (point-at-eol))
22677 (list :org-license-to-kill t)))))
22678 title))
22680 (defun org-solidify-link-text (s &optional alist)
22681 "Take link text and make a safe target out of it."
22682 (save-match-data
22683 (let* ((rtn
22684 (mapconcat
22685 'identity
22686 (org-split-string s "[ \t\r\n]+") "--"))
22687 (a (assoc rtn alist)))
22688 (or (cdr a) rtn))))
22690 (defun org-get-min-level (lines)
22691 "Get the minimum level in LINES."
22692 (let ((re "^\\(\\*+\\) ") l min)
22693 (catch 'exit
22694 (while (setq l (pop lines))
22695 (if (string-match re l)
22696 (throw 'exit (org-tr-level (length (match-string 1 l))))))
22697 1)))
22699 ;; Variable holding the vector with section numbers
22700 (defvar org-section-numbers (make-vector org-level-max 0))
22702 (defun org-init-section-numbers ()
22703 "Initialize the vector for the section numbers."
22704 (let* ((level -1)
22705 (numbers (nreverse (org-split-string "" "\\.")))
22706 (depth (1- (length org-section-numbers)))
22707 (i depth) number-string)
22708 (while (>= i 0)
22709 (if (> i level)
22710 (aset org-section-numbers i 0)
22711 (setq number-string (or (car numbers) "0"))
22712 (if (string-match "\\`[A-Z]\\'" number-string)
22713 (aset org-section-numbers i
22714 (- (string-to-char number-string) ?A -1))
22715 (aset org-section-numbers i (string-to-number number-string)))
22716 (pop numbers))
22717 (setq i (1- i)))))
22719 (defun org-section-number (&optional level)
22720 "Return a string with the current section number.
22721 When LEVEL is non-nil, increase section numbers on that level."
22722 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
22723 (when level
22724 (when (> level -1)
22725 (aset org-section-numbers
22726 level (1+ (aref org-section-numbers level))))
22727 (setq idx (1+ level))
22728 (while (<= idx depth)
22729 (if (not (= idx 1))
22730 (aset org-section-numbers idx 0))
22731 (setq idx (1+ idx))))
22732 (setq idx 0)
22733 (while (<= idx depth)
22734 (setq n (aref org-section-numbers idx))
22735 (setq string (concat string (if (not (string= string "")) "." "")
22736 (int-to-string n)))
22737 (setq idx (1+ idx)))
22738 (save-match-data
22739 (if (string-match "\\`\\([@0]\\.\\)+" string)
22740 (setq string (replace-match "" t nil string)))
22741 (if (string-match "\\(\\.0\\)+\\'" string)
22742 (setq string (replace-match "" t nil string))))
22743 string))
22745 ;;; ASCII export
22747 (defvar org-last-level nil) ; dynamically scoped variable
22748 (defvar org-min-level nil) ; dynamically scoped variable
22749 (defvar org-levels-open nil) ; dynamically scoped parameter
22750 (defvar org-ascii-current-indentation nil) ; For communication
22752 (defun org-export-as-ascii (arg)
22753 "Export the outline as a pretty ASCII file.
22754 If there is an active region, export only the region.
22755 The prefix ARG specifies how many levels of the outline should become
22756 underlined headlines. The default is 3."
22757 (interactive "P")
22758 (setq-default org-todo-line-regexp org-todo-line-regexp)
22759 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
22760 (org-infile-export-plist)))
22761 (region-p (org-region-active-p))
22762 (subtree-p
22763 (when region-p
22764 (save-excursion
22765 (goto-char (region-beginning))
22766 (and (org-at-heading-p)
22767 (>= (org-end-of-subtree t t) (region-end))))))
22768 (custom-times org-display-custom-times)
22769 (org-ascii-current-indentation '(0 . 0))
22770 (level 0) line txt
22771 (umax nil)
22772 (umax-toc nil)
22773 (case-fold-search nil)
22774 (filename (concat (file-name-as-directory
22775 (org-export-directory :ascii opt-plist))
22776 (file-name-sans-extension
22777 (or (and subtree-p
22778 (org-entry-get (region-beginning)
22779 "EXPORT_FILE_NAME" t))
22780 (file-name-nondirectory buffer-file-name)))
22781 ".txt"))
22782 (filename (if (equal (file-truename filename)
22783 (file-truename buffer-file-name))
22784 (concat filename ".txt")
22785 filename))
22786 (buffer (find-file-noselect filename))
22787 (org-levels-open (make-vector org-level-max nil))
22788 (odd org-odd-levels-only)
22789 (date (plist-get opt-plist :date))
22790 (author (plist-get opt-plist :author))
22791 (title (or (and subtree-p (org-export-get-title-from-subtree))
22792 (plist-get opt-plist :title)
22793 (and (not
22794 (plist-get opt-plist :skip-before-1st-heading))
22795 (org-export-grab-title-from-buffer))
22796 (file-name-sans-extension
22797 (file-name-nondirectory buffer-file-name))))
22798 (email (plist-get opt-plist :email))
22799 (language (plist-get opt-plist :language))
22800 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
22801 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
22802 (todo nil)
22803 (lang-words nil)
22804 (region
22805 (buffer-substring
22806 (if (org-region-active-p) (region-beginning) (point-min))
22807 (if (org-region-active-p) (region-end) (point-max))))
22808 (lines (org-split-string
22809 (org-cleaned-string-for-export
22810 region
22811 :for-ascii t
22812 :skip-before-1st-heading
22813 (plist-get opt-plist :skip-before-1st-heading)
22814 :archived-trees
22815 (plist-get opt-plist :archived-trees)
22816 :add-text (plist-get opt-plist :text))
22817 "\n"))
22818 thetoc have-headings first-heading-pos
22819 table-open table-buffer)
22821 (let ((inhibit-read-only t))
22822 (org-unmodified
22823 (remove-text-properties (point-min) (point-max)
22824 '(:org-license-to-kill t))))
22826 (setq org-min-level (org-get-min-level lines))
22827 (setq org-last-level org-min-level)
22828 (org-init-section-numbers)
22830 (find-file-noselect filename)
22832 (setq lang-words (or (assoc language org-export-language-setup)
22833 (assoc "en" org-export-language-setup)))
22834 (switch-to-buffer-other-window buffer)
22835 (erase-buffer)
22836 (fundamental-mode)
22837 ;; create local variables for all options, to make sure all called
22838 ;; functions get the correct information
22839 (mapc (lambda (x)
22840 (set (make-local-variable (cdr x))
22841 (plist-get opt-plist (car x))))
22842 org-export-plist-vars)
22843 (org-set-local 'org-odd-levels-only odd)
22844 (setq umax (if arg (prefix-numeric-value arg)
22845 org-export-headline-levels))
22846 (setq umax-toc (if (integerp org-export-with-toc)
22847 (min org-export-with-toc umax)
22848 umax))
22850 ;; File header
22851 (if title (org-insert-centered title ?=))
22852 (insert "\n")
22853 (if (and (or author email)
22854 org-export-author-info)
22855 (insert (concat (nth 1 lang-words) ": " (or author "")
22856 (if email (concat " <" email ">") "")
22857 "\n")))
22859 (cond
22860 ((and date (string-match "%" date))
22861 (setq date (format-time-string date (current-time))))
22862 (date)
22863 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
22865 (if (and date org-export-time-stamp-file)
22866 (insert (concat (nth 2 lang-words) ": " date"\n")))
22868 (insert "\n\n")
22870 (if org-export-with-toc
22871 (progn
22872 (push (concat (nth 3 lang-words) "\n") thetoc)
22873 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
22874 (mapc '(lambda (line)
22875 (if (string-match org-todo-line-regexp
22876 line)
22877 ;; This is a headline
22878 (progn
22879 (setq have-headings t)
22880 (setq level (- (match-end 1) (match-beginning 1))
22881 level (org-tr-level level)
22882 txt (match-string 3 line)
22883 todo
22884 (or (and org-export-mark-todo-in-toc
22885 (match-beginning 2)
22886 (not (member (match-string 2 line)
22887 org-done-keywords)))
22888 ; TODO, not DONE
22889 (and org-export-mark-todo-in-toc
22890 (= level umax-toc)
22891 (org-search-todo-below
22892 line lines level))))
22893 (setq txt (org-html-expand-for-ascii txt))
22895 (while (string-match org-bracket-link-regexp txt)
22896 (setq txt
22897 (replace-match
22898 (match-string (if (match-end 2) 3 1) txt)
22899 t t txt)))
22901 (if (and (memq org-export-with-tags '(not-in-toc nil))
22902 (string-match
22903 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
22904 txt))
22905 (setq txt (replace-match "" t t txt)))
22906 (if (string-match quote-re0 txt)
22907 (setq txt (replace-match "" t t txt)))
22909 (if org-export-with-section-numbers
22910 (setq txt (concat (org-section-number level)
22911 " " txt)))
22912 (if (<= level umax-toc)
22913 (progn
22914 (push
22915 (concat
22916 (make-string
22917 (* (max 0 (- level org-min-level)) 4) ?\ )
22918 (format (if todo "%s (*)\n" "%s\n") txt))
22919 thetoc)
22920 (setq org-last-level level))
22921 ))))
22922 lines)
22923 (setq thetoc (if have-headings (nreverse thetoc) nil))))
22925 (org-init-section-numbers)
22926 (while (setq line (pop lines))
22927 ;; Remove the quoted HTML tags.
22928 (setq line (org-html-expand-for-ascii line))
22929 ;; Remove targets
22930 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
22931 (setq line (replace-match "" t t line)))
22932 ;; Replace internal links
22933 (while (string-match org-bracket-link-regexp line)
22934 (setq line (replace-match
22935 (if (match-end 3) "[\\3]" "[\\1]")
22936 t nil line)))
22937 (when custom-times
22938 (setq line (org-translate-time line)))
22939 (cond
22940 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
22941 ;; a Headline
22942 (setq first-heading-pos (or first-heading-pos (point)))
22943 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
22944 txt (match-string 2 line))
22945 (org-ascii-level-start level txt umax lines))
22947 ((and org-export-with-tables
22948 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
22949 (if (not table-open)
22950 ;; New table starts
22951 (setq table-open t table-buffer nil))
22952 ;; Accumulate lines
22953 (setq table-buffer (cons line table-buffer))
22954 (when (or (not lines)
22955 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
22956 (car lines))))
22957 (setq table-open nil
22958 table-buffer (nreverse table-buffer))
22959 (insert (mapconcat
22960 (lambda (x)
22961 (org-fix-indentation x org-ascii-current-indentation))
22962 (org-format-table-ascii table-buffer)
22963 "\n") "\n")))
22965 (setq line (org-fix-indentation line org-ascii-current-indentation))
22966 (if (and org-export-with-fixed-width
22967 (string-match "^\\([ \t]*\\)\\(:\\)" line))
22968 (setq line (replace-match "\\1" nil nil line)))
22969 (insert line "\n"))))
22971 (normal-mode)
22973 ;; insert the table of contents
22974 (when thetoc
22975 (goto-char (point-min))
22976 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
22977 (progn
22978 (goto-char (match-beginning 0))
22979 (replace-match ""))
22980 (goto-char first-heading-pos))
22981 (mapc 'insert thetoc)
22982 (or (looking-at "[ \t]*\n[ \t]*\n")
22983 (insert "\n\n")))
22985 ;; Convert whitespace place holders
22986 (goto-char (point-min))
22987 (let (beg end)
22988 (while (setq beg (next-single-property-change (point) 'org-whitespace))
22989 (setq end (next-single-property-change beg 'org-whitespace))
22990 (goto-char beg)
22991 (delete-region beg end)
22992 (insert (make-string (- end beg) ?\ ))))
22994 (save-buffer)
22995 ;; remove display and invisible chars
22996 (let (beg end)
22997 (goto-char (point-min))
22998 (while (setq beg (next-single-property-change (point) 'display))
22999 (setq end (next-single-property-change beg 'display))
23000 (delete-region beg end)
23001 (goto-char beg)
23002 (insert "=>"))
23003 (goto-char (point-min))
23004 (while (setq beg (next-single-property-change (point) 'org-cwidth))
23005 (setq end (next-single-property-change beg 'org-cwidth))
23006 (delete-region beg end)
23007 (goto-char beg)))
23008 (goto-char (point-min))))
23010 (defun org-search-todo-below (line lines level)
23011 "Search the subtree below LINE for any TODO entries."
23012 (let ((rest (cdr (memq line lines)))
23013 (re org-todo-line-regexp)
23014 line lv todo)
23015 (catch 'exit
23016 (while (setq line (pop rest))
23017 (if (string-match re line)
23018 (progn
23019 (setq lv (- (match-end 1) (match-beginning 1))
23020 todo (and (match-beginning 2)
23021 (not (member (match-string 2 line)
23022 org-done-keywords))))
23023 ; TODO, not DONE
23024 (if (<= lv level) (throw 'exit nil))
23025 (if todo (throw 'exit t))))))))
23027 (defun org-html-expand-for-ascii (line)
23028 "Handle quoted HTML for ASCII export."
23029 (if org-export-html-expand
23030 (while (string-match "@<[^<>\n]*>" line)
23031 ;; We just remove the tags for now.
23032 (setq line (replace-match "" nil nil line))))
23033 line)
23035 (defun org-insert-centered (s &optional underline)
23036 "Insert the string S centered and underline it with character UNDERLINE."
23037 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23038 (insert (make-string ind ?\ ) s "\n")
23039 (if underline
23040 (insert (make-string ind ?\ )
23041 (make-string (string-width s) underline)
23042 "\n"))))
23044 (defun org-ascii-level-start (level title umax &optional lines)
23045 "Insert a new level in ASCII export."
23046 (let (char (n (- level umax 1)) (ind 0))
23047 (if (> level umax)
23048 (progn
23049 (insert (make-string (* 2 n) ?\ )
23050 (char-to-string (nth (% n (length org-export-ascii-bullets))
23051 org-export-ascii-bullets))
23052 " " title "\n")
23053 ;; find the indentation of the next non-empty line
23054 (catch 'stop
23055 (while lines
23056 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23057 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23058 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23059 (pop lines)))
23060 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23061 (if (or (not (equal (char-before) ?\n))
23062 (not (equal (char-before (1- (point))) ?\n)))
23063 (insert "\n"))
23064 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23065 (unless org-export-with-tags
23066 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23067 (setq title (replace-match "" t t title))))
23068 (if org-export-with-section-numbers
23069 (setq title (concat (org-section-number level) " " title)))
23070 (insert title "\n" (make-string (string-width title) char) "\n")
23071 (setq org-ascii-current-indentation '(0 . 0)))))
23073 (defun org-export-visible (type arg)
23074 "Create a copy of the visible part of the current buffer, and export it.
23075 The copy is created in a temporary buffer and removed after use.
23076 TYPE is the final key (as a string) that also select the export command in
23077 the `C-c C-e' export dispatcher.
23078 As a special case, if the you type SPC at the prompt, the temporary
23079 org-mode file will not be removed but presented to you so that you can
23080 continue to use it. The prefix arg ARG is passed through to the exporting
23081 command."
23082 (interactive
23083 (list (progn
23084 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23085 (read-char-exclusive))
23086 current-prefix-arg))
23087 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23088 (error "Invalid export key"))
23089 (let* ((binding (cdr (assoc type
23090 '((?a . org-export-as-ascii)
23091 (?\C-a . org-export-as-ascii)
23092 (?b . org-export-as-html-and-open)
23093 (?\C-b . org-export-as-html-and-open)
23094 (?h . org-export-as-html)
23095 (?H . org-export-as-html-to-buffer)
23096 (?l . org-export-as-latex)
23097 (?L . org-export-as-latex-to-buffer)
23098 (?R . org-export-region-as-html)
23099 (?x . org-export-as-xoxo)))))
23100 (keepp (equal type ?\ ))
23101 (file buffer-file-name)
23102 (buffer (get-buffer-create "*Org Export Visible*"))
23103 s e)
23104 ;; Need to hack the drawers here.
23105 (save-excursion
23106 (goto-char (point-min))
23107 (while (re-search-forward org-drawer-regexp nil t)
23108 (goto-char (match-beginning 1))
23109 (or (org-invisible-p) (org-flag-drawer nil))))
23110 (with-current-buffer buffer (erase-buffer))
23111 (save-excursion
23112 (setq s (goto-char (point-min)))
23113 (while (not (= (point) (point-max)))
23114 (goto-char (org-find-invisible))
23115 (append-to-buffer buffer s (point))
23116 (setq s (goto-char (org-find-visible))))
23117 (org-cycle-hide-drawers 'all)
23118 (goto-char (point-min))
23119 (unless keepp
23120 ;; Copy all comment lines to the end, to make sure #+ settings are
23121 ;; still available for the second export step. Kind of a hack, but
23122 ;; does do the trick.
23123 (if (looking-at "#[^\r\n]*")
23124 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23125 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23126 (append-to-buffer buffer (1+ (match-beginning 0))
23127 (min (point-max) (1+ (match-end 0))))))
23128 (set-buffer buffer)
23129 (let ((buffer-file-name file)
23130 (org-inhibit-startup t))
23131 (org-mode)
23132 (show-all)
23133 (unless keepp (funcall binding arg))))
23134 (if (not keepp)
23135 (kill-buffer buffer)
23136 (switch-to-buffer-other-window buffer)
23137 (goto-char (point-min)))))
23139 (defun org-find-visible ()
23140 (let ((s (point)))
23141 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23142 (get-char-property s 'invisible)))
23144 (defun org-find-invisible ()
23145 (let ((s (point)))
23146 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23147 (not (get-char-property s 'invisible))))
23150 ;;; HTML export
23152 (defun org-get-current-options ()
23153 "Return a string with current options as keyword options.
23154 Does include HTML export options as well as TODO and CATEGORY stuff."
23155 (format
23156 "#+TITLE: %s
23157 #+AUTHOR: %s
23158 #+EMAIL: %s
23159 #+LANGUAGE: %s
23160 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23161 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
23162 #+CATEGORY: %s
23163 #+SEQ_TODO: %s
23164 #+TYP_TODO: %s
23165 #+PRIORITIES: %c %c %c
23166 #+DRAWERS: %s
23167 #+STARTUP: %s %s %s %s %s
23168 #+TAGS: %s
23169 #+ARCHIVE: %s
23170 #+LINK: %s
23172 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23173 org-export-headline-levels
23174 org-export-with-section-numbers
23175 org-export-with-toc
23176 org-export-preserve-breaks
23177 org-export-html-expand
23178 org-export-with-fixed-width
23179 org-export-with-tables
23180 org-export-with-sub-superscripts
23181 org-export-with-footnotes
23182 org-export-with-emphasize
23183 org-export-with-TeX-macros
23184 org-export-with-LaTeX-fragments
23185 org-export-skip-text-before-1st-heading
23186 org-export-with-drawers
23187 org-export-with-tags
23188 (file-name-nondirectory buffer-file-name)
23189 "TODO FEEDBACK VERIFY DONE"
23190 "Me Jason Marie DONE"
23191 org-highest-priority org-lowest-priority org-default-priority
23192 (mapconcat 'identity org-drawers " ")
23193 (cdr (assoc org-startup-folded
23194 '((nil . "showall") (t . "overview") (content . "content"))))
23195 (if org-odd-levels-only "odd" "oddeven")
23196 (if org-hide-leading-stars "hidestars" "showstars")
23197 (if org-startup-align-all-tables "align" "noalign")
23198 (cond ((eq t org-log-done) "logdone")
23199 ((not org-log-done) "nologging")
23200 ((listp org-log-done)
23201 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23202 org-log-done " ")))
23203 (or (mapconcat (lambda (x)
23204 (cond
23205 ((equal '(:startgroup) x) "{")
23206 ((equal '(:endgroup) x) "}")
23207 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23208 (t (car x))))
23209 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23210 org-archive-location
23211 "org file:~/org/%s.org"
23214 (defun org-insert-export-options-template ()
23215 "Insert into the buffer a template with information for exporting."
23216 (interactive)
23217 (if (not (bolp)) (newline))
23218 (let ((s (org-get-current-options)))
23219 (and (string-match "#\\+CATEGORY" s)
23220 (setq s (substring s 0 (match-beginning 0))))
23221 (insert s)))
23223 (defun org-toggle-fixed-width-section (arg)
23224 "Toggle the fixed-width export.
23225 If there is no active region, the QUOTE keyword at the current headline is
23226 inserted or removed. When present, it causes the text between this headline
23227 and the next to be exported as fixed-width text, and unmodified.
23228 If there is an active region, this command adds or removes a colon as the
23229 first character of this line. If the first character of a line is a colon,
23230 this line is also exported in fixed-width font."
23231 (interactive "P")
23232 (let* ((cc 0)
23233 (regionp (org-region-active-p))
23234 (beg (if regionp (region-beginning) (point)))
23235 (end (if regionp (region-end)))
23236 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
23237 (re "[ \t]*\\(:\\)")
23238 off)
23239 (if regionp
23240 (save-excursion
23241 (goto-char beg)
23242 (setq cc (current-column))
23243 (beginning-of-line 1)
23244 (setq off (looking-at re))
23245 (while (> nlines 0)
23246 (setq nlines (1- nlines))
23247 (beginning-of-line 1)
23248 (cond
23249 (arg
23250 (move-to-column cc t)
23251 (insert ":\n")
23252 (forward-line -1))
23253 ((and off (looking-at re))
23254 (replace-match "" t t nil 1))
23255 ((not off) (move-to-column cc t) (insert ":")))
23256 (forward-line 1)))
23257 (save-excursion
23258 (org-back-to-heading)
23259 (if (looking-at (concat outline-regexp
23260 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
23261 (replace-match "" t t nil 1)
23262 (if (looking-at outline-regexp)
23263 (progn
23264 (goto-char (match-end 0))
23265 (insert org-quote-string " "))))))))
23267 (defun org-export-as-html-and-open (arg)
23268 "Export the outline as HTML and immediately open it with a browser.
23269 If there is an active region, export only the region.
23270 The prefix ARG specifies how many levels of the outline should become
23271 headlines. The default is 3. Lower levels will become bulleted lists."
23272 (interactive "P")
23273 (org-export-as-html arg 'hidden)
23274 (org-open-file buffer-file-name))
23276 (defun org-export-as-html-batch ()
23277 "Call `org-export-as-html', may be used in batch processing as
23278 emacs --batch
23279 --load=$HOME/lib/emacs/org.el
23280 --eval \"(setq org-export-headline-levels 2)\"
23281 --visit=MyFile --funcall org-export-as-html-batch"
23282 (org-export-as-html org-export-headline-levels 'hidden))
23284 (defun org-export-as-html-to-buffer (arg)
23285 "Call `org-exort-as-html` with output to a temporary buffer.
23286 No file is created. The prefix ARG is passed through to `org-export-as-html'."
23287 (interactive "P")
23288 (org-export-as-html arg nil nil "*Org HTML Export*")
23289 (switch-to-buffer-other-window "*Org HTML Export*"))
23291 (defun org-replace-region-by-html (beg end)
23292 "Assume the current region has org-mode syntax, and convert it to HTML.
23293 This can be used in any buffer. For example, you could write an
23294 itemized list in org-mode syntax in an HTML buffer and then use this
23295 command to convert it."
23296 (interactive "r")
23297 (let (reg html buf pop-up-frames)
23298 (save-window-excursion
23299 (if (org-mode-p)
23300 (setq html (org-export-region-as-html
23301 beg end t 'string))
23302 (setq reg (buffer-substring beg end)
23303 buf (get-buffer-create "*Org tmp*"))
23304 (with-current-buffer buf
23305 (erase-buffer)
23306 (insert reg)
23307 (org-mode)
23308 (setq html (org-export-region-as-html
23309 (point-min) (point-max) t 'string)))
23310 (kill-buffer buf)))
23311 (delete-region beg end)
23312 (insert html)))
23314 (defun org-export-region-as-html (beg end &optional body-only buffer)
23315 "Convert region from BEG to END in org-mode buffer to HTML.
23316 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
23317 contents, and only produce the region of converted text, useful for
23318 cut-and-paste operations.
23319 If BUFFER is a buffer or a string, use/create that buffer as a target
23320 of the converted HTML. If BUFFER is the symbol `string', return the
23321 produced HTML as a string and leave not buffer behind. For example,
23322 a Lisp program could call this function in the following way:
23324 (setq html (org-export-region-as-html beg end t 'string))
23326 When called interactively, the output buffer is selected, and shown
23327 in a window. A non-interactive call will only retunr the buffer."
23328 (interactive "r\nP")
23329 (when (interactive-p)
23330 (setq buffer "*Org HTML Export*"))
23331 (let ((transient-mark-mode t) (zmacs-regions t)
23332 rtn)
23333 (goto-char end)
23334 (set-mark (point)) ;; to activate the region
23335 (goto-char beg)
23336 (setq rtn (org-export-as-html
23337 nil nil nil
23338 buffer body-only))
23339 (if (fboundp 'deactivate-mark) (deactivate-mark))
23340 (if (and (interactive-p) (bufferp rtn))
23341 (switch-to-buffer-other-window rtn)
23342 rtn)))
23344 (defun org-export-as-html (arg &optional hidden ext-plist
23345 to-buffer body-only)
23346 "Export the outline as a pretty HTML file.
23347 If there is an active region, export only the region. The prefix
23348 ARG specifies how many levels of the outline should become
23349 headlines. The default is 3. Lower levels will become bulleted
23350 lists. When HIDDEN is non-nil, don't display the HTML buffer.
23351 EXT-PLIST is a property list with external parameters overriding
23352 org-mode's default settings, but still inferior to file-local
23353 settings. When TO-BUFFER is non-nil, create a buffer with that
23354 name and export to that buffer. If TO-BUFFER is the symbol `string',
23355 don't leave any buffer behind but just return the resulting HTML as
23356 a string. When BODY-ONLY is set, don't produce the file header and footer,
23357 simply return the content of <body>...</body>, without even
23358 the body tags themselves."
23359 (interactive "P")
23361 ;; Make sure we have a file name when we need it.
23362 (when (and (not (or to-buffer body-only))
23363 (not buffer-file-name))
23364 (if (buffer-base-buffer)
23365 (org-set-local 'buffer-file-name
23366 (with-current-buffer (buffer-base-buffer)
23367 buffer-file-name))
23368 (error "Need a file name to be able to export.")))
23370 (message "Exporting...")
23371 (setq-default org-todo-line-regexp org-todo-line-regexp)
23372 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
23373 (setq-default org-done-keywords org-done-keywords)
23374 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
23375 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23376 ext-plist
23377 (org-infile-export-plist)))
23379 (style (plist-get opt-plist :style))
23380 (link-validate (plist-get opt-plist :link-validation-function))
23381 valid thetoc have-headings first-heading-pos
23382 (odd org-odd-levels-only)
23383 (region-p (org-region-active-p))
23384 (subtree-p
23385 (when region-p
23386 (save-excursion
23387 (goto-char (region-beginning))
23388 (and (org-at-heading-p)
23389 (>= (org-end-of-subtree t t) (region-end))))))
23390 ;; The following two are dynamically scoped into other
23391 ;; routines below.
23392 (org-current-export-dir (org-export-directory :html opt-plist))
23393 (org-current-export-file buffer-file-name)
23394 (level 0) (line "") (origline "") txt todo
23395 (umax nil)
23396 (umax-toc nil)
23397 (filename (if to-buffer nil
23398 (concat (file-name-as-directory
23399 (org-export-directory :html opt-plist))
23400 (file-name-sans-extension
23401 (or (and subtree-p
23402 (org-entry-get (region-beginning)
23403 "EXPORT_FILE_NAME" t))
23404 (file-name-nondirectory buffer-file-name)))
23405 "." org-export-html-extension)))
23406 (current-dir (if buffer-file-name
23407 (file-name-directory buffer-file-name)
23408 default-directory))
23409 (buffer (if to-buffer
23410 (cond
23411 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
23412 (t (get-buffer-create to-buffer)))
23413 (find-file-noselect filename)))
23414 (org-levels-open (make-vector org-level-max nil))
23415 (date (plist-get opt-plist :date))
23416 (author (plist-get opt-plist :author))
23417 (title (or (and subtree-p (org-export-get-title-from-subtree))
23418 (plist-get opt-plist :title)
23419 (and (not
23420 (plist-get opt-plist :skip-before-1st-heading))
23421 (org-export-grab-title-from-buffer))
23422 (and buffer-file-name
23423 (file-name-sans-extension
23424 (file-name-nondirectory buffer-file-name)))
23425 "UNTITLED"))
23426 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23427 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
23428 (inquote nil)
23429 (infixed nil)
23430 (in-local-list nil)
23431 (local-list-num nil)
23432 (local-list-indent nil)
23433 (llt org-plain-list-ordered-item-terminator)
23434 (email (plist-get opt-plist :email))
23435 (language (plist-get opt-plist :language))
23436 (lang-words nil)
23437 (target-alist nil) tg
23438 (head-count 0) cnt
23439 (start 0)
23440 (coding-system (and (boundp 'buffer-file-coding-system)
23441 buffer-file-coding-system))
23442 (coding-system-for-write (or org-export-html-coding-system
23443 coding-system))
23444 (save-buffer-coding-system (or org-export-html-coding-system
23445 coding-system))
23446 (charset (and coding-system-for-write
23447 (fboundp 'coding-system-get)
23448 (coding-system-get coding-system-for-write
23449 'mime-charset)))
23450 (region
23451 (buffer-substring
23452 (if region-p (region-beginning) (point-min))
23453 (if region-p (region-end) (point-max))))
23454 (lines
23455 (org-split-string
23456 (org-cleaned-string-for-export
23457 region
23458 :emph-multiline t
23459 :for-html t
23460 :skip-before-1st-heading
23461 (plist-get opt-plist :skip-before-1st-heading)
23462 :archived-trees
23463 (plist-get opt-plist :archived-trees)
23464 :add-text
23465 (plist-get opt-plist :text)
23466 :LaTeX-fragments
23467 (plist-get opt-plist :LaTeX-fragments))
23468 "[\r\n]"))
23469 table-open type
23470 table-buffer table-orig-buffer
23471 ind start-is-num starter didclose
23472 rpl path desc descp desc1 desc2 link
23475 (let ((inhibit-read-only t))
23476 (org-unmodified
23477 (remove-text-properties (point-min) (point-max)
23478 '(:org-license-to-kill t))))
23480 (message "Exporting...")
23482 (setq org-min-level (org-get-min-level lines))
23483 (setq org-last-level org-min-level)
23484 (org-init-section-numbers)
23486 (cond
23487 ((and date (string-match "%" date))
23488 (setq date (format-time-string date (current-time))))
23489 (date)
23490 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23492 ;; Get the language-dependent settings
23493 (setq lang-words (or (assoc language org-export-language-setup)
23494 (assoc "en" org-export-language-setup)))
23496 ;; Switch to the output buffer
23497 (set-buffer buffer)
23498 (erase-buffer)
23499 (fundamental-mode)
23501 (and (fboundp 'set-buffer-file-coding-system)
23502 (set-buffer-file-coding-system coding-system-for-write))
23504 (let ((case-fold-search nil)
23505 (org-odd-levels-only odd))
23506 ;; create local variables for all options, to make sure all called
23507 ;; functions get the correct information
23508 (mapc (lambda (x)
23509 (set (make-local-variable (cdr x))
23510 (plist-get opt-plist (car x))))
23511 org-export-plist-vars)
23512 (setq umax (if arg (prefix-numeric-value arg)
23513 org-export-headline-levels))
23514 (setq umax-toc (if (integerp org-export-with-toc)
23515 (min org-export-with-toc umax)
23516 umax))
23517 (unless body-only
23518 ;; File header
23519 (insert (format
23520 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
23521 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
23522 <html xmlns=\"http://www.w3.org/1999/xhtml\"
23523 lang=\"%s\" xml:lang=\"%s\">
23524 <head>
23525 <title>%s</title>
23526 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
23527 <meta name=\"generator\" content=\"Org-mode\"/>
23528 <meta name=\"generated\" content=\"%s\"/>
23529 <meta name=\"author\" content=\"%s\"/>
23531 </head><body>
23533 language language (org-html-expand title)
23534 (or charset "iso-8859-1") date author style))
23536 (insert (or (plist-get opt-plist :preamble) ""))
23538 (when (plist-get opt-plist :auto-preamble)
23539 (if title (insert (format org-export-html-title-format
23540 (org-html-expand title))))))
23542 (if (and org-export-with-toc (not body-only))
23543 (progn
23544 (push (format "<h%d>%s</h%d>\n"
23545 org-export-html-toplevel-hlevel
23546 (nth 3 lang-words)
23547 org-export-html-toplevel-hlevel)
23548 thetoc)
23549 (push "<ul>\n<li>" thetoc)
23550 (setq lines
23551 (mapcar '(lambda (line)
23552 (if (string-match org-todo-line-regexp line)
23553 ;; This is a headline
23554 (progn
23555 (setq have-headings t)
23556 (setq level (- (match-end 1) (match-beginning 1))
23557 level (org-tr-level level)
23558 txt (save-match-data
23559 (org-html-expand
23560 (org-export-cleanup-toc-line
23561 (match-string 3 line))))
23562 todo
23563 (or (and org-export-mark-todo-in-toc
23564 (match-beginning 2)
23565 (not (member (match-string 2 line)
23566 org-done-keywords)))
23567 ; TODO, not DONE
23568 (and org-export-mark-todo-in-toc
23569 (= level umax-toc)
23570 (org-search-todo-below
23571 line lines level))))
23572 (if (string-match
23573 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
23574 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
23575 (if (string-match quote-re0 txt)
23576 (setq txt (replace-match "" t t txt)))
23577 (if org-export-with-section-numbers
23578 (setq txt (concat (org-section-number level)
23579 " " txt)))
23580 (if (<= level (max umax umax-toc))
23581 (setq head-count (+ head-count 1)))
23582 (if (<= level umax-toc)
23583 (progn
23584 (if (> level org-last-level)
23585 (progn
23586 (setq cnt (- level org-last-level))
23587 (while (>= (setq cnt (1- cnt)) 0)
23588 (push "\n<ul>\n<li>" thetoc))
23589 (push "\n" thetoc)))
23590 (if (< level org-last-level)
23591 (progn
23592 (setq cnt (- org-last-level level))
23593 (while (>= (setq cnt (1- cnt)) 0)
23594 (push "</li>\n</ul>" thetoc))
23595 (push "\n" thetoc)))
23596 ;; Check for targets
23597 (while (string-match org-target-regexp line)
23598 (setq tg (match-string 1 line)
23599 line (replace-match
23600 (concat "@<span class=\"target\">" tg "@</span> ")
23601 t t line))
23602 (push (cons (org-solidify-link-text tg)
23603 (format "sec-%d" head-count))
23604 target-alist))
23605 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
23606 (setq txt (replace-match "" t t txt)))
23607 (push
23608 (format
23609 (if todo
23610 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
23611 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
23612 head-count txt) thetoc)
23614 (setq org-last-level level))
23616 line)
23617 lines))
23618 (while (> org-last-level (1- org-min-level))
23619 (setq org-last-level (1- org-last-level))
23620 (push "</li>\n</ul>\n" thetoc))
23621 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23623 (setq head-count 0)
23624 (org-init-section-numbers)
23626 (while (setq line (pop lines) origline line)
23627 (catch 'nextline
23629 ;; end of quote section?
23630 (when (and inquote (string-match "^\\*+ " line))
23631 (insert "</pre>\n")
23632 (setq inquote nil))
23633 ;; inside a quote section?
23634 (when inquote
23635 (insert (org-html-protect line) "\n")
23636 (throw 'nextline nil))
23638 ;; verbatim lines
23639 (when (and org-export-with-fixed-width
23640 (string-match "^[ \t]*:\\(.*\\)" line))
23641 (when (not infixed)
23642 (setq infixed t)
23643 (insert "<pre>\n"))
23644 (insert (org-html-protect (match-string 1 line)) "\n")
23645 (when (and lines
23646 (not (string-match "^[ \t]*\\(:.*\\)"
23647 (car lines))))
23648 (setq infixed nil)
23649 (insert "</pre>\n"))
23650 (throw 'nextline nil))
23652 ;; Protected HTML
23653 (when (get-text-property 0 'org-protected line)
23654 (let (par)
23655 (when (re-search-backward
23656 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
23657 (setq par (match-string 1))
23658 (replace-match "\\2\n"))
23659 (insert line "\n")
23660 (while (and lines
23661 (get-text-property 0 'org-protected (car lines)))
23662 (insert (pop lines) "\n"))
23663 (and par (insert "<p>\n")))
23664 (throw 'nextline nil))
23666 ;; Horizontal line
23667 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
23668 (insert "\n<hr/>\n")
23669 (throw 'nextline nil))
23671 ;; make targets to anchors
23672 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
23673 (cond
23674 ((match-end 2)
23675 (setq line (replace-match
23676 (concat "@<a name=\""
23677 (org-solidify-link-text (match-string 1 line))
23678 "\">\\nbsp@</a>")
23679 t t line)))
23680 ((and org-export-with-toc (equal (string-to-char line) ?*))
23681 (setq line (replace-match
23682 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
23683 ; (concat "@<i>" (match-string 1 line) "@</i> ")
23684 t t line)))
23686 (setq line (replace-match
23687 (concat "@<a name=\""
23688 (org-solidify-link-text (match-string 1 line))
23689 "\" class=\"target\">" (match-string 1 line) "@</a> ")
23690 t t line)))))
23692 (setq line (org-html-handle-time-stamps line))
23694 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
23695 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
23696 ;; Also handle sub_superscripts and checkboxes
23697 (setq line (org-html-expand line))
23699 ;; Format the links
23700 (setq start 0)
23701 (while (string-match org-bracket-link-analytic-regexp line start)
23702 (setq start (match-beginning 0))
23703 (setq type (if (match-end 2) (match-string 2 line) "internal"))
23704 (setq path (match-string 3 line))
23705 (setq desc1 (if (match-end 5) (match-string 5 line))
23706 desc2 (if (match-end 2) (concat type ":" path) path)
23707 descp (and desc1 (not (equal desc1 desc2)))
23708 desc (or desc1 desc2))
23709 ;; Make an image out of the description if that is so wanted
23710 (when (and descp (org-file-image-p desc))
23711 (save-match-data
23712 (if (string-match "^file:" desc)
23713 (setq desc (substring desc (match-end 0)))))
23714 (setq desc (concat "<img src=\"" desc "\"/>")))
23715 ;; FIXME: do we need to unescape here somewhere?
23716 (cond
23717 ((equal type "internal")
23718 (setq rpl
23719 (concat
23720 "<a href=\"#"
23721 (org-solidify-link-text
23722 (save-match-data (org-link-unescape path)) target-alist)
23723 "\">" desc "</a>")))
23724 ((member type '("http" "https"))
23725 ;; standard URL, just check if we need to inline an image
23726 (if (and (or (eq t org-export-html-inline-images)
23727 (and org-export-html-inline-images (not descp)))
23728 (org-file-image-p path))
23729 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
23730 (setq link (concat type ":" path))
23731 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
23732 ((member type '("ftp" "mailto" "news"))
23733 ;; standard URL
23734 (setq link (concat type ":" path))
23735 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
23736 ((string= type "file")
23737 ;; FILE link
23738 (let* ((filename path)
23739 (abs-p (file-name-absolute-p filename))
23740 thefile file-is-image-p search)
23741 (save-match-data
23742 (if (string-match "::\\(.*\\)" filename)
23743 (setq search (match-string 1 filename)
23744 filename (replace-match "" t nil filename)))
23745 (setq valid
23746 (if (functionp link-validate)
23747 (funcall link-validate filename current-dir)
23749 (setq file-is-image-p (org-file-image-p filename))
23750 (setq thefile (if abs-p (expand-file-name filename) filename))
23751 (when (and org-export-html-link-org-files-as-html
23752 (string-match "\\.org$" thefile))
23753 (setq thefile (concat (substring thefile 0
23754 (match-beginning 0))
23755 "." org-export-html-extension))
23756 (if (and search
23757 ;; make sure this is can be used as target search
23758 (not (string-match "^[0-9]*$" search))
23759 (not (string-match "^\\*" search))
23760 (not (string-match "^/.*/$" search)))
23761 (setq thefile (concat thefile "#"
23762 (org-solidify-link-text
23763 (org-link-unescape search)))))
23764 (when (string-match "^file:" desc)
23765 (setq desc (replace-match "" t t desc))
23766 (if (string-match "\\.org$" desc)
23767 (setq desc (replace-match "" t t desc))))))
23768 (setq rpl (if (and file-is-image-p
23769 (or (eq t org-export-html-inline-images)
23770 (and org-export-html-inline-images
23771 (not descp))))
23772 (concat "<img src=\"" thefile "\"/>")
23773 (concat "<a href=\"" thefile "\">" desc "</a>")))
23774 (if (not valid) (setq rpl desc))))
23775 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
23776 (setq rpl (concat "<i>&lt;" type ":"
23777 (save-match-data (org-link-unescape path))
23778 "&gt;</i>"))))
23779 (setq line (replace-match rpl t t line)
23780 start (+ start (length rpl))))
23782 ;; TODO items
23783 (if (and (string-match org-todo-line-regexp line)
23784 (match-beginning 2))
23786 (setq line
23787 (concat (substring line 0 (match-beginning 2))
23788 "<span class=\""
23789 (if (member (match-string 2 line)
23790 org-done-keywords)
23791 "done" "todo")
23792 "\">" (match-string 2 line)
23793 "</span>" (substring line (match-end 2)))))
23795 ;; Does this contain a reference to a footnote?
23796 (when org-export-with-footnotes
23797 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line)
23798 (let ((n (match-string 2 line)))
23799 (setq line
23800 (replace-match
23801 (format
23802 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
23803 (match-string 1 line) n n n)
23804 t t line)))))
23806 (cond
23807 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23808 ;; This is a headline
23809 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23810 txt (match-string 2 line))
23811 (if (string-match quote-re0 txt)
23812 (setq txt (replace-match "" t t txt)))
23813 (if (<= level (max umax umax-toc))
23814 (setq head-count (+ head-count 1)))
23815 (when in-local-list
23816 ;; Close any local lists before inserting a new header line
23817 (while local-list-num
23818 (org-close-li)
23819 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23820 (pop local-list-num))
23821 (setq local-list-indent nil
23822 in-local-list nil))
23823 (setq first-heading-pos (or first-heading-pos (point)))
23824 (org-html-level-start level txt umax
23825 (and org-export-with-toc (<= level umax))
23826 head-count)
23827 ;; QUOTES
23828 (when (string-match quote-re line)
23829 (insert "<pre>")
23830 (setq inquote t)))
23832 ((and org-export-with-tables
23833 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23834 (if (not table-open)
23835 ;; New table starts
23836 (setq table-open t table-buffer nil table-orig-buffer nil))
23837 ;; Accumulate lines
23838 (setq table-buffer (cons line table-buffer)
23839 table-orig-buffer (cons origline table-orig-buffer))
23840 (when (or (not lines)
23841 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23842 (car lines))))
23843 (setq table-open nil
23844 table-buffer (nreverse table-buffer)
23845 table-orig-buffer (nreverse table-orig-buffer))
23846 (org-close-par-maybe)
23847 (insert (org-format-table-html table-buffer table-orig-buffer))))
23849 ;; Normal lines
23850 (when (string-match
23851 (cond
23852 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23853 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23854 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
23855 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
23856 line)
23857 (setq ind (org-get-string-indentation line)
23858 start-is-num (match-beginning 4)
23859 starter (if (match-beginning 2)
23860 (substring (match-string 2 line) 0 -1))
23861 line (substring line (match-beginning 5)))
23862 (unless (string-match "[^ \t]" line)
23863 ;; empty line. Pretend indentation is large.
23864 (setq ind (if org-empty-line-terminates-plain-lists
23866 (1+ (or (car local-list-indent) 1)))))
23867 (setq didclose nil)
23868 (while (and in-local-list
23869 (or (and (= ind (car local-list-indent))
23870 (not starter))
23871 (< ind (car local-list-indent))))
23872 (setq didclose t)
23873 (org-close-li)
23874 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
23875 (pop local-list-num) (pop local-list-indent)
23876 (setq in-local-list local-list-indent))
23877 (cond
23878 ((and starter
23879 (or (not in-local-list)
23880 (> ind (car local-list-indent))))
23881 ;; Start new (level of) list
23882 (org-close-par-maybe)
23883 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
23884 (push start-is-num local-list-num)
23885 (push ind local-list-indent)
23886 (setq in-local-list t))
23887 (starter
23888 ;; continue current list
23889 (org-close-li)
23890 (insert "<li>\n"))
23891 (didclose
23892 ;; we did close a list, normal text follows: need <p>
23893 (org-open-par)))
23894 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
23895 (setq line
23896 (replace-match
23897 (if (equal (match-string 1 line) "X")
23898 "<b>[X]</b>"
23899 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
23900 t t line))))
23902 ;; Empty lines start a new paragraph. If hand-formatted lists
23903 ;; are not fully interpreted, lines starting with "-", "+", "*"
23904 ;; also start a new paragraph.
23905 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
23907 ;; Is this the start of a footnote?
23908 (when org-export-with-footnotes
23909 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
23910 (org-close-par-maybe)
23911 (let ((n (match-string 1 line)))
23912 (setq line (replace-match
23913 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
23915 ;; Check if the line break needs to be conserved
23916 (cond
23917 ((string-match "\\\\\\\\[ \t]*$" line)
23918 (setq line (replace-match "<br/>" t t line)))
23919 (org-export-preserve-breaks
23920 (setq line (concat line "<br/>"))))
23922 (insert line "\n")))))
23924 ;; Properly close all local lists and other lists
23925 (when inquote (insert "</pre>\n"))
23926 (when in-local-list
23927 ;; Close any local lists before inserting a new header line
23928 (while local-list-num
23929 (org-close-li)
23930 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
23931 (pop local-list-num))
23932 (setq local-list-indent nil
23933 in-local-list nil))
23934 (org-html-level-start 1 nil umax
23935 (and org-export-with-toc (<= level umax))
23936 head-count)
23938 (unless body-only
23939 (when (plist-get opt-plist :auto-postamble)
23940 (insert "<div id=\"postamble\">")
23941 (when (and org-export-author-info author)
23942 (insert "<p class=\"author\"> "
23943 (nth 1 lang-words) ": " author "\n")
23944 (when email
23945 (insert "<a href=\"mailto:" email "\">&lt;"
23946 email "&gt;</a>\n"))
23947 (insert "</p>\n"))
23948 (when (and date org-export-time-stamp-file)
23949 (insert "<p class=\"date\"> "
23950 (nth 2 lang-words) ": "
23951 date "</p>\n"))
23952 (insert "</div>"))
23954 (if org-export-html-with-timestamp
23955 (insert org-export-html-html-helper-timestamp))
23956 (insert (or (plist-get opt-plist :postamble) ""))
23957 (insert "</body>\n</html>\n"))
23959 (normal-mode)
23960 (if (eq major-mode default-major-mode) (html-mode))
23962 ;; insert the table of contents
23963 (goto-char (point-min))
23964 (when thetoc
23965 (if (or (re-search-forward
23966 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
23967 (re-search-forward
23968 "\\[TABLE-OF-CONTENTS\\]" nil t))
23969 (progn
23970 (goto-char (match-beginning 0))
23971 (replace-match ""))
23972 (goto-char first-heading-pos)
23973 (when (looking-at "\\s-*</p>")
23974 (goto-char (match-end 0))
23975 (insert "\n")))
23976 (insert "<div id=\"table-of-contents\">\n")
23977 (mapc 'insert thetoc)
23978 (insert "</div>\n"))
23979 ;; remove empty paragraphs and lists
23980 (goto-char (point-min))
23981 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
23982 (replace-match ""))
23983 (goto-char (point-min))
23984 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
23985 (replace-match ""))
23986 ;; Convert whitespace place holders
23987 (goto-char (point-min))
23988 (let (beg end n)
23989 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23990 (setq n (get-text-property beg 'org-whitespace)
23991 end (next-single-property-change beg 'org-whitespace))
23992 (goto-char beg)
23993 (delete-region beg end)
23994 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
23995 (make-string n ?x)))))
23997 (or to-buffer (save-buffer))
23998 (goto-char (point-min))
23999 (message "Exporting... done")
24000 (if (eq to-buffer 'string)
24001 (prog1 (buffer-substring (point-min) (point-max))
24002 (kill-buffer (current-buffer)))
24003 (current-buffer)))))
24005 (defvar org-table-colgroup-info nil)
24006 (defun org-format-table-ascii (lines)
24007 "Format a table for ascii export."
24008 (if (stringp lines)
24009 (setq lines (org-split-string lines "\n")))
24010 (if (not (string-match "^[ \t]*|" (car lines)))
24011 ;; Table made by table.el - test for spanning
24012 lines
24014 ;; A normal org table
24015 ;; Get rid of hlines at beginning and end
24016 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24017 (setq lines (nreverse lines))
24018 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24019 (setq lines (nreverse lines))
24020 (when org-export-table-remove-special-lines
24021 ;; Check if the table has a marking column. If yes remove the
24022 ;; column and the special lines
24023 (setq lines (org-table-clean-before-export lines)))
24024 ;; Get rid of the vertical lines except for grouping
24025 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24026 rtn line vl1 start)
24027 (while (setq line (pop lines))
24028 (if (string-match org-table-hline-regexp line)
24029 (and (string-match "|\\(.*\\)|" line)
24030 (setq line (replace-match " \\1" t nil line)))
24031 (setq start 0 vl1 vl)
24032 (while (string-match "|" line start)
24033 (setq start (match-end 0))
24034 (or (pop vl1) (setq line (replace-match " " t t line)))))
24035 (push line rtn))
24036 (nreverse rtn))))
24038 (defun org-colgroup-info-to-vline-list (info)
24039 (let (vl new last)
24040 (while info
24041 (setq last new new (pop info))
24042 (if (or (memq last '(:end :startend))
24043 (memq new '(:start :startend)))
24044 (push t vl)
24045 (push nil vl)))
24046 (setq vl (nreverse vl))
24047 (and vl (setcar vl nil))
24048 vl))
24050 (defun org-format-table-html (lines olines)
24051 "Find out which HTML converter to use and return the HTML code."
24052 (if (stringp lines)
24053 (setq lines (org-split-string lines "\n")))
24054 (if (string-match "^[ \t]*|" (car lines))
24055 ;; A normal org table
24056 (org-format-org-table-html lines)
24057 ;; Table made by table.el - test for spanning
24058 (let* ((hlines (delq nil (mapcar
24059 (lambda (x)
24060 (if (string-match "^[ \t]*\\+-" x) x
24061 nil))
24062 lines)))
24063 (first (car hlines))
24064 (ll (and (string-match "\\S-+" first)
24065 (match-string 0 first)))
24066 (re (concat "^[ \t]*" (regexp-quote ll)))
24067 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24068 hlines))))
24069 (if (and (not spanning)
24070 (not org-export-prefer-native-exporter-for-tables))
24071 ;; We can use my own converter with HTML conversions
24072 (org-format-table-table-html lines)
24073 ;; Need to use the code generator in table.el, with the original text.
24074 (org-format-table-table-html-using-table-generate-source olines)))))
24076 (defun org-format-org-table-html (lines &optional splice)
24077 "Format a table into HTML."
24078 ;; Get rid of hlines at beginning and end
24079 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24080 (setq lines (nreverse lines))
24081 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24082 (setq lines (nreverse lines))
24083 (when org-export-table-remove-special-lines
24084 ;; Check if the table has a marking column. If yes remove the
24085 ;; column and the special lines
24086 (setq lines (org-table-clean-before-export lines)))
24088 (let ((head (and org-export-highlight-first-table-line
24089 (delq nil (mapcar
24090 (lambda (x) (string-match "^[ \t]*|-" x))
24091 (cdr lines)))))
24092 (nlines 0) fnum i
24093 tbopen line fields html gr colgropen)
24094 (if splice (setq head nil))
24095 (unless splice (push (if head "<thead>" "<tbody>") html))
24096 (setq tbopen t)
24097 (while (setq line (pop lines))
24098 (catch 'next-line
24099 (if (string-match "^[ \t]*|-" line)
24100 (progn
24101 (unless splice
24102 (push (if head "</thead>" "</tbody>") html)
24103 (if lines (push "<tbody>" html) (setq tbopen nil)))
24104 (setq head nil) ;; head ends here, first time around
24105 ;; ignore this line
24106 (throw 'next-line t)))
24107 ;; Break the line into fields
24108 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24109 (unless fnum (setq fnum (make-vector (length fields) 0)))
24110 (setq nlines (1+ nlines) i -1)
24111 (push (concat "<tr>"
24112 (mapconcat
24113 (lambda (x)
24114 (setq i (1+ i))
24115 (if (and (< i nlines)
24116 (string-match org-table-number-regexp x))
24117 (incf (aref fnum i)))
24118 (if head
24119 (concat (car org-export-table-header-tags) x
24120 (cdr org-export-table-header-tags))
24121 (concat (car org-export-table-data-tags) x
24122 (cdr org-export-table-data-tags))))
24123 fields "")
24124 "</tr>")
24125 html)))
24126 (unless splice (if tbopen (push "</tbody>" html)))
24127 (unless splice (push "</table>\n" html))
24128 (setq html (nreverse html))
24129 (unless splice
24130 ;; Put in COL tags with the alignment (unfortuntely often ignored...)
24131 (push (mapconcat
24132 (lambda (x)
24133 (setq gr (pop org-table-colgroup-info))
24134 (format "%s<COL align=\"%s\"></COL>%s"
24135 (if (memq gr '(:start :startend))
24136 (prog1
24137 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24138 (setq colgropen t))
24140 (if (> (/ (float x) nlines) org-table-number-fraction)
24141 "right" "left")
24142 (if (memq gr '(:end :startend))
24143 (progn (setq colgropen nil) "</colgroup>")
24144 "")))
24145 fnum "")
24146 html)
24147 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24148 (push org-export-html-table-tag html))
24149 (concat (mapconcat 'identity html "\n") "\n")))
24151 (defun org-table-clean-before-export (lines)
24152 "Check if the table has a marking column.
24153 If yes remove the column and the special lines."
24154 (setq org-table-colgroup-info nil)
24155 (if (memq nil
24156 (mapcar
24157 (lambda (x) (or (string-match "^[ \t]*|-" x)
24158 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24159 lines))
24160 (progn
24161 (setq org-table-clean-did-remove-column nil)
24162 (delq nil
24163 (mapcar
24164 (lambda (x)
24165 (cond
24166 ((string-match "^[ \t]*| */ *|" x)
24167 (setq org-table-colgroup-info
24168 (mapcar (lambda (x)
24169 (cond ((member x '("<" "&lt;")) :start)
24170 ((member x '(">" "&gt;")) :end)
24171 ((member x '("<>" "&lt;&gt;")) :startend)
24172 (t nil)))
24173 (org-split-string x "[ \t]*|[ \t]*")))
24174 nil)
24175 (t x)))
24176 lines)))
24177 (setq org-table-clean-did-remove-column t)
24178 (delq nil
24179 (mapcar
24180 (lambda (x)
24181 (cond
24182 ((string-match "^[ \t]*| */ *|" x)
24183 (setq org-table-colgroup-info
24184 (mapcar (lambda (x)
24185 (cond ((member x '("<" "&lt;")) :start)
24186 ((member x '(">" "&gt;")) :end)
24187 ((member x '("<>" "&lt;&gt;")) :startend)
24188 (t nil)))
24189 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24190 nil)
24191 ((string-match "^[ \t]*| *[!_^/] *|" x)
24192 nil) ; ignore this line
24193 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24194 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24195 ;; remove the first column
24196 (replace-match "\\1|" t nil x))
24197 (t (error "This should not happen"))))
24198 lines))))
24200 (defun org-format-table-table-html (lines)
24201 "Format a table generated by table.el into HTML.
24202 This conversion does *not* use `table-generate-source' from table.el.
24203 This has the advantage that Org-mode's HTML conversions can be used.
24204 But it has the disadvantage, that no cell- or row-spanning is allowed."
24205 (let (line field-buffer
24206 (head org-export-highlight-first-table-line)
24207 fields html empty)
24208 (setq html (concat org-export-html-table-tag "\n"))
24209 (while (setq line (pop lines))
24210 (setq empty "&nbsp;")
24211 (catch 'next-line
24212 (if (string-match "^[ \t]*\\+-" line)
24213 (progn
24214 (if field-buffer
24215 (progn
24216 (setq
24217 html
24218 (concat
24219 html
24220 "<tr>"
24221 (mapconcat
24222 (lambda (x)
24223 (if (equal x "") (setq x empty))
24224 (if head
24225 (concat (car org-export-table-header-tags) x
24226 (cdr org-export-table-header-tags))
24227 (concat (car org-export-table-data-tags) x
24228 (cdr org-export-table-data-tags))))
24229 field-buffer "\n")
24230 "</tr>\n"))
24231 (setq head nil)
24232 (setq field-buffer nil)))
24233 ;; Ignore this line
24234 (throw 'next-line t)))
24235 ;; Break the line into fields and store the fields
24236 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24237 (if field-buffer
24238 (setq field-buffer (mapcar
24239 (lambda (x)
24240 (concat x "<br/>" (pop fields)))
24241 field-buffer))
24242 (setq field-buffer fields))))
24243 (setq html (concat html "</table>\n"))
24244 html))
24246 (defun org-format-table-table-html-using-table-generate-source (lines)
24247 "Format a table into html, using `table-generate-source' from table.el.
24248 This has the advantage that cell- or row-spanning is allowed.
24249 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
24250 (require 'table)
24251 (with-current-buffer (get-buffer-create " org-tmp1 ")
24252 (erase-buffer)
24253 (insert (mapconcat 'identity lines "\n"))
24254 (goto-char (point-min))
24255 (if (not (re-search-forward "|[^+]" nil t))
24256 (error "Error processing table"))
24257 (table-recognize-table)
24258 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
24259 (table-generate-source 'html " org-tmp2 ")
24260 (set-buffer " org-tmp2 ")
24261 (buffer-substring (point-min) (point-max))))
24263 (defun org-html-handle-time-stamps (s)
24264 "Format time stamps in string S, or remove them."
24265 (catch 'exit
24266 (let (r b)
24267 (while (string-match org-maybe-keyword-time-regexp s)
24268 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
24269 ;; never export CLOCK
24270 (throw 'exit ""))
24271 (or b (setq b (substring s 0 (match-beginning 0))))
24272 (if (not org-export-with-timestamps)
24273 (setq r (concat r (substring s 0 (match-beginning 0)))
24274 s (substring s (match-end 0)))
24275 (setq r (concat
24276 r (substring s 0 (match-beginning 0))
24277 (if (match-end 1)
24278 (format "@<span class=\"timestamp-kwd\">%s @</span>"
24279 (match-string 1 s)))
24280 (format " @<span class=\"timestamp\">%s@</span>"
24281 (substring
24282 (org-translate-time (match-string 3 s)) 1 -1)))
24283 s (substring s (match-end 0)))))
24284 ;; Line break if line started and ended with time stamp stuff
24285 (if (not r)
24287 (setq r (concat r s))
24288 (unless (string-match "\\S-" (concat b s))
24289 (setq r (concat r "@<br/>")))
24290 r))))
24292 (defun org-html-protect (s)
24293 ;; convert & to &amp;, < to &lt; and > to &gt;
24294 (let ((start 0))
24295 (while (string-match "&" s start)
24296 (setq s (replace-match "&amp;" t t s)
24297 start (1+ (match-beginning 0))))
24298 (while (string-match "<" s)
24299 (setq s (replace-match "&lt;" t t s)))
24300 (while (string-match ">" s)
24301 (setq s (replace-match "&gt;" t t s))))
24304 (defun org-export-cleanup-toc-line (s)
24305 "Remove tags and time staps from lines going into the toc."
24306 (when (memq org-export-with-tags '(not-in-toc nil))
24307 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
24308 (setq s (replace-match "" t t s))))
24309 (when org-export-remove-timestamps-from-toc
24310 (while (string-match org-maybe-keyword-time-regexp s)
24311 (setq s (replace-match "" t t s))))
24312 (while (string-match org-bracket-link-regexp s)
24313 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
24314 t t s)))
24317 (defun org-html-expand (string)
24318 "Prepare STRING for HTML export. Applies all active conversions.
24319 If there are links in the string, don't modify these."
24320 (let* ((re (concat org-bracket-link-regexp "\\|"
24321 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
24322 m s l res)
24323 (while (setq m (string-match re string))
24324 (setq s (substring string 0 m)
24325 l (match-string 0 string)
24326 string (substring string (match-end 0)))
24327 (push (org-html-do-expand s) res)
24328 (push l res))
24329 (push (org-html-do-expand string) res)
24330 (apply 'concat (nreverse res))))
24332 (defun org-html-do-expand (s)
24333 "Apply all active conversions to translate special ASCII to HTML."
24334 (setq s (org-html-protect s))
24335 (if org-export-html-expand
24336 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
24337 (setq s (replace-match "<\\1>" t nil s))))
24338 (if org-export-with-emphasize
24339 (setq s (org-export-html-convert-emphasize s)))
24340 (if org-export-with-sub-superscripts
24341 (setq s (org-export-html-convert-sub-super s)))
24342 (if org-export-with-TeX-macros
24343 (let ((start 0) wd ass)
24344 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
24345 (setq wd (match-string 1 s))
24346 (if (setq ass (assoc wd org-html-entities))
24347 (setq s (replace-match (or (cdr ass)
24348 (concat "&" (car ass) ";"))
24349 t t s))
24350 (setq start (+ start (length wd)))))))
24353 (defun org-create-multibrace-regexp (left right n)
24354 "Create a regular expression which will match a balanced sexp.
24355 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
24356 as single character strings.
24357 The regexp returned will match the entire expression including the
24358 delimiters. It will also define a single group which contains the
24359 match except for the outermost delimiters. The maximum depth of
24360 stacked delimiters is N. Escaping delimiters is not possible."
24361 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
24362 (or "\\|")
24363 (re nothing)
24364 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
24365 (while (> n 1)
24366 (setq n (1- n)
24367 re (concat re or next)
24368 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
24369 (concat left "\\(" re "\\)" right)))
24371 (defvar org-match-substring-regexp
24372 (concat
24373 "\\([^\\]\\)\\([_^]\\)\\("
24374 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24375 "\\|"
24376 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
24377 "\\|"
24378 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
24379 "The regular expression matching a sub- or superscript.")
24381 ;(let ((s "a\\_b"))
24382 ; (and (string-match org-match-substring-regexp s)
24383 ; (conca t (match-string 1 s) ":::" (match-string 2 s))))
24385 (defun org-export-html-convert-sub-super (string)
24386 "Convert sub- and superscripts in STRING to HTML."
24387 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
24388 (while (string-match org-match-substring-regexp string s)
24389 (if (and requireb (match-end 8))
24390 (setq s (match-end 2))
24391 (setq s (match-end 1)
24392 key (if (string= (match-string 2 string) "_") "sub" "sup")
24393 c (or (match-string 8 string)
24394 (match-string 6 string)
24395 (match-string 5 string))
24396 string (replace-match
24397 (concat (match-string 1 string)
24398 "<" key ">" c "</" key ">")
24399 t t string))))
24400 (while (string-match "\\\\\\([_^]\\)" string)
24401 (setq string (replace-match (match-string 1 string) t t string)))
24402 string))
24404 (defun org-export-html-convert-emphasize (string)
24405 "Apply emphasis."
24406 (let ((s 0))
24407 (while (string-match org-emph-re string s)
24408 (if (not (equal
24409 (substring string (match-beginning 3) (1+ (match-beginning 3)))
24410 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
24411 (setq string (replace-match
24412 (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
24413 "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist))
24414 "\\5") t nil string))
24415 (setq s (1+ s))))
24416 string))
24418 (defvar org-par-open nil)
24419 (defun org-open-par ()
24420 "Insert <p>, but first close previous paragraph if any."
24421 (org-close-par-maybe)
24422 (insert "\n<p>")
24423 (setq org-par-open t))
24424 (defun org-close-par-maybe ()
24425 "Close paragraph if there is one open."
24426 (when org-par-open
24427 (insert "</p>")
24428 (setq org-par-open nil)))
24429 (defun org-close-li ()
24430 "Close <li> if necessary."
24431 (org-close-par-maybe)
24432 (insert "</li>\n"))
24434 (defvar body-only) ; dynamically scoped into this.
24435 (defun org-html-level-start (level title umax with-toc head-count)
24436 "Insert a new level in HTML export.
24437 When TITLE is nil, just close all open levels."
24438 (org-close-par-maybe)
24439 (let ((l org-level-max))
24440 (while (>= l level)
24441 ; (while (>= l (1+ level))
24442 (if (aref org-levels-open (1- l))
24443 (progn
24444 (org-html-level-close l umax)
24445 (aset org-levels-open (1- l) nil)))
24446 (setq l (1- l)))
24447 (when title
24448 ;; If title is nil, this means this function is called to close
24449 ;; all levels, so the rest is done only if title is given
24450 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24451 (setq title (replace-match
24452 (if org-export-with-tags
24453 (save-match-data
24454 (concat
24455 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
24456 (mapconcat 'identity (org-split-string
24457 (match-string 1 title) ":")
24458 "&nbsp;")
24459 "</span>"))
24461 t t title)))
24462 (if (> level umax)
24463 (progn
24464 (if (aref org-levels-open (1- level))
24465 (progn
24466 (org-close-li)
24467 (insert "<li>" title "<br/>\n"))
24468 (aset org-levels-open (1- level) t)
24469 (org-close-par-maybe)
24470 (insert "<ul>\n<li>" title "<br/>\n")))
24471 (aset org-levels-open (1- level) t)
24472 (if (and org-export-with-section-numbers (not body-only))
24473 (setq title (concat (org-section-number level) " " title)))
24474 (setq level (+ level org-export-html-toplevel-hlevel -1))
24475 (if with-toc
24476 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
24477 level level head-count title level))
24478 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
24479 (org-open-par)))))
24481 (defun org-html-level-close (level max-outline-level)
24482 "Terminate one level in HTML export."
24483 (if (<= level max-outline-level)
24484 (insert "</div>\n")
24485 (org-close-li)
24486 (insert "</ul>\n")))
24488 ;;; iCalendar export
24490 ;;;###autoload
24491 (defun org-export-icalendar-this-file ()
24492 "Export current file as an iCalendar file.
24493 The iCalendar file will be located in the same directory as the Org-mode
24494 file, but with extension `.ics'."
24495 (interactive)
24496 (org-export-icalendar nil buffer-file-name))
24498 ;;;###autoload
24499 (defun org-export-icalendar-all-agenda-files ()
24500 "Export all files in `org-agenda-files' to iCalendar .ics files.
24501 Each iCalendar file will be located in the same directory as the Org-mode
24502 file, but with extension `.ics'."
24503 (interactive)
24504 (apply 'org-export-icalendar nil (org-agenda-files t)))
24506 ;;;###autoload
24507 (defun org-export-icalendar-combine-agenda-files ()
24508 "Export all files in `org-agenda-files' to a single combined iCalendar file.
24509 The file is stored under the name `org-combined-agenda-icalendar-file'."
24510 (interactive)
24511 (apply 'org-export-icalendar t (org-agenda-files t)))
24513 (defun org-export-icalendar (combine &rest files)
24514 "Create iCalendar files for all elements of FILES.
24515 If COMBINE is non-nil, combine all calendar entries into a single large
24516 file and store it under the name `org-combined-agenda-icalendar-file'."
24517 (save-excursion
24518 (org-prepare-agenda-buffers files)
24519 (let* ((dir (org-export-directory
24520 :ical (list :publishing-directory
24521 org-export-publishing-directory)))
24522 file ical-file ical-buffer category started org-agenda-new-buffers)
24524 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
24525 (when combine
24526 (setq ical-file
24527 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
24528 org-combined-agenda-icalendar-file
24529 (expand-file-name org-combined-agenda-icalendar-file dir))
24530 ical-buffer (org-get-agenda-file-buffer ical-file))
24531 (set-buffer ical-buffer) (erase-buffer))
24532 (while (setq file (pop files))
24533 (catch 'nextfile
24534 (org-check-agenda-file file)
24535 (set-buffer (org-get-agenda-file-buffer file))
24536 (unless combine
24537 (setq ical-file (concat (file-name-as-directory dir)
24538 (file-name-sans-extension
24539 (file-name-nondirectory buffer-file-name))
24540 ".ics"))
24541 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
24542 (with-current-buffer ical-buffer (erase-buffer)))
24543 (setq category (or org-category
24544 (file-name-sans-extension
24545 (file-name-nondirectory buffer-file-name))))
24546 (if (symbolp category) (setq category (symbol-name category)))
24547 (let ((standard-output ical-buffer))
24548 (if combine
24549 (and (not started) (setq started t)
24550 (org-start-icalendar-file org-icalendar-combined-name))
24551 (org-start-icalendar-file category))
24552 (org-print-icalendar-entries combine)
24553 (when (or (and combine (not files)) (not combine))
24554 (org-finish-icalendar-file)
24555 (set-buffer ical-buffer)
24556 (save-buffer)
24557 (run-hooks 'org-after-save-iCalendar-file-hook)))))
24558 (org-release-buffers org-agenda-new-buffers))))
24560 (defvar org-after-save-iCalendar-file-hook nil
24561 "Hook run after an iCalendar file has been saved.
24562 The iCalendar buffer is still current when this hook is run.
24563 A good way to use this is to tell a desktop calenndar application to re-read
24564 the iCalendar file.")
24566 (defun org-print-icalendar-entries (&optional combine)
24567 "Print iCalendar entries for the current Org-mode file to `standard-output'.
24568 When COMBINE is non nil, add the category to each line."
24569 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
24570 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
24571 (dts (org-ical-ts-to-string
24572 (format-time-string (cdr org-time-stamp-formats) (current-time))
24573 "DTSTART"))
24574 hd ts ts2 state status (inc t) pos b sexp rrule
24575 scheduledp deadlinep tmp pri category entry location summary desc
24576 (sexp-buffer (get-buffer-create "*ical-tmp*")))
24577 (org-refresh-category-properties)
24578 (save-excursion
24579 (goto-char (point-min))
24580 (while (re-search-forward re1 nil t)
24581 (catch :skip
24582 (org-agenda-skip)
24583 (setq pos (match-beginning 0)
24584 ts (match-string 0)
24585 inc t
24586 hd (org-get-heading)
24587 summary (org-entry-get nil "SUMMARY")
24588 desc (or (org-entry-get nil "DESCRIPTION")
24589 (org-get-cleaned-entry org-icalendar-include-body))
24590 location (org-entry-get nil "LOCATION")
24591 category (org-get-category))
24592 (if (looking-at re2)
24593 (progn
24594 (goto-char (match-end 0))
24595 (setq ts2 (match-string 1) inc nil))
24596 (setq tmp (buffer-substring (max (point-min)
24597 (- pos org-ds-keyword-length))
24598 pos)
24599 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
24600 (progn
24601 (setq inc nil)
24602 (replace-match "\\1" t nil ts))
24604 deadlinep (string-match org-deadline-regexp tmp)
24605 scheduledp (string-match org-scheduled-regexp tmp)
24606 ;; donep (org-entry-is-done-p)
24608 (if (or (string-match org-tr-regexp hd)
24609 (string-match org-ts-regexp hd))
24610 (setq hd (replace-match "" t t hd)))
24611 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
24612 (setq rrule
24613 (concat "\nRRULE:FREQ="
24614 (cdr (assoc
24615 (match-string 2 ts)
24616 '(("d" . "DAILY")("w" . "WEEKLY")
24617 ("m" . "MONTHLY")("y" . "YEARLY"))))
24618 ";INTERVAL=" (match-string 1 ts)))
24619 (setq rrule ""))
24620 (setq summary (or summary hd))
24621 (if (string-match org-bracket-link-regexp summary)
24622 (setq summary
24623 (replace-match (if (match-end 3)
24624 (match-string 3 summary)
24625 (match-string 1 summary))
24626 t t summary)))
24627 (if deadlinep (setq summary (concat "DL: " summary)))
24628 (if scheduledp (setq summary (concat "S: " summary)))
24629 (if (string-match "\\`<%%" ts)
24630 (with-current-buffer sexp-buffer
24631 (insert (substring ts 1 -1) " " summary "\n"))
24632 (princ (format "BEGIN:VEVENT
24634 %s%s
24635 SUMMARY:%s%s%s
24636 CATEGORIES:%s
24637 END:VEVENT\n"
24638 (org-ical-ts-to-string ts "DTSTART")
24639 (org-ical-ts-to-string ts2 "DTEND" inc)
24640 rrule summary
24641 (if (and desc (string-match "\\S-" desc))
24642 (concat "\nDESCRIPTION: " desc) "")
24643 (if (and location (string-match "\\S-" location))
24644 (concat "\nLOCATION: " location) "")
24645 category)))))
24647 (when (and org-icalendar-include-sexps
24648 (condition-case nil (require 'icalendar) (error nil))
24649 (fboundp 'icalendar-export-region))
24650 ;; Get all the literal sexps
24651 (goto-char (point-min))
24652 (while (re-search-forward "^&?%%(" nil t)
24653 (catch :skip
24654 (org-agenda-skip)
24655 (setq b (match-beginning 0))
24656 (goto-char (1- (match-end 0)))
24657 (forward-sexp 1)
24658 (end-of-line 1)
24659 (setq sexp (buffer-substring b (point)))
24660 (with-current-buffer sexp-buffer
24661 (insert sexp "\n"))
24662 (princ (org-diary-to-ical-string sexp-buffer)))))
24664 (when org-icalendar-include-todo
24665 (goto-char (point-min))
24666 (while (re-search-forward org-todo-line-regexp nil t)
24667 (catch :skip
24668 (org-agenda-skip)
24669 (setq state (match-string 2))
24670 (setq status (if (member state org-done-keywords)
24671 "COMPLETED" "NEEDS-ACTION"))
24672 (when (and state
24673 (or (not (member state org-done-keywords))
24674 (eq org-icalendar-include-todo 'all))
24675 (not (member org-archive-tag (org-get-tags-at)))
24677 (setq hd (match-string 3)
24678 summary (org-entry-get nil "SUMMARY")
24679 desc (or (org-entry-get nil "DESCRIPTION")
24680 (org-get-cleaned-entry org-icalendar-include-body))
24681 location (org-entry-get nil "LOCATION"))
24682 (if (string-match org-bracket-link-regexp hd)
24683 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
24684 (match-string 1 hd))
24685 t t hd)))
24686 (if (string-match org-priority-regexp hd)
24687 (setq pri (string-to-char (match-string 2 hd))
24688 hd (concat (substring hd 0 (match-beginning 1))
24689 (substring hd (match-end 1))))
24690 (setq pri org-default-priority))
24691 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
24692 (- org-lowest-priority org-highest-priority))))))
24694 (princ (format "BEGIN:VTODO
24696 SUMMARY:%s%s%s
24697 CATEGORIES:%s
24698 SEQUENCE:1
24699 PRIORITY:%d
24700 STATUS:%s
24701 END:VTODO\n"
24703 (or summary hd)
24704 (if (and location (string-match "\\S-" location))
24705 (concat "\nLOCATION: " location) "")
24706 (if (and desc (string-match "\\S-" desc))
24707 (concat "\nDESCRIPTION: " desc) "")
24708 category pri status)))))))))
24710 (defun org-get-cleaned-entry (what)
24711 "Clean-up description string."
24712 (when what
24713 (save-excursion
24714 (org-back-to-heading t)
24715 (let ((s (buffer-substring (point-at-bol 2) (org-end-of-subtree t)))
24716 (re (concat org-drawer-regexp "[^\000]*?:END:.*\n?"))
24717 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
24718 (while (string-match re s) (setq s (replace-match "" t t s)))
24719 (while (string-match re2 s) (setq s (replace-match "" t t s)))
24720 (if (string-match "[ \t\r\n]+\\'" s) (setq s (replace-match "" t t s)))
24721 (while (string-match "[ \t]*\n[ \t]*" s)
24722 (setq s (replace-match "\\n" t t s)))
24723 (setq s (org-trim s))
24724 (if (and (numberp what)
24725 (> (length s) what))
24726 (substring s 0 what)
24727 s)))))
24729 (defun org-start-icalendar-file (name)
24730 "Start an iCalendar file by inserting the header."
24731 (let ((user user-full-name)
24732 (name (or name "unknown"))
24733 (timezone (cadr (current-time-zone))))
24734 (princ
24735 (format "BEGIN:VCALENDAR
24736 VERSION:2.0
24737 X-WR-CALNAME:%s
24738 PRODID:-//%s//Emacs with Org-mode//EN
24739 X-WR-TIMEZONE:%s
24740 CALSCALE:GREGORIAN\n" name user timezone))))
24742 (defun org-finish-icalendar-file ()
24743 "Finish an iCalendar file by inserting the END statement."
24744 (princ "END:VCALENDAR\n"))
24746 (defun org-ical-ts-to-string (s keyword &optional inc)
24747 "Take a time string S and convert it to iCalendar format.
24748 KEYWORD is added in front, to make a complete line like DTSTART....
24749 When INC is non-nil, increase the hour by two (if time string contains
24750 a time), or the day by one (if it does not contain a time)."
24751 (let ((t1 (org-parse-time-string s 'nodefault))
24752 t2 fmt have-time time)
24753 (if (and (car t1) (nth 1 t1) (nth 2 t1))
24754 (setq t2 t1 have-time t)
24755 (setq t2 (org-parse-time-string s)))
24756 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
24757 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
24758 (when inc
24759 (if have-time
24760 (if org-agenda-default-appointment-duration
24761 (setq mi (+ org-agenda-default-appointment-duration mi))
24762 (setq h (+ 2 h)))
24763 (setq d (1+ d))))
24764 (setq time (encode-time s mi h d m y)))
24765 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
24766 (concat keyword (format-time-string fmt time))))
24768 ;;; XOXO export
24770 (defun org-export-as-xoxo-insert-into (buffer &rest output)
24771 (with-current-buffer buffer
24772 (apply 'insert output)))
24773 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
24775 (defun org-export-as-xoxo (&optional buffer)
24776 "Export the org buffer as XOXO.
24777 The XOXO buffer is named *xoxo-<source buffer name>*"
24778 (interactive (list (current-buffer)))
24779 ;; A quickie abstraction
24781 ;; Output everything as XOXO
24782 (with-current-buffer (get-buffer buffer)
24783 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
24784 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24785 (org-infile-export-plist)))
24786 (filename (concat (file-name-as-directory
24787 (org-export-directory :xoxo opt-plist))
24788 (file-name-sans-extension
24789 (file-name-nondirectory buffer-file-name))
24790 ".html"))
24791 (out (find-file-noselect filename))
24792 (last-level 1)
24793 (hanging-li nil))
24794 ;; Check the output buffer is empty.
24795 (with-current-buffer out (erase-buffer))
24796 ;; Kick off the output
24797 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
24798 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
24799 (let* ((hd (match-string-no-properties 1))
24800 (level (length hd))
24801 (text (concat
24802 (match-string-no-properties 2)
24803 (save-excursion
24804 (goto-char (match-end 0))
24805 (let ((str ""))
24806 (catch 'loop
24807 (while 't
24808 (forward-line)
24809 (if (looking-at "^[ \t]\\(.*\\)")
24810 (setq str (concat str (match-string-no-properties 1)))
24811 (throw 'loop str)))))))))
24813 ;; Handle level rendering
24814 (cond
24815 ((> level last-level)
24816 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
24818 ((< level last-level)
24819 (dotimes (- (- last-level level) 1)
24820 (if hanging-li
24821 (org-export-as-xoxo-insert-into out "</li>\n"))
24822 (org-export-as-xoxo-insert-into out "</ol>\n"))
24823 (when hanging-li
24824 (org-export-as-xoxo-insert-into out "</li>\n")
24825 (setq hanging-li nil)))
24827 ((equal level last-level)
24828 (if hanging-li
24829 (org-export-as-xoxo-insert-into out "</li>\n")))
24832 (setq last-level level)
24834 ;; And output the new li
24835 (setq hanging-li 't)
24836 (if (equal ?+ (elt text 0))
24837 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
24838 (org-export-as-xoxo-insert-into out "<li>" text))))
24840 ;; Finally finish off the ol
24841 (dotimes (- last-level 1)
24842 (if hanging-li
24843 (org-export-as-xoxo-insert-into out "</li>\n"))
24844 (org-export-as-xoxo-insert-into out "</ol>\n"))
24846 ;; Finish the buffer off and clean it up.
24847 (switch-to-buffer-other-window out)
24848 (indent-region (point-min) (point-max) nil)
24849 (save-buffer)
24850 (goto-char (point-min))
24854 ;;;; Key bindings
24856 ;; Make `C-c C-x' a prefix key
24857 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
24859 ;; TAB key with modifiers
24860 (org-defkey org-mode-map "\C-i" 'org-cycle)
24861 (org-defkey org-mode-map [(tab)] 'org-cycle)
24862 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
24863 (org-defkey org-mode-map [(meta tab)] 'org-complete)
24864 (org-defkey org-mode-map "\M-\t" 'org-complete)
24865 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
24866 ;; The following line is necessary under Suse GNU/Linux
24867 (unless (featurep 'xemacs)
24868 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
24869 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
24870 (define-key org-mode-map [backtab] 'org-shifttab)
24872 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
24873 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
24874 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
24876 ;; Cursor keys with modifiers
24877 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
24878 (org-defkey org-mode-map [(meta right)] 'org-metaright)
24879 (org-defkey org-mode-map [(meta up)] 'org-metaup)
24880 (org-defkey org-mode-map [(meta down)] 'org-metadown)
24882 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
24883 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
24884 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
24885 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
24887 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
24888 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
24889 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
24890 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
24892 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
24893 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
24895 ;;; Extra keys for tty access.
24896 ;; We only set them when really needed because otherwise the
24897 ;; menus don't show the simple keys
24899 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
24900 (not window-system))
24901 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
24902 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
24903 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
24904 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
24905 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
24906 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
24907 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
24908 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
24909 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
24910 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
24911 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
24912 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
24913 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
24914 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
24915 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
24916 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
24917 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
24918 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
24919 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
24920 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
24921 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
24922 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
24924 ;; All the other keys
24926 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
24927 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
24928 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
24929 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
24930 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
24931 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
24932 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
24933 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
24934 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
24935 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
24936 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
24937 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
24938 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
24939 (org-defkey org-mode-map "\C-c\C-w" 'org-check-deadlines)
24940 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
24941 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
24942 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
24943 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
24944 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
24945 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
24946 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
24947 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
24948 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
24949 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
24950 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
24951 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
24952 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
24953 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
24954 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
24955 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
24956 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
24957 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
24958 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
24959 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
24960 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
24961 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
24962 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
24963 (org-defkey org-mode-map "\C-c^" 'org-sort)
24964 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
24965 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
24966 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
24967 (org-defkey org-mode-map "\C-m" 'org-return)
24968 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
24969 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
24970 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
24971 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
24972 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
24973 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
24974 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
24975 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
24976 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
24977 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
24978 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
24979 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
24980 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
24981 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
24982 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
24983 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
24985 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
24986 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
24987 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
24988 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
24990 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
24991 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
24992 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
24993 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
24994 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
24995 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
24996 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
24997 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
24998 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
24999 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
25000 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
25001 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
25003 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
25005 (when (featurep 'xemacs)
25006 (org-defkey org-mode-map 'button3 'popup-mode-menu))
25008 (defsubst org-table-p () (org-at-table-p))
25010 (defun org-self-insert-command (N)
25011 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
25012 If the cursor is in a table looking at whitespace, the whitespace is
25013 overwritten, and the table is not marked as requiring realignment."
25014 (interactive "p")
25015 (if (and (org-table-p)
25016 (progn
25017 ;; check if we blank the field, and if that triggers align
25018 (and org-table-auto-blank-field
25019 (member last-command
25020 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25021 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25022 ;; got extra space, this field does not determine column width
25023 (let (org-table-may-need-update) (org-table-blank-field))
25024 ;; no extra space, this field may determine column width
25025 (org-table-blank-field)))
25027 (eq N 1)
25028 (looking-at "[^|\n]* |"))
25029 (let (org-table-may-need-update)
25030 (goto-char (1- (match-end 0)))
25031 (delete-backward-char 1)
25032 (goto-char (match-beginning 0))
25033 (self-insert-command N))
25034 (setq org-table-may-need-update t)
25035 (self-insert-command N)
25036 (org-fix-tags-on-the-fly)))
25038 (defun org-fix-tags-on-the-fly ()
25039 (when (and (equal (char-after (point-at-bol)) ?*)
25040 (org-on-heading-p))
25041 (org-align-tags-here org-tags-column)))
25043 (defun org-delete-backward-char (N)
25044 "Like `delete-backward-char', insert whitespace at field end in tables.
25045 When deleting backwards, in tables this function will insert whitespace in
25046 front of the next \"|\" separator, to keep the table aligned. The table will
25047 still be marked for re-alignment if the field did fill the entire column,
25048 because, in this case the deletion might narrow the column."
25049 (interactive "p")
25050 (if (and (org-table-p)
25051 (eq N 1)
25052 (string-match "|" (buffer-substring (point-at-bol) (point)))
25053 (looking-at ".*?|"))
25054 (let ((pos (point))
25055 (noalign (looking-at "[^|\n\r]* |"))
25056 (c org-table-may-need-update))
25057 (backward-delete-char N)
25058 (skip-chars-forward "^|")
25059 (insert " ")
25060 (goto-char (1- pos))
25061 ;; noalign: if there were two spaces at the end, this field
25062 ;; does not determine the width of the column.
25063 (if noalign (setq org-table-may-need-update c)))
25064 (backward-delete-char N)
25065 (org-fix-tags-on-the-fly)))
25067 (defun org-delete-char (N)
25068 "Like `delete-char', but insert whitespace at field end in tables.
25069 When deleting characters, in tables this function will insert whitespace in
25070 front of the next \"|\" separator, to keep the table aligned. The table will
25071 still be marked for re-alignment if the field did fill the entire column,
25072 because, in this case the deletion might narrow the column."
25073 (interactive "p")
25074 (if (and (org-table-p)
25075 (not (bolp))
25076 (not (= (char-after) ?|))
25077 (eq N 1))
25078 (if (looking-at ".*?|")
25079 (let ((pos (point))
25080 (noalign (looking-at "[^|\n\r]* |"))
25081 (c org-table-may-need-update))
25082 (replace-match (concat
25083 (substring (match-string 0) 1 -1)
25084 " |"))
25085 (goto-char pos)
25086 ;; noalign: if there were two spaces at the end, this field
25087 ;; does not determine the width of the column.
25088 (if noalign (setq org-table-may-need-update c)))
25089 (delete-char N))
25090 (delete-char N)
25091 (org-fix-tags-on-the-fly)))
25093 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25094 (put 'org-self-insert-command 'delete-selection t)
25095 (put 'orgtbl-self-insert-command 'delete-selection t)
25096 (put 'org-delete-char 'delete-selection 'supersede)
25097 (put 'org-delete-backward-char 'delete-selection 'supersede)
25099 ;; Make `flyspell-mode' delay after some commands
25100 (put 'org-self-insert-command 'flyspell-delayed t)
25101 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25102 (put 'org-delete-char 'flyspell-delayed t)
25103 (put 'org-delete-backward-char 'flyspell-delayed t)
25105 (eval-after-load "pabbrev"
25106 '(progn
25107 (add-to-list 'pabbrev-expand-after-command-list
25108 'orgtbl-self-insert-command t)
25109 (add-to-list 'pabbrev-expand-after-command-list
25110 'org-self-insert-command t)))
25112 ;; How to do this: Measure non-white length of current string
25113 ;; If equal to column width, we should realign.
25115 (defun org-remap (map &rest commands)
25116 "In MAP, remap the functions given in COMMANDS.
25117 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25118 (let (new old)
25119 (while commands
25120 (setq old (pop commands) new (pop commands))
25121 (if (fboundp 'command-remapping)
25122 (org-defkey map (vector 'remap old) new)
25123 (substitute-key-definition old new map global-map)))))
25125 (when (eq org-enable-table-editor 'optimized)
25126 ;; If the user wants maximum table support, we need to hijack
25127 ;; some standard editing functions
25128 (org-remap org-mode-map
25129 'self-insert-command 'org-self-insert-command
25130 'delete-char 'org-delete-char
25131 'delete-backward-char 'org-delete-backward-char)
25132 (org-defkey org-mode-map "|" 'org-force-self-insert))
25134 (defun org-shiftcursor-error ()
25135 "Throw an error because Shift-Cursor command was applied in wrong context."
25136 (error "This command is active in special context like tables, headlines or timestamps"))
25138 (defun org-shifttab (&optional arg)
25139 "Global visibility cycling or move to previous table field.
25140 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25141 on context.
25142 See the individual commands for more information."
25143 (interactive "P")
25144 (cond
25145 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25146 (arg (message "Content view to level: ")
25147 (org-content (prefix-numeric-value arg))
25148 (setq org-cycle-global-status 'overview))
25149 (t (call-interactively 'org-global-cycle))))
25151 (defun org-shiftmetaleft ()
25152 "Promote subtree or delete table column.
25153 Calls `org-promote-subtree', `org-outdent-item',
25154 or `org-table-delete-column', depending on context.
25155 See the individual commands for more information."
25156 (interactive)
25157 (cond
25158 ((org-at-table-p) (call-interactively 'org-table-delete-column))
25159 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
25160 ((org-at-item-p) (call-interactively 'org-outdent-item))
25161 (t (org-shiftcursor-error))))
25163 (defun org-shiftmetaright ()
25164 "Demote subtree or insert table column.
25165 Calls `org-demote-subtree', `org-indent-item',
25166 or `org-table-insert-column', depending on context.
25167 See the individual commands for more information."
25168 (interactive)
25169 (cond
25170 ((org-at-table-p) (call-interactively 'org-table-insert-column))
25171 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
25172 ((org-at-item-p) (call-interactively 'org-indent-item))
25173 (t (org-shiftcursor-error))))
25175 (defun org-shiftmetaup (&optional arg)
25176 "Move subtree up or kill table row.
25177 Calls `org-move-subtree-up' or `org-table-kill-row' or
25178 `org-move-item-up' depending on context. See the individual commands
25179 for more information."
25180 (interactive "P")
25181 (cond
25182 ((org-at-table-p) (call-interactively 'org-table-kill-row))
25183 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25184 ((org-at-item-p) (call-interactively 'org-move-item-up))
25185 (t (org-shiftcursor-error))))
25186 (defun org-shiftmetadown (&optional arg)
25187 "Move subtree down or insert table row.
25188 Calls `org-move-subtree-down' or `org-table-insert-row' or
25189 `org-move-item-down', depending on context. See the individual
25190 commands for more information."
25191 (interactive "P")
25192 (cond
25193 ((org-at-table-p) (call-interactively 'org-table-insert-row))
25194 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25195 ((org-at-item-p) (call-interactively 'org-move-item-down))
25196 (t (org-shiftcursor-error))))
25198 (defun org-metaleft (&optional arg)
25199 "Promote heading or move table column to left.
25200 Calls `org-do-promote' or `org-table-move-column', depending on context.
25201 With no specific context, calls the Emacs default `backward-word'.
25202 See the individual commands for more information."
25203 (interactive "P")
25204 (cond
25205 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
25206 ((or (org-on-heading-p) (org-region-active-p))
25207 (call-interactively 'org-do-promote))
25208 ((org-at-item-p) (call-interactively 'org-outdent-item))
25209 (t (call-interactively 'backward-word))))
25211 (defun org-metaright (&optional arg)
25212 "Demote subtree or move table column to right.
25213 Calls `org-do-demote' or `org-table-move-column', depending on context.
25214 With no specific context, calls the Emacs default `forward-word'.
25215 See the individual commands for more information."
25216 (interactive "P")
25217 (cond
25218 ((org-at-table-p) (call-interactively 'org-table-move-column))
25219 ((or (org-on-heading-p) (org-region-active-p))
25220 (call-interactively 'org-do-demote))
25221 ((org-at-item-p) (call-interactively 'org-indent-item))
25222 (t (call-interactively 'forward-word))))
25224 (defun org-metaup (&optional arg)
25225 "Move subtree up or move table row up.
25226 Calls `org-move-subtree-up' or `org-table-move-row' or
25227 `org-move-item-up', depending on context. See the individual commands
25228 for more information."
25229 (interactive "P")
25230 (cond
25231 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
25232 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25233 ((org-at-item-p) (call-interactively 'org-move-item-up))
25234 (t (transpose-lines 1) (beginning-of-line -1))))
25236 (defun org-metadown (&optional arg)
25237 "Move subtree down or move table row down.
25238 Calls `org-move-subtree-down' or `org-table-move-row' or
25239 `org-move-item-down', depending on context. See the individual
25240 commands for more information."
25241 (interactive "P")
25242 (cond
25243 ((org-at-table-p) (call-interactively 'org-table-move-row))
25244 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25245 ((org-at-item-p) (call-interactively 'org-move-item-down))
25246 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
25248 (defun org-shiftup (&optional arg)
25249 "Increase item in timestamp or increase priority of current headline.
25250 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
25251 depending on context. See the individual commands for more information."
25252 (interactive "P")
25253 (cond
25254 ((org-at-timestamp-p t)
25255 (call-interactively (if org-edit-timestamp-down-means-later
25256 'org-timestamp-down 'org-timestamp-up)))
25257 ((org-on-heading-p) (call-interactively 'org-priority-up))
25258 ((org-at-item-p) (call-interactively 'org-previous-item))
25259 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
25261 (defun org-shiftdown (&optional arg)
25262 "Decrease item in timestamp or decrease priority of current headline.
25263 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
25264 depending on context. See the individual commands for more information."
25265 (interactive "P")
25266 (cond
25267 ((org-at-timestamp-p t)
25268 (call-interactively (if org-edit-timestamp-down-means-later
25269 'org-timestamp-up 'org-timestamp-down)))
25270 ((org-on-heading-p) (call-interactively 'org-priority-down))
25271 (t (call-interactively 'org-next-item))))
25273 (defun org-shiftright ()
25274 "Next TODO keyword or timestamp one day later, depending on context."
25275 (interactive)
25276 (cond
25277 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
25278 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
25279 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
25280 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
25281 (t (org-shiftcursor-error))))
25283 (defun org-shiftleft ()
25284 "Previous TODO keyword or timestamp one day earlier, depending on context."
25285 (interactive)
25286 (cond
25287 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
25288 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
25289 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
25290 ((org-at-property-p)
25291 (call-interactively 'org-property-previous-allowed-value))
25292 (t (org-shiftcursor-error))))
25294 (defun org-shiftcontrolright ()
25295 "Switch to next TODO set."
25296 (interactive)
25297 (cond
25298 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
25299 (t (org-shiftcursor-error))))
25301 (defun org-shiftcontrolleft ()
25302 "Switch to previous TODO set."
25303 (interactive)
25304 (cond
25305 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
25306 (t (org-shiftcursor-error))))
25308 (defun org-ctrl-c-ret ()
25309 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
25310 (interactive)
25311 (cond
25312 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
25313 (t (call-interactively 'org-insert-heading))))
25315 (defun org-copy-special ()
25316 "Copy region in table or copy current subtree.
25317 Calls `org-table-copy' or `org-copy-subtree', depending on context.
25318 See the individual commands for more information."
25319 (interactive)
25320 (call-interactively
25321 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
25323 (defun org-cut-special ()
25324 "Cut region in table or cut current subtree.
25325 Calls `org-table-copy' or `org-cut-subtree', depending on context.
25326 See the individual commands for more information."
25327 (interactive)
25328 (call-interactively
25329 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
25331 (defun org-paste-special (arg)
25332 "Paste rectangular region into table, or past subtree relative to level.
25333 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
25334 See the individual commands for more information."
25335 (interactive "P")
25336 (if (org-at-table-p)
25337 (org-table-paste-rectangle)
25338 (org-paste-subtree arg)))
25340 (defun org-ctrl-c-ctrl-c (&optional arg)
25341 "Set tags in headline, or update according to changed information at point.
25343 This command does many different things, depending on context:
25345 - If the cursor is in a headline, prompt for tags and insert them
25346 into the current line, aligned to `org-tags-column'. When called
25347 with prefix arg, realign all tags in the current buffer.
25349 - If the cursor is in one of the special #+KEYWORD lines, this
25350 triggers scanning the buffer for these lines and updating the
25351 information.
25353 - If the cursor is inside a table, realign the table. This command
25354 works even if the automatic table editor has been turned off.
25356 - If the cursor is on a #+TBLFM line, re-apply the formulas to
25357 the entire table.
25359 - If the cursor is a the beginning of a dynamic block, update it.
25361 - If the cursor is inside a table created by the table.el package,
25362 activate that table.
25364 - If the current buffer is a remember buffer, close note and file it.
25365 with a prefix argument, file it without further interaction to the default
25366 location.
25368 - If the cursor is on a <<<target>>>, update radio targets and corresponding
25369 links in this buffer.
25371 - If the cursor is on a numbered item in a plain list, renumber the
25372 ordered list."
25373 (interactive "P")
25374 (let ((org-enable-table-editor t))
25375 (cond
25376 ((or org-clock-overlays
25377 org-occur-highlights
25378 org-latex-fragment-image-overlays)
25379 (org-remove-clock-overlays)
25380 (org-remove-occur-highlights)
25381 (org-remove-latex-fragment-image-overlays)
25382 (message "Temporary highlights/overlays removed from current buffer"))
25383 ((and (local-variable-p 'org-finish-function (current-buffer))
25384 (fboundp org-finish-function))
25385 (funcall org-finish-function))
25386 ((org-at-property-p)
25387 (call-interactively 'org-property-action))
25388 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
25389 ((org-on-heading-p) (call-interactively 'org-set-tags))
25390 ((org-at-table.el-p)
25391 (require 'table)
25392 (beginning-of-line 1)
25393 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
25394 (call-interactively 'table-recognize-table))
25395 ((org-at-table-p)
25396 (org-table-maybe-eval-formula)
25397 (if arg
25398 (call-interactively 'org-table-recalculate)
25399 (org-table-maybe-recalculate-line))
25400 (call-interactively 'org-table-align))
25401 ((org-at-item-checkbox-p)
25402 (call-interactively 'org-toggle-checkbox))
25403 ((org-at-item-p)
25404 (call-interactively 'org-maybe-renumber-ordered-list))
25405 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
25406 ;; Dynamic block
25407 (beginning-of-line 1)
25408 (org-update-dblock))
25409 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
25410 (cond
25411 ((equal (match-string 1) "TBLFM")
25412 ;; Recalculate the table before this line
25413 (save-excursion
25414 (beginning-of-line 1)
25415 (skip-chars-backward " \r\n\t")
25416 (if (org-at-table-p)
25417 (org-call-with-arg 'org-table-recalculate t))))
25419 (call-interactively 'org-mode-restart))))
25420 (t (error "C-c C-c can do nothing useful at this location.")))))
25422 (defun org-mode-restart ()
25423 "Restart Org-mode, to scan again for special lines.
25424 Also updates the keyword regular expressions."
25425 (interactive)
25426 (let ((org-inhibit-startup t)) (org-mode))
25427 (message "Org-mode restarted to refresh keyword and special line setup"))
25429 (defun org-kill-note-or-show-branches ()
25430 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
25431 (interactive)
25432 (if (not org-finish-function)
25433 (call-interactively 'show-branches)
25434 (let ((org-note-abort t))
25435 (funcall org-finish-function))))
25437 (defun org-return ()
25438 "Goto next table row or insert a newline.
25439 Calls `org-table-next-row' or `newline', depending on context.
25440 See the individual commands for more information."
25441 (interactive)
25442 (cond
25443 ((bobp) (newline))
25444 ((org-at-table-p)
25445 (org-table-justify-field-maybe)
25446 (call-interactively 'org-table-next-row))
25447 (t (newline))))
25450 (defun org-ctrl-c-minus ()
25451 "Insert separator line in table or modify bullet type in list.
25452 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
25453 depending on context."
25454 (interactive)
25455 (cond
25456 ((org-at-table-p)
25457 (call-interactively 'org-table-insert-hline))
25458 ((org-on-heading-p)
25459 ;; Convert to item
25460 (save-excursion
25461 (beginning-of-line 1)
25462 (if (looking-at "\\*+ ")
25463 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
25464 ((org-in-item-p)
25465 (call-interactively 'org-cycle-list-bullet))
25466 (t (error "`C-c -' does have no function here."))))
25468 (defun org-meta-return (&optional arg)
25469 "Insert a new heading or wrap a region in a table.
25470 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
25471 See the individual commands for more information."
25472 (interactive "P")
25473 (cond
25474 ((org-at-table-p)
25475 (call-interactively 'org-table-wrap-region))
25476 (t (call-interactively 'org-insert-heading))))
25478 ;;; Menu entries
25480 ;; Define the Org-mode menus
25481 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
25482 '("Tbl"
25483 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
25484 ["Next Field" org-cycle (org-at-table-p)]
25485 ["Previous Field" org-shifttab (org-at-table-p)]
25486 ["Next Row" org-return (org-at-table-p)]
25487 "--"
25488 ["Blank Field" org-table-blank-field (org-at-table-p)]
25489 ["Edit Field" org-table-edit-field (org-at-table-p)]
25490 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
25491 "--"
25492 ("Column"
25493 ["Move Column Left" org-metaleft (org-at-table-p)]
25494 ["Move Column Right" org-metaright (org-at-table-p)]
25495 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
25496 ["Insert Column" org-shiftmetaright (org-at-table-p)])
25497 ("Row"
25498 ["Move Row Up" org-metaup (org-at-table-p)]
25499 ["Move Row Down" org-metadown (org-at-table-p)]
25500 ["Delete Row" org-shiftmetaup (org-at-table-p)]
25501 ["Insert Row" org-shiftmetadown (org-at-table-p)]
25502 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
25503 "--"
25504 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
25505 ("Rectangle"
25506 ["Copy Rectangle" org-copy-special (org-at-table-p)]
25507 ["Cut Rectangle" org-cut-special (org-at-table-p)]
25508 ["Paste Rectangle" org-paste-special (org-at-table-p)]
25509 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
25510 "--"
25511 ("Calculate"
25512 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
25513 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
25514 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
25515 "--"
25516 ["Recalculate line" org-table-recalculate (org-at-table-p)]
25517 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
25518 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
25519 "--"
25520 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
25521 "--"
25522 ["Sum Column/Rectangle" org-table-sum
25523 (or (org-at-table-p) (org-region-active-p))]
25524 ["Which Column?" org-table-current-column (org-at-table-p)])
25525 ["Debug Formulas"
25526 org-table-toggle-formula-debugger
25527 :style toggle :selected org-table-formula-debug]
25528 ["Show Col/Row Numbers"
25529 org-table-toggle-coordinate-overlays
25530 :style toggle :selected org-table-overlay-coordinates]
25531 "--"
25532 ["Create" org-table-create (and (not (org-at-table-p))
25533 org-enable-table-editor)]
25534 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
25535 ["Import from File" org-table-import (not (org-at-table-p))]
25536 ["Export to File" org-table-export (org-at-table-p)]
25537 "--"
25538 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
25540 (easy-menu-define org-org-menu org-mode-map "Org menu"
25541 '("Org"
25542 ("Show/Hide"
25543 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
25544 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
25545 ["Sparse Tree" org-occur t]
25546 ["Reveal Context" org-reveal t]
25547 ["Show All" show-all t]
25548 "--"
25549 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
25550 "--"
25551 ["New Heading" org-insert-heading t]
25552 ("Navigate Headings"
25553 ["Up" outline-up-heading t]
25554 ["Next" outline-next-visible-heading t]
25555 ["Previous" outline-previous-visible-heading t]
25556 ["Next Same Level" outline-forward-same-level t]
25557 ["Previous Same Level" outline-backward-same-level t]
25558 "--"
25559 ["Jump" org-goto t])
25560 ("Edit Structure"
25561 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
25562 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
25563 "--"
25564 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
25565 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
25566 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
25567 "--"
25568 ["Promote Heading" org-metaleft (not (org-at-table-p))]
25569 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
25570 ["Demote Heading" org-metaright (not (org-at-table-p))]
25571 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
25572 "--"
25573 ["Sort Region/Children" org-sort (not (org-at-table-p))]
25574 "--"
25575 ["Convert to odd levels" org-convert-to-odd-levels t]
25576 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
25577 ("Editing"
25578 ["Emphasis..." org-emphasize t])
25579 ("Archive"
25580 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
25581 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
25582 ; :active t :keys "C-u C-c C-x C-a"]
25583 ["Sparse trees open ARCHIVE trees"
25584 (setq org-sparse-tree-open-archived-trees
25585 (not org-sparse-tree-open-archived-trees))
25586 :style toggle :selected org-sparse-tree-open-archived-trees]
25587 ["Cycling opens ARCHIVE trees"
25588 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
25589 :style toggle :selected org-cycle-open-archived-trees]
25590 ["Agenda includes ARCHIVE trees"
25591 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
25592 :style toggle :selected (not org-agenda-skip-archived-trees)]
25593 "--"
25594 ["Move Subtree to Archive" org-advertized-archive-subtree t]
25595 ; ["Check and Move Children" (org-archive-subtree '(4))
25596 ; :active t :keys "C-u C-c C-x C-s"]
25598 "--"
25599 ("TODO Lists"
25600 ["TODO/DONE/-" org-todo t]
25601 ("Select keyword"
25602 ["Next keyword" org-shiftright (org-on-heading-p)]
25603 ["Previous keyword" org-shiftleft (org-on-heading-p)]
25604 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
25605 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
25606 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
25607 ["Show TODO Tree" org-show-todo-tree t]
25608 ["Global TODO list" org-todo-list t]
25609 "--"
25610 ["Set Priority" org-priority t]
25611 ["Priority Up" org-shiftup t]
25612 ["Priority Down" org-shiftdown t])
25613 ("TAGS and Properties"
25614 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
25615 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
25616 "--"
25617 ["Set property" 'org-set-property t]
25618 ["Column view of properties" org-columns t]
25619 ["Insert Column View DBlock" org-insert-columns-dblock t])
25620 ("Dates and Scheduling"
25621 ["Timestamp" org-time-stamp t]
25622 ["Timestamp (inactive)" org-time-stamp-inactive t]
25623 ("Change Date"
25624 ["1 Day Later" org-shiftright t]
25625 ["1 Day Earlier" org-shiftleft t]
25626 ["1 ... Later" org-shiftup t]
25627 ["1 ... Earlier" org-shiftdown t])
25628 ["Compute Time Range" org-evaluate-time-range t]
25629 ["Schedule Item" org-schedule t]
25630 ["Deadline" org-deadline t]
25631 "--"
25632 ["Custom time format" org-toggle-time-stamp-overlays
25633 :style radio :selected org-display-custom-times]
25634 "--"
25635 ["Goto Calendar" org-goto-calendar t]
25636 ["Date from Calendar" org-date-from-calendar t])
25637 ("Logging work"
25638 ["Clock in" org-clock-in t]
25639 ["Clock out" org-clock-out t]
25640 ["Clock cancel" org-clock-cancel t]
25641 ["Goto running clock" org-clock-goto t]
25642 ["Display times" org-clock-display t]
25643 ["Create clock table" org-clock-report t]
25644 "--"
25645 ["Record DONE time"
25646 (progn (setq org-log-done (not org-log-done))
25647 (message "Switching to %s will %s record a timestamp"
25648 (car org-done-keywords)
25649 (if org-log-done "automatically" "not")))
25650 :style toggle :selected org-log-done])
25651 "--"
25652 ["Agenda Command..." org-agenda t]
25653 ("File List for Agenda")
25654 ("Special views current file"
25655 ["TODO Tree" org-show-todo-tree t]
25656 ["Check Deadlines" org-check-deadlines t]
25657 ["Timeline" org-timeline t]
25658 ["Tags Tree" org-tags-sparse-tree t])
25659 "--"
25660 ("Hyperlinks"
25661 ["Store Link (Global)" org-store-link t]
25662 ["Insert Link" org-insert-link t]
25663 ["Follow Link" org-open-at-point t]
25664 "--"
25665 ["Next link" org-next-link t]
25666 ["Previous link" org-previous-link t]
25667 "--"
25668 ["Descriptive Links"
25669 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
25670 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
25671 ["Literal Links"
25672 (progn
25673 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
25674 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
25675 "--"
25676 ["Export/Publish..." org-export t]
25677 ("LaTeX"
25678 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
25679 :selected org-cdlatex-mode]
25680 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
25681 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
25682 ["Modify math symbol" org-cdlatex-math-modify
25683 (org-inside-LaTeX-fragment-p)]
25684 ["Export LaTeX fragments as images"
25685 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
25686 :style toggle :selected org-export-with-LaTeX-fragments])
25687 "--"
25688 ("Documentation"
25689 ["Show Version" org-version t]
25690 ["Info Documentation" org-info t])
25691 ("Customize"
25692 ["Browse Org Group" org-customize t]
25693 "--"
25694 ["Expand This Menu" org-create-customize-menu
25695 (fboundp 'customize-menu-create)])
25696 "--"
25697 ["Refresh setup" org-mode-restart t]
25700 (defun org-info (&optional node)
25701 "Read documentation for Org-mode in the info system.
25702 With optional NODE, go directly to that node."
25703 (interactive)
25704 (require 'info)
25705 (Info-goto-node (format "(org)%s" (or node ""))))
25707 (defun org-install-agenda-files-menu ()
25708 (let ((bl (buffer-list)))
25709 (save-excursion
25710 (while bl
25711 (set-buffer (pop bl))
25712 (if (org-mode-p) (setq bl nil)))
25713 (when (org-mode-p)
25714 (easy-menu-change
25715 '("Org") "File List for Agenda"
25716 (append
25717 (list
25718 ["Edit File List" (org-edit-agenda-file-list) t]
25719 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
25720 ["Remove Current File from List" org-remove-file t]
25721 ["Cycle through agenda files" org-cycle-agenda-files t]
25722 ["Occur in all agenda files" org-occur-in-agenda-files t]
25723 "--")
25724 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
25726 ;;;; Documentation
25728 (defun org-customize ()
25729 "Call the customize function with org as argument."
25730 (interactive)
25731 (customize-browse 'org))
25733 (defun org-create-customize-menu ()
25734 "Create a full customization menu for Org-mode, insert it into the menu."
25735 (interactive)
25736 (if (fboundp 'customize-menu-create)
25737 (progn
25738 (easy-menu-change
25739 '("Org") "Customize"
25740 `(["Browse Org group" org-customize t]
25741 "--"
25742 ,(customize-menu-create 'org)
25743 ["Set" Custom-set t]
25744 ["Save" Custom-save t]
25745 ["Reset to Current" Custom-reset-current t]
25746 ["Reset to Saved" Custom-reset-saved t]
25747 ["Reset to Standard Settings" Custom-reset-standard t]))
25748 (message "\"Org\"-menu now contains full customization menu"))
25749 (error "Cannot expand menu (outdated version of cus-edit.el)")))
25751 ;;;; Miscellaneous stuff
25754 ;;; Generally useful functions
25756 (defun org-context ()
25757 "Return a list of contexts of the current cursor position.
25758 If several contexts apply, all are returned.
25759 Each context entry is a list with a symbol naming the context, and
25760 two positions indicating start and end of the context. Possible
25761 contexts are:
25763 :headline anywhere in a headline
25764 :headline-stars on the leading stars in a headline
25765 :todo-keyword on a TODO keyword (including DONE) in a headline
25766 :tags on the TAGS in a headline
25767 :priority on the priority cookie in a headline
25768 :item on the first line of a plain list item
25769 :item-bullet on the bullet/number of a plain list item
25770 :checkbox on the checkbox in a plain list item
25771 :table in an org-mode table
25772 :table-special on a special filed in a table
25773 :table-table in a table.el table
25774 :link on a hyperlink
25775 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
25776 :target on a <<target>>
25777 :radio-target on a <<<radio-target>>>
25778 :latex-fragment on a LaTeX fragment
25779 :latex-preview on a LaTeX fragment with overlayed preview image
25781 This function expects the position to be visible because it uses font-lock
25782 faces as a help to recognize the following contexts: :table-special, :link,
25783 and :keyword."
25784 (let* ((f (get-text-property (point) 'face))
25785 (faces (if (listp f) f (list f)))
25786 (p (point)) clist o)
25787 ;; First the large context
25788 (cond
25789 ((org-on-heading-p t)
25790 (push (list :headline (point-at-bol) (point-at-eol)) clist)
25791 (when (progn
25792 (beginning-of-line 1)
25793 (looking-at org-todo-line-tags-regexp))
25794 (push (org-point-in-group p 1 :headline-stars) clist)
25795 (push (org-point-in-group p 2 :todo-keyword) clist)
25796 (push (org-point-in-group p 4 :tags) clist))
25797 (goto-char p)
25798 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
25799 (if (looking-at "\\[#[A-Z0-9]\\]")
25800 (push (org-point-in-group p 0 :priority) clist)))
25802 ((org-at-item-p)
25803 (push (org-point-in-group p 2 :item-bullet) clist)
25804 (push (list :item (point-at-bol)
25805 (save-excursion (org-end-of-item) (point)))
25806 clist)
25807 (and (org-at-item-checkbox-p)
25808 (push (org-point-in-group p 0 :checkbox) clist)))
25810 ((org-at-table-p)
25811 (push (list :table (org-table-begin) (org-table-end)) clist)
25812 (if (memq 'org-formula faces)
25813 (push (list :table-special
25814 (previous-single-property-change p 'face)
25815 (next-single-property-change p 'face)) clist)))
25816 ((org-at-table-p 'any)
25817 (push (list :table-table) clist)))
25818 (goto-char p)
25820 ;; Now the small context
25821 (cond
25822 ((org-at-timestamp-p)
25823 (push (org-point-in-group p 0 :timestamp) clist))
25824 ((memq 'org-link faces)
25825 (push (list :link
25826 (previous-single-property-change p 'face)
25827 (next-single-property-change p 'face)) clist))
25828 ((memq 'org-special-keyword faces)
25829 (push (list :keyword
25830 (previous-single-property-change p 'face)
25831 (next-single-property-change p 'face)) clist))
25832 ((org-on-target-p)
25833 (push (org-point-in-group p 0 :target) clist)
25834 (goto-char (1- (match-beginning 0)))
25835 (if (looking-at org-radio-target-regexp)
25836 (push (org-point-in-group p 0 :radio-target) clist))
25837 (goto-char p))
25838 ((setq o (car (delq nil
25839 (mapcar
25840 (lambda (x)
25841 (if (memq x org-latex-fragment-image-overlays) x))
25842 (org-overlays-at (point))))))
25843 (push (list :latex-fragment
25844 (org-overlay-start o) (org-overlay-end o)) clist)
25845 (push (list :latex-preview
25846 (org-overlay-start o) (org-overlay-end o)) clist))
25847 ((org-inside-LaTeX-fragment-p)
25848 ;; FIXME: positions wrong.
25849 (push (list :latex-fragment (point) (point)) clist)))
25851 (setq clist (nreverse (delq nil clist)))
25852 clist))
25854 ;; FIXME: Compare with at-regexp-p Do we need both?
25855 (defun org-in-regexp (re &optional nlines visually)
25856 "Check if point is inside a match of regexp.
25857 Normally only the current line is checked, but you can include NLINES extra
25858 lines both before and after point into the search.
25859 If VISUALLY is set, require that the cursor is not after the match but
25860 really on, so that the block visually is on the match."
25861 (catch 'exit
25862 (let ((pos (point))
25863 (eol (point-at-eol (+ 1 (or nlines 0))))
25864 (inc (if visually 1 0)))
25865 (save-excursion
25866 (beginning-of-line (- 1 (or nlines 0)))
25867 (while (re-search-forward re eol t)
25868 (if (and (<= (match-beginning 0) pos)
25869 (>= (+ inc (match-end 0)) pos))
25870 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
25872 (defun org-at-regexp-p (regexp)
25873 "Is point inside a match of REGEXP in the current line?"
25874 (catch 'exit
25875 (save-excursion
25876 (let ((pos (point)) (end (point-at-eol)))
25877 (beginning-of-line 1)
25878 (while (re-search-forward regexp end t)
25879 (if (and (<= (match-beginning 0) pos)
25880 (>= (match-end 0) pos))
25881 (throw 'exit t)))
25882 nil))))
25884 (defun org-occur-in-agenda-files (regexp &optional nlines)
25885 "Call `multi-occur' with buffers for all agenda files."
25886 (interactive "sOrg-files matching: \np")
25887 (let* ((files (org-agenda-files))
25888 (tnames (mapcar 'file-truename files))
25889 (extra org-agenda-multi-occur-extra-files)
25891 (while (setq f (pop extra))
25892 (unless (member (file-truename f) tnames)
25893 (add-to-list 'files f 'append)
25894 (add-to-list 'tnames (file-truename f) 'append)))
25895 (multi-occur
25896 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
25897 regexp)))
25899 (defun org-uniquify (list)
25900 "Remove duplicate elements from LIST."
25901 (let (res)
25902 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
25903 res))
25905 (defun org-delete-all (elts list)
25906 "Remove all elements in ELTS from LIST."
25907 (while elts
25908 (setq list (delete (pop elts) list)))
25909 list)
25911 (defun org-point-in-group (point group &optional context)
25912 "Check if POINT is in match-group GROUP.
25913 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
25914 match. If the match group does ot exist or point is not inside it,
25915 return nil."
25916 (and (match-beginning group)
25917 (>= point (match-beginning group))
25918 (<= point (match-end group))
25919 (if context
25920 (list context (match-beginning group) (match-end group))
25921 t)))
25923 (defun org-switch-to-buffer-other-window (&rest args)
25924 "Switch to buffer in a second window on the current frame.
25925 In particular, do not allow pop-up frames."
25926 (let (pop-up-frames special-display-buffer-names special-display-regexps
25927 special-display-function)
25928 (apply 'switch-to-buffer-other-window args)))
25930 (defun org-combine-plists (&rest plists)
25931 "Create a single property list from all plists in PLISTS.
25932 The process starts by copying the first list, and then setting properties
25933 from the other lists. Settings in the last list are the most significant
25934 ones and overrule settings in the other lists."
25935 (let ((rtn (copy-sequence (pop plists)))
25936 p v ls)
25937 (while plists
25938 (setq ls (pop plists))
25939 (while ls
25940 (setq p (pop ls) v (pop ls))
25941 (setq rtn (plist-put rtn p v))))
25942 rtn))
25944 (defun org-move-line-down (arg)
25945 "Move the current line down. With prefix argument, move it past ARG lines."
25946 (interactive "p")
25947 (let ((col (current-column))
25948 beg end pos)
25949 (beginning-of-line 1) (setq beg (point))
25950 (beginning-of-line 2) (setq end (point))
25951 (beginning-of-line (+ 1 arg))
25952 (setq pos (move-marker (make-marker) (point)))
25953 (insert (delete-and-extract-region beg end))
25954 (goto-char pos)
25955 (move-to-column col)))
25957 (defun org-move-line-up (arg)
25958 "Move the current line up. With prefix argument, move it past ARG lines."
25959 (interactive "p")
25960 (let ((col (current-column))
25961 beg end pos)
25962 (beginning-of-line 1) (setq beg (point))
25963 (beginning-of-line 2) (setq end (point))
25964 (beginning-of-line (- arg))
25965 (setq pos (move-marker (make-marker) (point)))
25966 (insert (delete-and-extract-region beg end))
25967 (goto-char pos)
25968 (move-to-column col)))
25970 (defun org-replace-escapes (string table)
25971 "Replace %-escapes in STRING with values in TABLE.
25972 TABLE is an association list with keys like \"%a\" and string values.
25973 The sequences in STRING may contain normal field width and padding information,
25974 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
25975 so values can contain further %-escapes if they are define later in TABLE."
25976 (let ((case-fold-search nil)
25977 e re rpl)
25978 (while (setq e (pop table))
25979 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
25980 (while (string-match re string)
25981 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
25982 (cdr e)))
25983 (setq string (replace-match rpl t t string))))
25984 string))
25987 (defun org-sublist (list start end)
25988 "Return a section of LIST, from START to END.
25989 Counting starts at 1."
25990 (let (rtn (c start))
25991 (setq list (nthcdr (1- start) list))
25992 (while (and list (<= c end))
25993 (push (pop list) rtn)
25994 (setq c (1+ c)))
25995 (nreverse rtn)))
25997 (defun org-find-base-buffer-visiting (file)
25998 "Like `find-buffer-visiting' but alway return the base buffer and
25999 not an indirect buffer"
26000 (let ((buf (find-buffer-visiting file)))
26001 (if buf
26002 (or (buffer-base-buffer buf) buf)
26003 nil)))
26005 (defun org-image-file-name-regexp ()
26006 "Return regexp matching the file names of images."
26007 (if (fboundp 'image-file-name-regexp)
26008 (image-file-name-regexp)
26009 (let ((image-file-name-extensions
26010 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
26011 "xbm" "xpm" "pbm" "pgm" "ppm")))
26012 (concat "\\."
26013 (regexp-opt (nconc (mapcar 'upcase
26014 image-file-name-extensions)
26015 image-file-name-extensions)
26017 "\\'"))))
26019 (defun org-file-image-p (file)
26020 "Return non-nil if FILE is an image."
26021 (save-match-data
26022 (string-match (org-image-file-name-regexp) file)))
26024 ;;; Paragraph filling stuff.
26025 ;; We want this to be just right, so use the full arsenal.
26027 (defun org-indent-line-function ()
26028 "Indent line like previous, but further if previous was headline or item."
26029 (interactive)
26030 (let* ((pos (point))
26031 (itemp (org-at-item-p))
26032 column bpos bcol tpos tcol bullet btype bullet-type)
26033 ;; Find the previous relevant line
26034 (beginning-of-line 1)
26035 (cond
26036 ((looking-at "#") (setq column 0))
26037 ((looking-at "\\*+ ") (setq column 0))
26039 (beginning-of-line 0)
26040 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26041 (beginning-of-line 0))
26042 (cond
26043 ((looking-at "\\*+[ \t]+")
26044 (goto-char (match-end 0))
26045 (setq column (current-column)))
26046 ((org-in-item-p)
26047 (org-beginning-of-item)
26048 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26049 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26050 (setq bpos (match-beginning 1) tpos (match-end 0)
26051 bcol (progn (goto-char bpos) (current-column))
26052 tcol (progn (goto-char tpos) (current-column))
26053 bullet (match-string 1)
26054 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26055 (if (not itemp)
26056 (setq column tcol)
26057 (goto-char pos)
26058 (beginning-of-line 1)
26059 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26060 (setq bullet (match-string 1)
26061 btype (if (string-match "[0-9]" bullet) "n" bullet))
26062 (setq column (if (equal btype bullet-type) bcol tcol))))
26063 (t (setq column (org-get-indentation))))))
26064 (goto-char pos)
26065 (if (<= (current-column) (current-indentation))
26066 (indent-line-to column)
26067 (save-excursion (indent-line-to column)))
26068 (setq column (current-column))
26069 (beginning-of-line 1)
26070 (if (looking-at
26071 "\\([ \t]+\\)\\(:[0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26072 (replace-match (concat "\\1" (format org-property-format
26073 (match-string 2) (match-string 3)))
26074 t nil))
26075 (move-to-column column)))
26077 (defun org-set-autofill-regexps ()
26078 (interactive)
26079 ;; In the paragraph separator we include headlines, because filling
26080 ;; text in a line directly attached to a headline would otherwise
26081 ;; fill the headline as well.
26082 (org-set-local 'comment-start-skip "^#+[ \t]*")
26083 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26084 ;; The paragraph starter includes hand-formatted lists.
26085 (org-set-local 'paragraph-start
26086 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26087 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26088 ;; But only if the user has not turned off tables or fixed-width regions
26089 (org-set-local
26090 'auto-fill-inhibit-regexp
26091 (concat "\\*+ \\|#\\+"
26092 "\\|[ \t]*" org-keyword-time-regexp
26093 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26094 (concat
26095 "\\|[ \t]*["
26096 (if org-enable-table-editor "|" "")
26097 (if org-enable-fixed-width-editor ":" "")
26098 "]"))))
26099 ;; We use our own fill-paragraph function, to make sure that tables
26100 ;; and fixed-width regions are not wrapped. That function will pass
26101 ;; through to `fill-paragraph' when appropriate.
26102 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26103 ; Adaptive filling: To get full control, first make sure that
26104 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26105 (org-set-local 'adaptive-fill-regexp "\000")
26106 (org-set-local 'adaptive-fill-function
26107 'org-adaptive-fill-function))
26109 (defun org-fill-paragraph (&optional justify)
26110 "Re-align a table, pass through to fill-paragraph if no table."
26111 (let ((table-p (org-at-table-p))
26112 (table.el-p (org-at-table.el-p)))
26113 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26114 (table.el-p t) ; skip table.el tables
26115 (table-p (org-table-align) t) ; align org-mode tables
26116 (t nil)))) ; call paragraph-fill
26118 ;; For reference, this is the default value of adaptive-fill-regexp
26119 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26121 (defun org-adaptive-fill-function ()
26122 "Return a fill prefix for org-mode files.
26123 In particular, this makes sure hanging paragraphs for hand-formatted lists
26124 work correctly."
26125 (cond ((looking-at "#[ \t]+")
26126 (match-string 0))
26127 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26128 (save-excursion
26129 (goto-char (match-end 0))
26130 (make-string (current-column) ?\ )))
26131 (t nil)))
26133 ;;;; Functions extending outline functionality
26135 (defun org-beginning-of-line (&optional arg)
26136 "Go to the beginning of the current line. If that is invisible, continue
26137 to a visible line beginning. This makes the function of C-a more intuitive.
26138 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26139 first attempt, and only move to after the tags when the cursor is already
26140 beyond the end of the headline."
26141 (interactive "P")
26142 (let ((pos (point)))
26143 (beginning-of-line 1)
26144 (if (bobp)
26146 (backward-char 1)
26147 (if (org-invisible-p)
26148 (while (and (not (bobp)) (org-invisible-p))
26149 (backward-char 1)
26150 (beginning-of-line 1))
26151 (forward-char 1)))
26152 (when org-special-ctrl-a/e
26153 (cond
26154 ((and (looking-at org-todo-line-regexp)
26155 (= (char-after (match-end 1)) ?\ ))
26156 (goto-char
26157 (if (eq org-special-ctrl-a/e t)
26158 (cond ((> pos (match-beginning 3)) (match-beginning 3))
26159 ((= pos (point)) (match-beginning 3))
26160 (t (point)))
26161 (cond ((> pos (point)) (point))
26162 ((not (eq last-command this-command)) (point))
26163 (t (match-beginning 3))))))
26164 ((org-at-item-p)
26165 (goto-char
26166 (if (eq org-special-ctrl-a/e t)
26167 (cond ((> pos (match-end 4)) (match-end 4))
26168 ((= pos (point)) (match-end 4))
26169 (t (point)))
26170 (cond ((> pos (point)) (point))
26171 ((not (eq last-command this-command)) (point))
26172 (t (match-end 4))))))))))
26174 (defun org-end-of-line (&optional arg)
26175 "Go to the end of the line.
26176 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26177 first attempt, and only move to after the tags when the cursor is already
26178 beyond the end of the headline."
26179 (interactive "P")
26180 (if (or (not org-special-ctrl-a/e)
26181 (not (org-on-heading-p)))
26182 (end-of-line arg)
26183 (let ((pos (point)))
26184 (beginning-of-line 1)
26185 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
26186 (if (eq org-special-ctrl-a/e t)
26187 (if (or (< pos (match-beginning 1))
26188 (= pos (match-end 0)))
26189 (goto-char (match-beginning 1))
26190 (goto-char (match-end 0)))
26191 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
26192 (goto-char (match-end 0))
26193 (goto-char (match-beginning 1))))
26194 (end-of-line arg)))))
26196 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
26197 (define-key org-mode-map "\C-e" 'org-end-of-line)
26199 (defun org-invisible-p ()
26200 "Check if point is at a character currently not visible."
26201 ;; Early versions of noutline don't have `outline-invisible-p'.
26202 (if (fboundp 'outline-invisible-p)
26203 (outline-invisible-p)
26204 (get-char-property (point) 'invisible)))
26206 (defun org-invisible-p2 ()
26207 "Check if point is at a character currently not visible."
26208 (save-excursion
26209 (if (and (eolp) (not (bobp))) (backward-char 1))
26210 ;; Early versions of noutline don't have `outline-invisible-p'.
26211 (if (fboundp 'outline-invisible-p)
26212 (outline-invisible-p)
26213 (get-char-property (point) 'invisible))))
26215 (defalias 'org-back-to-heading 'outline-back-to-heading)
26216 (defalias 'org-on-heading-p 'outline-on-heading-p)
26217 (defalias 'org-at-heading-p 'outline-on-heading-p)
26218 (defun org-at-heading-or-item-p ()
26219 (or (org-on-heading-p) (org-at-item-p)))
26221 (defun org-on-target-p ()
26222 (or (org-in-regexp org-radio-target-regexp)
26223 (org-in-regexp org-target-regexp)))
26225 (defun org-up-heading-all (arg)
26226 "Move to the heading line of which the present line is a subheading.
26227 This function considers both visible and invisible heading lines.
26228 With argument, move up ARG levels."
26229 (if (fboundp 'outline-up-heading-all)
26230 (outline-up-heading-all arg) ; emacs 21 version of outline.el
26231 (outline-up-heading arg t))) ; emacs 22 version of outline.el
26233 (defun org-up-heading-safe ()
26234 "Move to the heading line of which the present line is a subheading.
26235 This version will not throw an error. It will return the level of the
26236 headline found, or nil if no higher level is found."
26237 (let ((pos (point)) start-level level
26238 (re (concat "^" outline-regexp)))
26239 (catch 'exit
26240 (outline-back-to-heading t)
26241 (setq start-level (funcall outline-level))
26242 (if (equal start-level 1) (throw 'exit nil))
26243 (while (re-search-backward re nil t)
26244 (setq level (funcall outline-level))
26245 (if (< level start-level) (throw 'exit level)))
26246 nil)))
26248 (defun org-goto-sibling (&optional previous)
26249 "Goto the next sibling, even if it is invisible.
26250 When PREVIOUS is set, go to the previous sibling instead. Returns t
26251 when a sibling was found. When none is found, return nil and don't
26252 move point."
26253 (let ((fun (if previous 're-search-backward 're-search-forward))
26254 (pos (point))
26255 (re (concat "^" outline-regexp))
26256 level l)
26257 (when (condition-case nil (org-back-to-heading t) (error nil))
26258 (setq level (funcall outline-level))
26259 (catch 'exit
26260 (or previous (forward-char 1))
26261 (while (funcall fun re nil t)
26262 (setq l (funcall outline-level))
26263 (when (< l level) (goto-char pos) (throw 'exit nil))
26264 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
26265 (goto-char pos)
26266 nil))))
26268 (defun org-show-siblings ()
26269 "Show all siblings of the current headline."
26270 (save-excursion
26271 (while (org-goto-sibling) (org-flag-heading nil)))
26272 (save-excursion
26273 (while (org-goto-sibling 'previous)
26274 (org-flag-heading nil))))
26276 (defun org-show-hidden-entry ()
26277 "Show an entry where even the heading is hidden."
26278 (save-excursion
26279 (org-show-entry)))
26281 (defun org-flag-heading (flag &optional entry)
26282 "Flag the current heading. FLAG non-nil means make invisible.
26283 When ENTRY is non-nil, show the entire entry."
26284 (save-excursion
26285 (org-back-to-heading t)
26286 ;; Check if we should show the entire entry
26287 (if entry
26288 (progn
26289 (org-show-entry)
26290 (save-excursion
26291 (and (outline-next-heading)
26292 (org-flag-heading nil))))
26293 (outline-flag-region (max (point-min) (1- (point)))
26294 (save-excursion (outline-end-of-heading) (point))
26295 flag))))
26297 (defun org-end-of-subtree (&optional invisible-OK to-heading)
26298 ;; This is an exact copy of the original function, but it uses
26299 ;; `org-back-to-heading', to make it work also in invisible
26300 ;; trees. And is uses an invisible-OK argument.
26301 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
26302 (org-back-to-heading invisible-OK)
26303 (let ((first t)
26304 (level (funcall outline-level)))
26305 (while (and (not (eobp))
26306 (or first (> (funcall outline-level) level)))
26307 (setq first nil)
26308 (outline-next-heading))
26309 (unless to-heading
26310 (if (memq (preceding-char) '(?\n ?\^M))
26311 (progn
26312 ;; Go to end of line before heading
26313 (forward-char -1)
26314 (if (memq (preceding-char) '(?\n ?\^M))
26315 ;; leave blank line before heading
26316 (forward-char -1))))))
26317 (point))
26319 (defun org-show-subtree ()
26320 "Show everything after this heading at deeper levels."
26321 (outline-flag-region
26322 (point)
26323 (save-excursion
26324 (outline-end-of-subtree) (outline-next-heading) (point))
26325 nil))
26327 (defun org-show-entry ()
26328 "Show the body directly following this heading.
26329 Show the heading too, if it is currently invisible."
26330 (interactive)
26331 (save-excursion
26332 (condition-case nil
26333 (progn
26334 (org-back-to-heading t)
26335 (outline-flag-region
26336 (max (point-min) (1- (point)))
26337 (save-excursion
26338 (re-search-forward
26339 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
26340 (or (match-beginning 1) (point-max)))
26341 nil))
26342 (error nil))))
26344 (defun org-make-options-regexp (kwds)
26345 "Make a regular expression for keyword lines."
26346 (concat
26348 "#?[ \t]*\\+\\("
26349 (mapconcat 'regexp-quote kwds "\\|")
26350 "\\):[ \t]*"
26351 "\\(.+\\)"))
26353 ;; Make isearch reveal the necessary context
26354 (defun org-isearch-end ()
26355 "Reveal context after isearch exits."
26356 (when isearch-success ; only if search was successful
26357 (if (featurep 'xemacs)
26358 ;; Under XEmacs, the hook is run in the correct place,
26359 ;; we directly show the context.
26360 (org-show-context 'isearch)
26361 ;; In Emacs the hook runs *before* restoring the overlays.
26362 ;; So we have to use a one-time post-command-hook to do this.
26363 ;; (Emacs 22 has a special variable, see function `org-mode')
26364 (unless (and (boundp 'isearch-mode-end-hook-quit)
26365 isearch-mode-end-hook-quit)
26366 ;; Only when the isearch was not quitted.
26367 (org-add-hook 'post-command-hook 'org-isearch-post-command
26368 'append 'local)))))
26370 (defun org-isearch-post-command ()
26371 "Remove self from hook, and show context."
26372 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
26373 (org-show-context 'isearch))
26376 ;;;; Address problems with some other packages
26378 ;; Make flyspell not check words in links, to not mess up our keymap
26379 (defun org-mode-flyspell-verify ()
26380 "Don't let flyspell put overlays at active buttons."
26381 (not (get-text-property (point) 'keymap)))
26383 ;; Make `bookmark-jump' show the jump location if it was hidden.
26384 (eval-after-load "bookmark"
26385 '(if (boundp 'bookmark-after-jump-hook)
26386 ;; We can use the hook
26387 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
26388 ;; Hook not available, use advice
26389 (defadvice bookmark-jump (after org-make-visible activate)
26390 "Make the position visible."
26391 (org-bookmark-jump-unhide))))
26393 (defun org-bookmark-jump-unhide ()
26394 "Unhide the current position, to show the bookmark location."
26395 (and (org-mode-p)
26396 (or (org-invisible-p)
26397 (save-excursion (goto-char (max (point-min) (1- (point))))
26398 (org-invisible-p)))
26399 (org-show-context 'bookmark-jump)))
26401 ;; Make session.el ignore our circular variable
26402 (eval-after-load "session"
26403 '(add-to-list 'session-globals-exclude 'org-mark-ring))
26405 ;;;; Experimental code
26407 (defun org-closed-in-range ()
26408 "Sparse tree of items closed in a certain time range.
26409 Still experimental, may disappear in the furture."
26410 (interactive)
26411 ;; Get the time interval from the user.
26412 (let* ((time1 (time-to-seconds
26413 (org-read-date nil 'to-time nil "Starting date: ")))
26414 (time2 (time-to-seconds
26415 (org-read-date nil 'to-time nil "End date:")))
26416 ;; callback function
26417 (callback (lambda ()
26418 (let ((time
26419 (time-to-seconds
26420 (apply 'encode-time
26421 (org-parse-time-string
26422 (match-string 1))))))
26423 ;; check if time in interval
26424 (and (>= time time1) (<= time time2))))))
26425 ;; make tree, check each match with the callback
26426 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
26428 (defun org-fill-paragraph-experimental (&optional justify)
26429 "Re-align a table, pass through to fill-paragraph if no table."
26430 (let ((table-p (org-at-table-p))
26431 (table.el-p (org-at-table.el-p)))
26432 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26433 (table.el-p t) ; skip table.el tables
26434 (table-p (org-table-align) t) ; align org-mode tables
26435 ((save-excursion
26436 (let ((pos (1+ (point-at-eol))))
26437 (backward-paragraph 1)
26438 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
26439 (save-excursion
26440 (save-restriction
26441 (narrow-to-region (1+ (match-end 0)) (point-max))
26442 (fill-paragraph nil)
26443 t)))
26444 (t nil)))) ; call paragraph-fill
26446 ;; FIXME: this needs a much better algorithm
26447 (defun org-assign-fast-keys (alist)
26448 "Assign fast keys to a keyword-key alist.
26449 Respect keys that are already there."
26450 (let (new e k c c1 c2 (char ?a))
26451 (while (setq e (pop alist))
26452 (cond
26453 ((equal e '(:startgroup)) (push e new))
26454 ((equal e '(:endgroup)) (push e new))
26456 (setq k (car e) c2 nil)
26457 (if (cdr e)
26458 (setq c (cdr e))
26459 ;; automatically assign a character.
26460 (setq c1 (string-to-char
26461 (downcase (substring
26462 k (if (= (string-to-char k) ?@) 1 0)))))
26463 (if (or (rassoc c1 new) (rassoc c1 alist))
26464 (while (or (rassoc char new) (rassoc char alist))
26465 (setq char (1+ char)))
26466 (setq c2 c1))
26467 (setq c (or c2 char)))
26468 (push (cons k c) new))))
26469 (nreverse new)))
26471 ;(defcustom org-read-date-prefer-future nil
26472 ; "Non-nil means, when reading an incomplete date from the user, assume future.
26473 ;This affects the following situations:
26474 ;1. The user give a day, but no month.
26475 ; In this case, if the day number if after today, the current month will
26476 ; be used, otherwise the next month.
26477 ;2. The user gives a month but not a year.
26478 ; In this case, the the given month is after the current month, the current
26479 ; year will be used. Otherwise the next year will be used.;
26481 ;When nil, always the current month and year will be used."
26482 ; :group 'org-time ;????
26483 ; :type 'boolean)
26486 ;;;; Finish up
26488 (provide 'org)
26490 (run-hooks 'org-load-hook)
26492 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
26493 ;;; org.el ends here