Release 5.15
[org-mode.git] / org.el
blob83eb90742ca881be24f27aeda3f646e618599a7e
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.15
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.15"
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 nil
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 (defcustom org-show-entry-below '((default . nil))
430 "Non-nil means, show the entry below a headline when revealing a location.
431 Org-mode often shows locations in an org-mode file which might have
432 been invisible before. When this is set, the text below the headline that is
433 exposed is also shown.
435 By default this is off for all contexts.
436 Instead of t, this can also be an alist specifying this option for different
437 contexts. See `org-show-hierarchy-above' for valid contexts."
438 :group 'org-reveal-location
439 :type '(choice
440 (const :tag "Always" t)
441 (const :tag "Never" nil)
442 (repeat :greedy t :tag "Individual contexts"
443 (cons
444 (choice :tag "Context"
445 (const agenda)
446 (const org-goto)
447 (const occur-tree)
448 (const tags-tree)
449 (const link-search)
450 (const mark-goto)
451 (const bookmark-jump)
452 (const isearch)
453 (const default))
454 (boolean)))))
456 (defgroup org-cycle nil
457 "Options concerning visibility cycling in Org-mode."
458 :tag "Org Cycle"
459 :group 'org-structure)
461 (defcustom org-drawers '("PROPERTIES" "CLOCK")
462 "Names of drawers. Drawers are not opened by cycling on the headline above.
463 Drawers only open with a TAB on the drawer line itself. A drawer looks like
464 this:
465 :DRAWERNAME:
466 .....
467 :END:
468 The drawer \"PROPERTIES\" is special for capturing properties through
469 the property API.
471 Drawers can be defined on the per-file basis with a line like:
473 #+DRAWERS: HIDDEN STATE PROPERTIES"
474 :group 'org-structure
475 :type '(repeat (string :tag "Drawer Name")))
477 (defcustom org-cycle-global-at-bob nil
478 "Cycle globally if cursor is at beginning of buffer and not at a headline.
479 This makes it possible to do global cycling without having to use S-TAB or
480 C-u TAB. For this special case to work, the first line of the buffer
481 must not be a headline - it may be empty ot some other text. When used in
482 this way, `org-cycle-hook' is disables temporarily, to make sure the
483 cursor stays at the beginning of the buffer.
484 When this option is nil, don't do anything special at the beginning
485 of the buffer."
486 :group 'org-cycle
487 :type 'boolean)
489 (defcustom org-cycle-emulate-tab t
490 "Where should `org-cycle' emulate TAB.
491 nil Never
492 white Only in completely white lines
493 whitestart Only at the beginning of lines, before the first non-white char.
494 t Everywhere except in headlines
495 exc-hl-bol Everywhere except at the start of a headline
496 If TAB is used in a place where it does not emulate TAB, the current subtree
497 visibility is cycled."
498 :group 'org-cycle
499 :type '(choice (const :tag "Never" nil)
500 (const :tag "Only in completely white lines" white)
501 (const :tag "Before first char in a line" whitestart)
502 (const :tag "Everywhere except in headlines" t)
503 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
506 (defcustom org-cycle-separator-lines 2
507 "Number of empty lines needed to keep an empty line between collapsed trees.
508 If you leave an empty line between the end of a subtree and the following
509 headline, this empty line is hidden when the subtree is folded.
510 Org-mode will leave (exactly) one empty line visible if the number of
511 empty lines is equal or larger to the number given in this variable.
512 So the default 2 means, at least 2 empty lines after the end of a subtree
513 are needed to produce free space between a collapsed subtree and the
514 following headline.
516 Special case: when 0, never leave empty lines in collapsed view."
517 :group 'org-cycle
518 :type 'integer)
520 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
521 org-cycle-hide-drawers
522 org-cycle-show-empty-lines
523 org-optimize-window-after-visibility-change)
524 "Hook that is run after `org-cycle' has changed the buffer visibility.
525 The function(s) in this hook must accept a single argument which indicates
526 the new state that was set by the most recent `org-cycle' command. The
527 argument is a symbol. After a global state change, it can have the values
528 `overview', `content', or `all'. After a local state change, it can have
529 the values `folded', `children', or `subtree'."
530 :group 'org-cycle
531 :type 'hook)
533 (defgroup org-edit-structure nil
534 "Options concerning structure editing in Org-mode."
535 :tag "Org Edit Structure"
536 :group 'org-structure)
538 (defcustom org-special-ctrl-a/e nil
539 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
540 When t, `C-a' will bring back the cursor to the beginning of the
541 headline text, i.e. after the stars and after a possible TODO keyword.
542 In an item, this will be the position after the bullet.
543 When the cursor is already at that position, another `C-a' will bring
544 it to the beginning of the line.
545 `C-e' will jump to the end of the headline, ignoring the presence of tags
546 in the headline. A second `C-e' will then jump to the true end of the
547 line, after any tags.
548 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
549 and only a directly following, identical keypress will bring the cursor
550 to the special positions."
551 :group 'org-edit-structure
552 :type '(choice
553 (const :tag "off" nil)
554 (const :tag "after bullet first" t)
555 (const :tag "border first" reversed)))
557 (if (fboundp 'defvaralias)
558 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
560 (defcustom org-odd-levels-only nil
561 "Non-nil means, skip even levels and only use odd levels for the outline.
562 This has the effect that two stars are being added/taken away in
563 promotion/demotion commands. It also influences how levels are
564 handled by the exporters.
565 Changing it requires restart of `font-lock-mode' to become effective
566 for fontification also in regions already fontified.
567 You may also set this on a per-file basis by adding one of the following
568 lines to the buffer:
570 #+STARTUP: odd
571 #+STARTUP: oddeven"
572 :group 'org-edit-structure
573 :group 'org-font-lock
574 :type 'boolean)
576 (defcustom org-adapt-indentation t
577 "Non-nil means, adapt indentation when promoting and demoting.
578 When this is set and the *entire* text in an entry is indented, the
579 indentation is increased by one space in a demotion command, and
580 decreased by one in a promotion command. If any line in the entry
581 body starts at column 0, indentation is not changed at all."
582 :group 'org-edit-structure
583 :type 'boolean)
585 (defcustom org-blank-before-new-entry '((heading . nil)
586 (plain-list-item . nil))
587 "Should `org-insert-heading' leave a blank line before new heading/item?
588 The value is an alist, with `heading' and `plain-list-item' as car,
589 and a boolean flag as cdr."
590 :group 'org-edit-structure
591 :type '(list
592 (cons (const heading) (boolean))
593 (cons (const plain-list-item) (boolean))))
595 (defcustom org-insert-heading-hook nil
596 "Hook being run after inserting a new heading."
597 :group 'org-edit-structure
598 :type 'hook)
600 (defcustom org-enable-fixed-width-editor t
601 "Non-nil means, lines starting with \":\" are treated as fixed-width.
602 This currently only means, they are never auto-wrapped.
603 When nil, such lines will be treated like ordinary lines.
604 See also the QUOTE keyword."
605 :group 'org-edit-structure
606 :type 'boolean)
608 (defgroup org-sparse-trees nil
609 "Options concerning sparse trees in Org-mode."
610 :tag "Org Sparse Trees"
611 :group 'org-structure)
613 (defcustom org-highlight-sparse-tree-matches t
614 "Non-nil means, highlight all matches that define a sparse tree.
615 The highlights will automatically disappear the next time the buffer is
616 changed by an edit command."
617 :group 'org-sparse-trees
618 :type 'boolean)
620 (defcustom org-remove-highlights-with-change t
621 "Non-nil means, any change to the buffer will remove temporary highlights.
622 Such highlights are created by `org-occur' and `org-clock-display'.
623 When nil, `C-c C-c needs to be used to get rid of the highlights.
624 The highlights created by `org-preview-latex-fragment' always need
625 `C-c C-c' to be removed."
626 :group 'org-sparse-trees
627 :group 'org-time
628 :type 'boolean)
631 (defcustom org-occur-hook '(org-first-headline-recenter)
632 "Hook that is run after `org-occur' has constructed a sparse tree.
633 This can be used to recenter the window to show as much of the structure
634 as possible."
635 :group 'org-sparse-trees
636 :type 'hook)
638 (defgroup org-plain-lists nil
639 "Options concerning plain lists in Org-mode."
640 :tag "Org Plain lists"
641 :group 'org-structure)
643 (defcustom org-cycle-include-plain-lists nil
644 "Non-nil means, include plain lists into visibility cycling.
645 This means that during cycling, plain list items will *temporarily* be
646 interpreted as outline headlines with a level given by 1000+i where i is the
647 indentation of the bullet. In all other operations, plain list items are
648 not seen as headlines. For example, you cannot assign a TODO keyword to
649 such an item."
650 :group 'org-plain-lists
651 :type 'boolean)
653 (defcustom org-plain-list-ordered-item-terminator t
654 "The character that makes a line with leading number an ordered list item.
655 Valid values are ?. and ?\). To get both terminators, use t. While
656 ?. may look nicer, it creates the danger that a line with leading
657 number may be incorrectly interpreted as an item. ?\) therefore is
658 the safe choice."
659 :group 'org-plain-lists
660 :type '(choice (const :tag "dot like in \"2.\"" ?.)
661 (const :tag "paren like in \"2)\"" ?\))
662 (const :tab "both" t)))
664 (defcustom org-auto-renumber-ordered-lists t
665 "Non-nil means, automatically renumber ordered plain lists.
666 Renumbering happens when the sequence have been changed with
667 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
668 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
669 :group 'org-plain-lists
670 :type 'boolean)
672 (defcustom org-provide-checkbox-statistics t
673 "Non-nil means, update checkbox statistics after insert and toggle.
674 When this is set, checkbox statistics is updated each time you either insert
675 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
676 with \\[org-ctrl-c-ctrl-c\\]."
677 :group 'org-plain-lists
678 :type 'boolean)
680 (defgroup org-archive nil
681 "Options concerning archiving in Org-mode."
682 :tag "Org Archive"
683 :group 'org-structure)
685 (defcustom org-archive-tag "ARCHIVE"
686 "The tag that marks a subtree as archived.
687 An archived subtree does not open during visibility cycling, and does
688 not contribute to the agenda listings.
689 After changing this, font-lock must be restarted in the relevant buffers to
690 get the proper fontification."
691 :group 'org-archive
692 :group 'org-keywords
693 :type 'string)
695 (defcustom org-agenda-skip-archived-trees t
696 "Non-nil means, the agenda will skip any items located in archived trees.
697 An archived tree is a tree marked with the tag ARCHIVE."
698 :group 'org-archive
699 :group 'org-agenda-skip
700 :type 'boolean)
702 (defcustom org-cycle-open-archived-trees nil
703 "Non-nil means, `org-cycle' will open archived trees.
704 An archived tree is a tree marked with the tag ARCHIVE.
705 When nil, archived trees will stay folded. You can still open them with
706 normal outline commands like `show-all', but not with the cycling commands."
707 :group 'org-archive
708 :group 'org-cycle
709 :type 'boolean)
711 (defcustom org-sparse-tree-open-archived-trees nil
712 "Non-nil means sparse tree construction shows matches in archived trees.
713 When nil, matches in these trees are highlighted, but the trees are kept in
714 collapsed state."
715 :group 'org-archive
716 :group 'org-sparse-trees
717 :type 'boolean)
719 (defcustom org-archive-location "%s_archive::"
720 "The location where subtrees should be archived.
721 This string consists of two parts, separated by a double-colon.
723 The first part is a file name - when omitted, archiving happens in the same
724 file. %s will be replaced by the current file name (without directory part).
725 Archiving to a different file is useful to keep archived entries from
726 contributing to the Org-mode Agenda.
728 The part after the double colon is a headline. The archived entries will be
729 filed under that headline. When omitted, the subtrees are simply filed away
730 at the end of the file, as top-level entries.
732 Here are a few examples:
733 \"%s_archive::\"
734 If the current file is Projects.org, archive in file
735 Projects.org_archive, as top-level trees. This is the default.
737 \"::* Archived Tasks\"
738 Archive in the current file, under the top-level headline
739 \"* Archived Tasks\".
741 \"~/org/archive.org::\"
742 Archive in file ~/org/archive.org (absolute path), as top-level trees.
744 \"basement::** Finished Tasks\"
745 Archive in file ./basement (relative path), as level 3 trees
746 below the level 2 heading \"** Finished Tasks\".
748 You may set this option on a per-file basis by adding to the buffer a
749 line like
751 #+ARCHIVE: basement::** Finished Tasks"
752 :group 'org-archive
753 :type 'string)
755 (defcustom org-archive-mark-done t
756 "Non-nil means, mark entries as DONE when they are moved to the archive file.
757 This can be a string to set the keyword to use. When t, Org-mode will
758 use the first keyword in its list that means done."
759 :group 'org-archive
760 :type '(choice
761 (const :tag "No" nil)
762 (const :tag "Yes" t)
763 (string :tag "Use this keyword")))
765 (defcustom org-archive-stamp-time t
766 "Non-nil means, add a time stamp to entries moved to an archive file.
767 This variable is obsolete and has no effect anymore, instead add ot remove
768 `time' from the variablle `org-archive-save-context-info'."
769 :group 'org-archive
770 :type 'boolean)
772 (defcustom org-archive-save-context-info '(time file category todo itags)
773 "Parts of context info that should be stored as properties when archiving.
774 When a subtree is moved to an archive file, it looses information given by
775 context, like inherited tags, the category, and possibly also the TODO
776 state (depending on the variable `org-archive-mark-done').
777 This variable can be a list of any of the following symbols:
779 time The time of archiving.
780 file The file where the entry originates.
781 itags The local tags, in the headline of the subtree.
782 ltags The tags the subtree inherits from further up the hierarchy.
783 todo The pre-archive TODO state.
784 category The category, taken from file name or #+CATEGORY lines.
786 For each symbol present in the list, a property will be created in
787 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
788 information."
789 :group 'org-archive
790 :type '(set :greedy t
791 (const :tag "Time" time)
792 (const :tag "File" file)
793 (const :tag "Category" category)
794 (const :tag "TODO state" todo)
795 (const :tag "TODO state" priority)
796 (const :tag "Inherited tags" itags)
797 (const :tag "Local tags" ltags)))
799 (defgroup org-table nil
800 "Options concerning tables in Org-mode."
801 :tag "Org Table"
802 :group 'org)
804 (defcustom org-enable-table-editor 'optimized
805 "Non-nil means, lines starting with \"|\" are handled by the table editor.
806 When nil, such lines will be treated like ordinary lines.
808 When equal to the symbol `optimized', the table editor will be optimized to
809 do the following:
810 - Automatic overwrite mode in front of whitespace in table fields.
811 This makes the structure of the table stay in tact as long as the edited
812 field does not exceed the column width.
813 - Minimize the number of realigns. Normally, the table is aligned each time
814 TAB or RET are pressed to move to another field. With optimization this
815 happens only if changes to a field might have changed the column width.
816 Optimization requires replacing the functions `self-insert-command',
817 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
818 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
819 very good at guessing when a re-align will be necessary, but you can always
820 force one with \\[org-ctrl-c-ctrl-c].
822 If you would like to use the optimized version in Org-mode, but the
823 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
825 This variable can be used to turn on and off the table editor during a session,
826 but in order to toggle optimization, a restart is required.
828 See also the variable `org-table-auto-blank-field'."
829 :group 'org-table
830 :type '(choice
831 (const :tag "off" nil)
832 (const :tag "on" t)
833 (const :tag "on, optimized" optimized)))
835 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
836 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
837 In the optimized version, the table editor takes over all simple keys that
838 normally just insert a character. In tables, the characters are inserted
839 in a way to minimize disturbing the table structure (i.e. in overwrite mode
840 for empty fields). Outside tables, the correct binding of the keys is
841 restored.
843 The default for this option is t if the optimized version is also used in
844 Org-mode. See the variable `org-enable-table-editor' for details. Changing
845 this variable requires a restart of Emacs to become effective."
846 :group 'org-table
847 :type 'boolean)
849 (defcustom orgtbl-radio-table-templates
850 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
851 % END RECEIVE ORGTBL %n
852 \\begin{comment}
853 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
854 | | |
855 \\end{comment}\n")
856 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
857 @c END RECEIVE ORGTBL %n
858 @ignore
859 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
860 | | |
861 @end ignore\n")
862 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
863 <!-- END RECEIVE ORGTBL %n -->
864 <!--
865 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
866 | | |
867 -->\n"))
868 "Templates for radio tables in different major modes.
869 All occurrences of %n in a template will be replaced with the name of the
870 table, obtained by prompting the user."
871 :group 'org-table
872 :type '(repeat
873 (list (symbol :tag "Major mode")
874 (string :tag "Format"))))
876 (defgroup org-table-settings nil
877 "Settings for tables in Org-mode."
878 :tag "Org Table Settings"
879 :group 'org-table)
881 (defcustom org-table-default-size "5x2"
882 "The default size for newly created tables, Columns x Rows."
883 :group 'org-table-settings
884 :type 'string)
886 (defcustom org-table-number-regexp
887 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
888 "Regular expression for recognizing numbers in table columns.
889 If a table column contains mostly numbers, it will be aligned to the
890 right. If not, it will be aligned to the left.
892 The default value of this option is a regular expression which allows
893 anything which looks remotely like a number as used in scientific
894 context. For example, all of the following will be considered a
895 number:
896 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
898 Other options offered by the customize interface are more restrictive."
899 :group 'org-table-settings
900 :type '(choice
901 (const :tag "Positive Integers"
902 "^[0-9]+$")
903 (const :tag "Integers"
904 "^[-+]?[0-9]+$")
905 (const :tag "Floating Point Numbers"
906 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
907 (const :tag "Floating Point Number or Integer"
908 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
909 (const :tag "Exponential, Floating point, Integer"
910 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
911 (const :tag "Very General Number-Like, including hex"
912 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
913 (string :tag "Regexp:")))
915 (defcustom org-table-number-fraction 0.5
916 "Fraction of numbers in a column required to make the column align right.
917 In a column all non-white fields are considered. If at least this
918 fraction of fields is matched by `org-table-number-fraction',
919 alignment to the right border applies."
920 :group 'org-table-settings
921 :type 'number)
923 (defgroup org-table-editing nil
924 "Behavior of tables during editing in Org-mode."
925 :tag "Org Table Editing"
926 :group 'org-table)
928 (defcustom org-table-automatic-realign t
929 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
930 When nil, aligning is only done with \\[org-table-align], or after column
931 removal/insertion."
932 :group 'org-table-editing
933 :type 'boolean)
935 (defcustom org-table-auto-blank-field t
936 "Non-nil means, automatically blank table field when starting to type into it.
937 This only happens when typing immediately after a field motion
938 command (TAB, S-TAB or RET).
939 Only relevant when `org-enable-table-editor' is equal to `optimized'."
940 :group 'org-table-editing
941 :type 'boolean)
943 (defcustom org-table-tab-jumps-over-hlines t
944 "Non-nil means, tab in the last column of a table with jump over a hline.
945 If a horizontal separator line is following the current line,
946 `org-table-next-field' can either create a new row before that line, or jump
947 over the line. When this option is nil, a new line will be created before
948 this line."
949 :group 'org-table-editing
950 :type 'boolean)
952 (defcustom org-table-tab-recognizes-table.el t
953 "Non-nil means, TAB will automatically notice a table.el table.
954 When it sees such a table, it moves point into it and - if necessary -
955 calls `table-recognize-table'."
956 :group 'org-table-editing
957 :type 'boolean)
959 (defgroup org-table-calculation nil
960 "Options concerning tables in Org-mode."
961 :tag "Org Table Calculation"
962 :group 'org-table)
964 (defcustom org-table-use-standard-references t
965 "Should org-mode work with table refrences like B3 instead of @3$2?
966 Possible values are:
967 nil never use them
968 from accept as input, do not present for editing
969 t: accept as input and present for editing"
970 :group 'org-table-calculation
971 :type '(choice
972 (const :tag "Never, don't even check unser input for them" nil)
973 (const :tag "Always, both as user input, and when editing" t)
974 (const :tag "Convert user input, don't offer during editing" 'from)))
976 (defcustom org-table-copy-increment t
977 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
978 :group 'org-table-calculation
979 :type 'boolean)
981 (defcustom org-calc-default-modes
982 '(calc-internal-prec 12
983 calc-float-format (float 5)
984 calc-angle-mode deg
985 calc-prefer-frac nil
986 calc-symbolic-mode nil
987 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
988 calc-display-working-message t
990 "List with Calc mode settings for use in calc-eval for table formulas.
991 The list must contain alternating symbols (Calc modes variables and values).
992 Don't remove any of the default settings, just change the values. Org-mode
993 relies on the variables to be present in the list."
994 :group 'org-table-calculation
995 :type 'plist)
997 (defcustom org-table-formula-evaluate-inline t
998 "Non-nil means, TAB and RET evaluate a formula in current table field.
999 If the current field starts with an equal sign, it is assumed to be a formula
1000 which should be evaluated as described in the manual and in the documentation
1001 string of the command `org-table-eval-formula'. This feature requires the
1002 Emacs calc package.
1003 When this variable is nil, formula calculation is only available through
1004 the command \\[org-table-eval-formula]."
1005 :group 'org-table-calculation
1006 :type 'boolean)
1008 (defcustom org-table-formula-use-constants t
1009 "Non-nil means, interpret constants in formulas in tables.
1010 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1011 by the value given in `org-table-formula-constants', or by a value obtained
1012 from the `constants.el' package."
1013 :group 'org-table-calculation
1014 :type 'boolean)
1016 (defcustom org-table-formula-constants nil
1017 "Alist with constant names and values, for use in table formulas.
1018 The car of each element is a name of a constant, without the `$' before it.
1019 The cdr is the value as a string. For example, if you'd like to use the
1020 speed of light in a formula, you would configure
1022 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1024 and then use it in an equation like `$1*$c'.
1026 Constants can also be defined on a per-file basis using a line like
1028 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1029 :group 'org-table-calculation
1030 :type '(repeat
1031 (cons (string :tag "name")
1032 (string :tag "value"))))
1034 (defvar org-table-formula-constants-local nil
1035 "Local version of `org-table-formula-constants'.")
1036 (make-variable-buffer-local 'org-table-formula-constants-local)
1038 (defcustom org-table-allow-automatic-line-recalculation t
1039 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1040 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1041 :group 'org-table-calculation
1042 :type 'boolean)
1044 (defgroup org-link nil
1045 "Options concerning links in Org-mode."
1046 :tag "Org Link"
1047 :group 'org)
1049 (defvar org-link-abbrev-alist-local nil
1050 "Buffer-local version of `org-link-abbrev-alist', which see.
1051 The value of this is taken from the #+LINK lines.")
1052 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1054 (defcustom org-link-abbrev-alist nil
1055 "Alist of link abbreviations.
1056 The car of each element is a string, to be replaced at the start of a link.
1057 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1058 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1060 [[linkkey:tag][description]]
1062 If REPLACE is a string, the tag will simply be appended to create the link.
1063 If the string contains \"%s\", the tag will be inserted there. REPLACE may
1064 also be a function that will be called with the tag as the only argument to
1065 create the link. See the manual for examples."
1066 :group 'org-link
1067 :type 'alist)
1069 (defcustom org-descriptive-links t
1070 "Non-nil means, hide link part and only show description of bracket links.
1071 Bracket links are like [[link][descritpion]]. This variable sets the initial
1072 state in new org-mode buffers. The setting can then be toggled on a
1073 per-buffer basis from the Org->Hyperlinks menu."
1074 :group 'org-link
1075 :type 'boolean)
1077 (defcustom org-link-file-path-type 'adaptive
1078 "How the path name in file links should be stored.
1079 Valid values are:
1081 relative relative to the current directory, i.e. the directory of the file
1082 into which the link is being inserted.
1083 absolute absolute path, if possible with ~ for home directory.
1084 noabbrev absolute path, no abbreviation of home directory.
1085 adaptive Use relative path for files in the current directory and sub-
1086 directories of it. For other files, use an absolute path."
1087 :group 'org-link
1088 :type '(choice
1089 (const relative)
1090 (const absolute)
1091 (const noabbrev)
1092 (const adaptive)))
1094 (defcustom org-activate-links '(bracket angle plain radio tag date)
1095 "Types of links that should be activated in Org-mode files.
1096 This is a list of symbols, each leading to the activation of a certain link
1097 type. In principle, it does not hurt to turn on most link types - there may
1098 be a small gain when turning off unused link types. The types are:
1100 bracket The recommended [[link][description]] or [[link]] links with hiding.
1101 angular Links in angular brackes that may contain whitespace like
1102 <bbdb:Carsten Dominik>.
1103 plain Plain links in normal text, no whitespace, like http://google.com.
1104 radio Text that is matched by a radio target, see manual for details.
1105 tag Tag settings in a headline (link to tag search).
1106 date Time stamps (link to calendar).
1108 Changing this variable requires a restart of Emacs to become effective."
1109 :group 'org-link
1110 :type '(set (const :tag "Double bracket links (new style)" bracket)
1111 (const :tag "Angular bracket links (old style)" angular)
1112 (const :tag "plain text links" plain)
1113 (const :tag "Radio target matches" radio)
1114 (const :tag "Tags" tag)
1115 (const :tag "Tags" target)
1116 (const :tag "Timestamps" date)))
1118 (defgroup org-link-store nil
1119 "Options concerning storing links in Org-mode"
1120 :tag "Org Store Link"
1121 :group 'org-link)
1123 (defcustom org-email-link-description-format "Email %c: %.30s"
1124 "Format of the description part of a link to an email or usenet message.
1125 The following %-excapes will be replaced by corresponding information:
1127 %F full \"From\" field
1128 %f name, taken from \"From\" field, address if no name
1129 %T full \"To\" field
1130 %t first name in \"To\" field, address if no name
1131 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1132 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1133 %s subject
1134 %m message-id.
1136 You may use normal field width specification between the % and the letter.
1137 This is for example useful to limit the length of the subject.
1139 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1140 :group 'org-link-store
1141 :type 'string)
1143 (defcustom org-from-is-user-regexp
1144 (let (r1 r2)
1145 (when (and user-mail-address (not (string= user-mail-address "")))
1146 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1147 (when (and user-full-name (not (string= user-full-name "")))
1148 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1149 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1150 "Regexp mached against the \"From:\" header of an email or usenet message.
1151 It should match if the message is from the user him/herself."
1152 :group 'org-link-store
1153 :type 'regexp)
1155 (defcustom org-context-in-file-links t
1156 "Non-nil means, file links from `org-store-link' contain context.
1157 A search string will be added to the file name with :: as separator and
1158 used to find the context when the link is activated by the command
1159 `org-open-at-point'.
1160 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1161 negates this setting for the duration of the command."
1162 :group 'org-link-store
1163 :type 'boolean)
1165 (defcustom org-keep-stored-link-after-insertion nil
1166 "Non-nil means, keep link in list for entire session.
1168 The command `org-store-link' adds a link pointing to the current
1169 location to an internal list. These links accumulate during a session.
1170 The command `org-insert-link' can be used to insert links into any
1171 Org-mode file (offering completion for all stored links). When this
1172 option is nil, every link which has been inserted once using \\[org-insert-link]
1173 will be removed from the list, to make completing the unused links
1174 more efficient."
1175 :group 'org-link-store
1176 :type 'boolean)
1178 (defcustom org-usenet-links-prefer-google nil
1179 "Non-nil means, `org-store-link' will create web links to Google groups.
1180 When nil, Gnus will be used for such links.
1181 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1182 negates this setting for the duration of the command."
1183 :group 'org-link-store
1184 :type 'boolean)
1186 (defgroup org-link-follow nil
1187 "Options concerning following links in Org-mode"
1188 :tag "Org Follow Link"
1189 :group 'org-link)
1191 (defcustom org-tab-follows-link nil
1192 "Non-nil means, on links TAB will follow the link.
1193 Needs to be set before org.el is loaded."
1194 :group 'org-link-follow
1195 :type 'boolean)
1197 (defcustom org-return-follows-link nil
1198 "Non-nil means, on links RET will follow the link.
1199 Needs to be set before org.el is loaded."
1200 :group 'org-link-follow
1201 :type 'boolean)
1203 (defcustom org-mouse-1-follows-link t
1204 "Non-nil means, mouse-1 on a link will follow the link.
1205 A longer mouse click will still set point. Does not wortk on XEmacs.
1206 Needs to be set before org.el is loaded."
1207 :group 'org-link-follow
1208 :type 'boolean)
1210 (defcustom org-mark-ring-length 4
1211 "Number of different positions to be recorded in the ring
1212 Changing this requires a restart of Emacs to work correctly."
1213 :group 'org-link-follow
1214 :type 'interger)
1216 (defcustom org-link-frame-setup
1217 '((vm . vm-visit-folder-other-frame)
1218 (gnus . gnus-other-frame)
1219 (file . find-file-other-window))
1220 "Setup the frame configuration for following links.
1221 When following a link with Emacs, it may often be useful to display
1222 this link in another window or frame. This variable can be used to
1223 set this up for the different types of links.
1224 For VM, use any of
1225 `vm-visit-folder'
1226 `vm-visit-folder-other-frame'
1227 For Gnus, use any of
1228 `gnus'
1229 `gnus-other-frame'
1230 For FILE, use any of
1231 `find-file'
1232 `find-file-other-window'
1233 `find-file-other-frame'
1234 For the calendar, use the variable `calendar-setup'.
1235 For BBDB, it is currently only possible to display the matches in
1236 another window."
1237 :group 'org-link-follow
1238 :type '(list
1239 (cons (const vm)
1240 (choice
1241 (const vm-visit-folder)
1242 (const vm-visit-folder-other-window)
1243 (const vm-visit-folder-other-frame)))
1244 (cons (const gnus)
1245 (choice
1246 (const gnus)
1247 (const gnus-other-frame)))
1248 (cons (const file)
1249 (choice
1250 (const find-file)
1251 (const find-file-other-window)
1252 (const find-file-other-frame)))))
1254 (defcustom org-display-internal-link-with-indirect-buffer nil
1255 "Non-nil means, use indirect buffer to display infile links.
1256 Activating internal links (from one location in a file to another location
1257 in the same file) normally just jumps to the location. When the link is
1258 activated with a C-u prefix (or with mouse-3), the link is displayed in
1259 another window. When this option is set, the other window actually displays
1260 an indirect buffer clone of the current buffer, to avoid any visibility
1261 changes to the current buffer."
1262 :group 'org-link-follow
1263 :type 'boolean)
1265 (defcustom org-open-non-existing-files nil
1266 "Non-nil means, `org-open-file' will open non-existing files.
1267 When nil, an error will be generated."
1268 :group 'org-link-follow
1269 :type 'boolean)
1271 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1272 "Function and arguments to call for following mailto links.
1273 This is a list with the first element being a lisp function, and the
1274 remaining elements being arguments to the function. In string arguments,
1275 %a will be replaced by the address, and %s will be replaced by the subject
1276 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1277 :group 'org-link-follow
1278 :type '(choice
1279 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1280 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1281 (const :tag "message-mail" (message-mail "%a" "%s"))
1282 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1284 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1285 "Non-nil means, ask for confirmation before executing shell links.
1286 Shell links can be dangerous: just think about a link
1288 [[shell:rm -rf ~/*][Google Search]]
1290 This link would show up in your Org-mode document as \"Google Search\",
1291 but really it would remove your entire home directory.
1292 Therefore we advise against setting this variable to nil.
1293 Just change it to `y-or-n-p' of you want to confirm with a
1294 single keystroke rather than having to type \"yes\"."
1295 :group 'org-link-follow
1296 :type '(choice
1297 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1298 (const :tag "with y-or-n (faster)" y-or-n-p)
1299 (const :tag "no confirmation (dangerous)" nil)))
1301 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1302 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1303 Elisp links can be dangerous: just think about a link
1305 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1307 This link would show up in your Org-mode document as \"Google Search\",
1308 but really it would remove your entire home directory.
1309 Therefore we advise against setting this variable to nil.
1310 Just change it to `y-or-n-p' of you want to confirm with a
1311 single keystroke rather than having to type \"yes\"."
1312 :group 'org-link-follow
1313 :type '(choice
1314 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1315 (const :tag "with y-or-n (faster)" y-or-n-p)
1316 (const :tag "no confirmation (dangerous)" nil)))
1318 (defconst org-file-apps-defaults-gnu
1319 '((remote . emacs)
1320 (t . mailcap))
1321 "Default file applications on a UNIX or GNU/Linux system.
1322 See `org-file-apps'.")
1324 (defconst org-file-apps-defaults-macosx
1325 '((remote . emacs)
1326 (t . "open %s")
1327 ("ps" . "gv %s")
1328 ("ps.gz" . "gv %s")
1329 ("eps" . "gv %s")
1330 ("eps.gz" . "gv %s")
1331 ("dvi" . "xdvi %s")
1332 ("fig" . "xfig %s"))
1333 "Default file applications on a MacOS X system.
1334 The system \"open\" is known as a default, but we use X11 applications
1335 for some files for which the OS does not have a good default.
1336 See `org-file-apps'.")
1338 (defconst org-file-apps-defaults-windowsnt
1339 (list
1340 '(remote . emacs)
1341 (cons t
1342 (list (if (featurep 'xemacs)
1343 'mswindows-shell-execute
1344 'w32-shell-execute)
1345 "open" 'file)))
1346 "Default file applications on a Windows NT system.
1347 The system \"open\" is used for most files.
1348 See `org-file-apps'.")
1350 (defcustom org-file-apps
1352 ("txt" . emacs)
1353 ("tex" . emacs)
1354 ("ltx" . emacs)
1355 ("org" . emacs)
1356 ("el" . emacs)
1357 ("bib" . emacs)
1359 "External applications for opening `file:path' items in a document.
1360 Org-mode uses system defaults for different file types, but
1361 you can use this variable to set the application for a given file
1362 extension. The entries in this list are cons cells where the car identifies
1363 files and the cdr the corresponding command. Possible values for the
1364 file identifier are
1365 \"ext\" A string identifying an extension
1366 `directory' Matches a directory
1367 `remote' Matches a remote file, accessible through tramp or efs.
1368 Remote files most likely should be visited through Emacs
1369 because external applications cannot handle such paths.
1370 t Default for all remaining files
1372 Possible values for the command are:
1373 `emacs' The file will be visited by the current Emacs process.
1374 `default' Use the default application for this file type.
1375 string A command to be executed by a shell; %s will be replaced
1376 by the path to the file.
1377 sexp A Lisp form which will be evaluated. The file path will
1378 be available in the Lisp variable `file'.
1379 For more examples, see the system specific constants
1380 `org-file-apps-defaults-macosx'
1381 `org-file-apps-defaults-windowsnt'
1382 `org-file-apps-defaults-gnu'."
1383 :group 'org-link-follow
1384 :type '(repeat
1385 (cons (choice :value ""
1386 (string :tag "Extension")
1387 (const :tag "Default for unrecognized files" t)
1388 (const :tag "Remote file" remote)
1389 (const :tag "Links to a directory" directory))
1390 (choice :value ""
1391 (const :tag "Visit with Emacs" emacs)
1392 (const :tag "Use system default" default)
1393 (string :tag "Command")
1394 (sexp :tag "Lisp form")))))
1396 (defcustom org-mhe-search-all-folders nil
1397 "Non-nil means, that the search for the mh-message will be extended to
1398 all folders if the message cannot be found in the folder given in the link.
1399 Searching all folders is very efficient with one of the search engines
1400 supported by MH-E, but will be slow with pick."
1401 :group 'org-link-follow
1402 :type 'boolean)
1404 (defgroup org-remember nil
1405 "Options concerning interaction with remember.el."
1406 :tag "Org Remember"
1407 :group 'org)
1409 (defcustom org-directory "~/org"
1410 "Directory with org files.
1411 This directory will be used as default to prompt for org files.
1412 Used by the hooks for remember.el."
1413 :group 'org-remember
1414 :type 'directory)
1416 (defcustom org-default-notes-file "~/.notes"
1417 "Default target for storing notes.
1418 Used by the hooks for remember.el. This can be a string, or nil to mean
1419 the value of `remember-data-file'.
1420 You can set this on a per-template basis with the variable
1421 `org-remember-templates'."
1422 :group 'org-remember
1423 :type '(choice
1424 (const :tag "Default from remember-data-file" nil)
1425 file))
1427 (defcustom org-remember-store-without-prompt t
1428 "Non-nil means, `C-c C-c' stores remember note without further promts.
1429 In this case, you need `C-u C-c C-c' to get the prompts for
1430 note file and headline.
1431 When this variable is nil, `C-c C-c' give you the prompts, and
1432 `C-u C-c C-c' trigger the fasttrack."
1433 :group 'org-remember
1434 :type 'boolean)
1436 (defcustom org-remember-default-headline ""
1437 "The headline that should be the default location in the notes file.
1438 When filing remember notes, the cursor will start at that position.
1439 You can set this on a per-template basis with the variable
1440 `org-remember-templates'."
1441 :group 'org-remember
1442 :type 'string)
1444 (defcustom org-remember-templates nil
1445 "Templates for the creation of remember buffers.
1446 When nil, just let remember make the buffer.
1447 When not nil, this is a list of 5-element lists. In each entry, the first
1448 element is a the name of the template, It should be a single short word.
1449 The second element is a character, a unique key to select this template.
1450 The third element is the template. The forth element is optional and can
1451 specify a destination file for remember items created with this template.
1452 The default file is given by `org-default-notes-file'. An optional fifth
1453 element can specify the headline in that file that should be offered
1454 first when the user is asked to file the entry. The default headline is
1455 given in the variable `org-remember-default-headline'.
1457 The template specifies the structure of the remember buffer. It should have
1458 a first line starting with a star, to act as the org-mode headline.
1459 Furthermore, the following %-escapes will be replaced with content:
1461 %^{prompt} prompt the user for a string and replace this sequence with it.
1462 %t time stamp, date only
1463 %T time stamp with date and time
1464 %u, %U like the above, but inactive time stamps
1465 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1466 You may define a prompt like %^{Please specify birthday}t
1467 %n user name (taken from `user-full-name')
1468 %a annotation, normally the link created with org-store-link
1469 %i initial content, the region when remember is called with C-u.
1470 If %i is indented, the entire inserted text will be indented
1471 as well.
1473 %? After completing the template, position cursor here.
1475 Apart from these general escapes, you can access information specific to the
1476 link type that is created. For example, calling `remember' in emails or gnus
1477 will record the author and the subject of the message, which you can access
1478 with %:author and %:subject, respectively. Here is a complete list of what
1479 is recorded for each link type.
1481 Link type | Available information
1482 -------------------+------------------------------------------------------
1483 bbdb | %:type %:name %:company
1484 vm, wl, mh, rmail | %:type %:subject %:message-id
1485 | %:from %:fromname %:fromaddress
1486 | %:to %:toname %:toaddress
1487 | %:fromto (either \"to NAME\" or \"from NAME\")
1488 gnus | %:group, for messages also all email fields
1489 w3, w3m | %:type %:url
1490 info | %:type %:file %:node
1491 calendar | %:type %:date"
1492 :group 'org-remember
1493 :get (lambda (var) ; Make sure all entries have 5 elements
1494 (mapcar (lambda (x)
1495 (if (not (stringp (car x))) (setq x (cons "" x)))
1496 (cond ((= (length x) 4) (append x '("")))
1497 ((= (length x) 3) (append x '("" "")))
1498 (t x)))
1499 (default-value var)))
1500 :type '(repeat
1501 :tag "enabled"
1502 (list :value ("" ?a "\n" nil nil)
1503 (string :tag "Name")
1504 (character :tag "Selection Key")
1505 (string :tag "Template")
1506 (choice
1507 (file :tag "Destination file")
1508 (const :tag "Prompt for file" nil))
1509 (choice
1510 (string :tag "Destination headline")
1511 (const :tag "Selection interface for heading")))))
1513 (defcustom org-reverse-note-order nil
1514 "Non-nil means, store new notes at the beginning of a file or entry.
1515 When nil, new notes will be filed to the end of a file or entry.
1516 This can also be a list with cons cells of regular expressions that
1517 are matched against file names, and values."
1518 :group 'org-remember
1519 :type '(choice
1520 (const :tag "Reverse always" t)
1521 (const :tag "Reverse never" nil)
1522 (repeat :tag "By file name regexp"
1523 (cons regexp boolean))))
1525 (defgroup org-todo nil
1526 "Options concerning TODO items in Org-mode."
1527 :tag "Org TODO"
1528 :group 'org)
1530 (defgroup org-progress nil
1531 "Options concerning Progress logging in Org-mode."
1532 :tag "Org Progress"
1533 :group 'org-time)
1535 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1536 "List of TODO entry keyword sequences and their interpretation.
1537 \\<org-mode-map>This is a list of sequences.
1539 Each sequence starts with a symbol, either `sequence' or `type',
1540 indicating if the keywords should be interpreted as a sequence of
1541 action steps, or as different types of TODO items. The first
1542 keywords are states requiring action - these states will select a headline
1543 for inclusion into the global TODO list Org-mode produces. If one of
1544 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1545 signify that no further action is necessary. If \"|\" is not found,
1546 the last keyword is treated as the only DONE state of the sequence.
1548 The command \\[org-todo] cycles an entry through these states, and one
1549 additional state where no keyword is present. For details about this
1550 cycling, see the manual.
1552 TODO keywords and interpretation can also be set on a per-file basis with
1553 the special #+SEQ_TODO and #+TYP_TODO lines.
1555 For backward compatibility, this variable may also be just a list
1556 of keywords - in this case the interptetation (sequence or type) will be
1557 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1558 :group 'org-todo
1559 :group 'org-keywords
1560 :type '(choice
1561 (repeat :tag "Old syntax, just keywords"
1562 (string :tag "Keyword"))
1563 (repeat :tag "New syntax"
1564 (cons
1565 (choice
1566 :tag "Interpretation"
1567 (const :tag "Sequence (cycling hits every state)" sequence)
1568 (const :tag "Type (cycling directly to DONE)" type))
1569 (repeat
1570 (string :tag "Keyword"))))))
1572 (defvar org-todo-keywords-1 nil)
1573 (make-variable-buffer-local 'org-todo-keywords-1)
1574 (defvar org-todo-keywords-for-agenda nil)
1575 (defvar org-done-keywords-for-agenda nil)
1576 (defvar org-not-done-keywords nil)
1577 (make-variable-buffer-local 'org-not-done-keywords)
1578 (defvar org-done-keywords nil)
1579 (make-variable-buffer-local 'org-done-keywords)
1580 (defvar org-todo-heads nil)
1581 (make-variable-buffer-local 'org-todo-heads)
1582 (defvar org-todo-sets nil)
1583 (make-variable-buffer-local 'org-todo-sets)
1584 (defvar org-todo-log-states nil)
1585 (make-variable-buffer-local 'org-todo-log-states)
1586 (defvar org-todo-kwd-alist nil)
1587 (make-variable-buffer-local 'org-todo-kwd-alist)
1588 (defvar org-todo-key-alist nil)
1589 (make-variable-buffer-local 'org-todo-key-alist)
1590 (defvar org-todo-key-trigger nil)
1591 (make-variable-buffer-local 'org-todo-key-trigger)
1593 (defcustom org-todo-interpretation 'sequence
1594 "Controls how TODO keywords are interpreted.
1595 This variable is in principle obsolete and is only used for
1596 backward compatibility, if the interpretation of todo keywords is
1597 not given already in `org-todo-keywords'. See that variable for
1598 more information."
1599 :group 'org-todo
1600 :group 'org-keywords
1601 :type '(choice (const sequence)
1602 (const type)))
1604 (defcustom org-use-fast-todo-selection 'prefix
1605 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1606 This variable describes if and under what circumstances the cycling
1607 mechanism for TODO keywords will be replaced by a single-key, direct
1608 selection scheme.
1610 When nil, fast selection is never used.
1612 When the symbol `prefix', it will be used when `org-todo' is called with
1613 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1614 in an agenda buffer.
1616 When t, fast selection is used by default. In this case, the prefix
1617 argument forces cycling instead.
1619 In all cases, the special interface is only used if access keys have actually
1620 been assigned by the user, i.e. if keywords in the configuration are followed
1621 by a letter in parenthesis, like TODO(t)."
1622 :group 'org-todo
1623 :type '(choice
1624 (const :tag "Never" nil)
1625 (const :tag "By default" t)
1626 (const :tag "Only with C-u C-c C-t" prefix)))
1628 (defcustom org-after-todo-state-change-hook nil
1629 "Hook which is run after the state of a TODO item was changed.
1630 The new state (a string with a TODO keyword, or nil) is available in the
1631 Lisp variable `state'."
1632 :group 'org-todo
1633 :type 'hook)
1635 (defcustom org-log-done nil
1636 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1637 When the state of an entry is changed from nothing or a DONE state to
1638 a not-done TODO state, remove a previous closing date.
1640 This can also be a list of symbols indicating under which conditions
1641 the time stamp recording the action should be annotated with a short note.
1642 Valid members of this list are
1644 done Offer to record a note when marking entries done
1645 state Offer to record a note whenever changing the TODO state
1646 of an item. This is only relevant if TODO keywords are
1647 interpreted as sequence, see variable `org-todo-interpretation'.
1648 When `state' is set, this includes tracking `done'.
1649 clock-out Offer to record a note when clocking out of an item.
1651 A separate window will then pop up and allow you to type a note.
1652 After finishing with C-c C-c, the note will be added directly after the
1653 timestamp, as a plain list item. See also the variable
1654 `org-log-note-headings'.
1656 Logging can also be configured on a per-file basis by adding one of
1657 the following lines anywhere in the buffer:
1659 #+STARTUP: logdone
1660 #+STARTUP: nologging
1661 #+STARTUP: lognotedone
1662 #+STARTUP: lognotestate
1663 #+STARTUP: lognoteclock-out
1665 You can have local logging settings for a subtree by setting the LOGGING
1666 property to one or more of these keywords."
1667 :group 'org-todo
1668 :group 'org-progress
1669 :type '(choice
1670 (const :tag "off" nil)
1671 (const :tag "on" t)
1672 (set :tag "on, with notes, detailed control" :greedy t :value (done)
1673 (const :tag "when item is marked DONE" done)
1674 (const :tag "when TODO state changes" state)
1675 (const :tag "when clocking out" clock-out))))
1677 (defcustom org-log-done-with-time t
1678 "Non-nil means, the CLOSED time stamp will contain date and time.
1679 When nil, only the date will be recorded."
1680 :group 'org-progress
1681 :type 'boolean)
1683 (defcustom org-log-note-headings
1684 '((done . "CLOSING NOTE %t")
1685 (state . "State %-12s %t")
1686 (clock-out . ""))
1687 "Headings for notes added when clocking out or closing TODO items.
1688 The value is an alist, with the car being a symbol indicating the note
1689 context, and the cdr is the heading to be used. The heading may also be the
1690 empty string.
1691 %t in the heading will be replaced by a time stamp.
1692 %s will be replaced by the new TODO state, in double quotes.
1693 %u will be replaced by the user name.
1694 %U will be replaced by the full user name."
1695 :group 'org-todo
1696 :group 'org-progress
1697 :type '(list :greedy t
1698 (cons (const :tag "Heading when closing an item" done) string)
1699 (cons (const :tag
1700 "Heading when changing todo state (todo sequence only)"
1701 state) string)
1702 (cons (const :tag "Heading when clocking out" clock-out) string)))
1704 (defcustom org-log-states-order-reversed t
1705 "Non-nil means, the latest state change note will be directly after heading.
1706 When nil, the notes will be orderer according to time."
1707 :group 'org-todo
1708 :group 'org-progress
1709 :type 'boolean)
1711 (defcustom org-log-repeat t
1712 "Non-nil means, prompt for a note when REPEAT is resetting a TODO entry.
1713 When nil, no note will be taken.
1714 This option can also be set with on a per-file-basis with
1716 #+STARTUP: logrepeat
1717 #+STARTUP: nologrepeat
1719 You can have local logging settings for a subtree by setting the LOGGING
1720 property to one or more of these keywords."
1721 :group 'org-todo
1722 :group 'org-progress
1723 :type 'boolean)
1725 (defcustom org-clock-into-drawer 2
1726 "Should clocking info be wrapped into a drawer?
1727 When t, clocking info will always be inserted into a :CLOCK: drawer.
1728 If necessary, the drawer will be created.
1729 When nil, the drawer will not be created, but used when present.
1730 When an integer and the number of clocking entries in an item
1731 reaches or exceeds this number, a drawer will be created."
1732 :group 'org-todo
1733 :group 'org-progress
1734 :type '(choice
1735 (const :tag "Always" t)
1736 (const :tag "Only when drawer exists" nil)
1737 (integer :tag "When at least N clock entries")))
1739 (defcustom org-clock-out-when-done t
1740 "When t, the clock will be stopped when the relevant entry is marked DONE.
1741 Nil means, clock will keep running until stopped explicitly with
1742 `C-c C-x C-o', or until the clock is started in a different item."
1743 :group 'org-progress
1744 :type 'boolean)
1746 (defgroup org-priorities nil
1747 "Priorities in Org-mode."
1748 :tag "Org Priorities"
1749 :group 'org-todo)
1751 (defcustom org-highest-priority ?A
1752 "The highest priority of TODO items. A character like ?A, ?B etc.
1753 Must have a smaller ASCII number than `org-lowest-priority'."
1754 :group 'org-priorities
1755 :type 'character)
1757 (defcustom org-lowest-priority ?C
1758 "The lowest priority of TODO items. A character like ?A, ?B etc.
1759 Must have a larger ASCII number than `org-highest-priority'."
1760 :group 'org-priorities
1761 :type 'character)
1763 (defcustom org-default-priority ?B
1764 "The default priority of TODO items.
1765 This is the priority an item get if no explicit priority is given."
1766 :group 'org-priorities
1767 :type 'character)
1769 (defcustom org-priority-start-cycle-with-default t
1770 "Non-nil means, start with default priority when starting to cycle.
1771 When this is nil, the first step in the cycle will be (depending on the
1772 command used) one higher or lower that the default priority."
1773 :group 'org-priorities
1774 :type 'boolean)
1776 (defgroup org-time nil
1777 "Options concerning time stamps and deadlines in Org-mode."
1778 :tag "Org Time"
1779 :group 'org)
1781 (defcustom org-insert-labeled-timestamps-at-point nil
1782 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1783 When nil, these labeled time stamps are forces into the second line of an
1784 entry, just after the headline. When scheduling from the global TODO list,
1785 the time stamp will always be forced into the second line."
1786 :group 'org-time
1787 :type 'boolean)
1789 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1790 "Formats for `format-time-string' which are used for time stamps.
1791 It is not recommended to change this constant.")
1793 (defcustom org-time-stamp-rounding-minutes 0
1794 "Number of minutes to round time stamps to upon insertion.
1795 When zero, insert the time unmodified. Useful rounding numbers
1796 should be factors of 60, so for example 5, 10, 15.
1797 When this is not zero, you can still force an exact time-stamp by using
1798 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1799 :group 'org-time
1800 :type 'integer)
1802 (defcustom org-display-custom-times nil
1803 "Non-nil means, overlay custom formats over all time stamps.
1804 The formats are defined through the variable `org-time-stamp-custom-formats'.
1805 To turn this on on a per-file basis, insert anywhere in the file:
1806 #+STARTUP: customtime"
1807 :group 'org-time
1808 :set 'set-default
1809 :type 'sexp)
1810 (make-variable-buffer-local 'org-display-custom-times)
1812 (defcustom org-time-stamp-custom-formats
1813 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1814 "Custom formats for time stamps. See `format-time-string' for the syntax.
1815 These are overlayed over the default ISO format if the variable
1816 `org-display-custom-times' is set. Time like %H:%M should be at the
1817 end of the second format."
1818 :group 'org-time
1819 :type 'sexp)
1821 (defun org-time-stamp-format (&optional long inactive)
1822 "Get the right format for a time string."
1823 (let ((f (if long (cdr org-time-stamp-formats)
1824 (car org-time-stamp-formats))))
1825 (if inactive
1826 (concat "[" (substring f 1 -1) "]")
1827 f)))
1829 (defcustom org-read-date-prefer-future t
1830 "Non-nil means, assume future for incomplete date input from user.
1831 This affects the following situations:
1832 1. The user gives a day, but no month.
1833 For example, if today is the 15th, and you enter \"3\", Org-mode will
1834 read this as the third of *next* month. However, if you enter \"17\",
1835 it will be considered as *this* month.
1836 2. The user gives a month but not a year.
1837 For example, if it is april and you enter \"feb 2\", this will be read
1838 as feb 2, *next* year. \"May 5\", however, will be this year.
1840 When this option is nil, the current month and year will always be used
1841 as defaults."
1842 :group 'org-time
1843 :type 'boolean)
1845 (defcustom org-read-date-display-live t
1846 "Non-nil means, display current interpretation of date prompt live.
1847 This display will be in an overlay, in the minibuffer."
1848 :group 'org-time
1849 :type 'boolean)
1851 (defcustom org-read-date-popup-calendar t
1852 "Non-nil means, pop up a calendar when prompting for a date.
1853 In the calendar, the date can be selected with mouse-1. However, the
1854 minibuffer will also be active, and you can simply enter the date as well.
1855 When nil, only the minibuffer will be available."
1856 :group 'org-time
1857 :type 'boolean)
1858 (if (fboundp 'defvaralias)
1859 (defvaralias 'org-popup-calendar-for-date-prompt
1860 'org-read-date-popup-calendar))
1862 (defcustom org-extend-today-until 0
1863 "The hour when your day really ends.
1864 This has influence for the following applications:
1865 - When switching the agenda to \"today\". It it is still earlier than
1866 the time given here, the day recognized as TODAY is actually yesterday.
1867 - When a date is read from the user and it is still before the time given
1868 here, the current date and time will be assumed to be yesterday, 23:59.
1870 FIXME:
1871 IMPORTANT: This is still a very experimental feature, it may disappear
1872 again or it may be extended to mean more things."
1873 :group 'org-time
1874 :type 'number)
1876 (defcustom org-edit-timestamp-down-means-later nil
1877 "Non-nil means, S-down will increase the time in a time stamp.
1878 When nil, S-up will increase."
1879 :group 'org-time
1880 :type 'boolean)
1882 (defcustom org-calendar-follow-timestamp-change t
1883 "Non-nil means, make the calendar window follow timestamp changes.
1884 When a timestamp is modified and the calendar window is visible, it will be
1885 moved to the new date."
1886 :group 'org-time
1887 :type 'boolean)
1889 (defcustom org-clock-heading-function nil
1890 "When non-nil, should be a function to create `org-clock-heading'.
1891 This is the string shown in the mode line when a clock is running.
1892 The function is called with point at the beginning of the headline."
1893 :group 'org-time ; FIXME: Should we have a separate group????
1894 :type 'function)
1896 (defgroup org-tags nil
1897 "Options concerning tags in Org-mode."
1898 :tag "Org Tags"
1899 :group 'org)
1901 (defcustom org-tag-alist nil
1902 "List of tags allowed in Org-mode files.
1903 When this list is nil, Org-mode will base TAG input on what is already in the
1904 buffer.
1905 The value of this variable is an alist, the car of each entry must be a
1906 keyword as a string, the cdr may be a character that is used to select
1907 that tag through the fast-tag-selection interface.
1908 See the manual for details."
1909 :group 'org-tags
1910 :type '(repeat
1911 (choice
1912 (cons (string :tag "Tag name")
1913 (character :tag "Access char"))
1914 (const :tag "Start radio group" (:startgroup))
1915 (const :tag "End radio group" (:endgroup)))))
1917 (defcustom org-use-fast-tag-selection 'auto
1918 "Non-nil means, use fast tag selection scheme.
1919 This is a special interface to select and deselect tags with single keys.
1920 When nil, fast selection is never used.
1921 When the symbol `auto', fast selection is used if and only if selection
1922 characters for tags have been configured, either through the variable
1923 `org-tag-alist' or through a #+TAGS line in the buffer.
1924 When t, fast selection is always used and selection keys are assigned
1925 automatically if necessary."
1926 :group 'org-tags
1927 :type '(choice
1928 (const :tag "Always" t)
1929 (const :tag "Never" nil)
1930 (const :tag "When selection characters are configured" 'auto)))
1932 (defcustom org-fast-tag-selection-single-key nil
1933 "Non-nil means, fast tag selection exits after first change.
1934 When nil, you have to press RET to exit it.
1935 During fast tag selection, you can toggle this flag with `C-c'.
1936 This variable can also have the value `expert'. In this case, the window
1937 displaying the tags menu is not even shown, until you press C-c again."
1938 :group 'org-tags
1939 :type '(choice
1940 (const :tag "No" nil)
1941 (const :tag "Yes" t)
1942 (const :tag "Expert" expert)))
1944 (defvar org-fast-tag-selection-include-todo nil
1945 "Non-nil means, fast tags selection interface will also offer TODO states.
1946 This is an undocumented feature, you should not rely on it.")
1948 (defcustom org-tags-column -80
1949 "The column to which tags should be indented in a headline.
1950 If this number is positive, it specifies the column. If it is negative,
1951 it means that the tags should be flushright to that column. For example,
1952 -80 works well for a normal 80 character screen."
1953 :group 'org-tags
1954 :type 'integer)
1956 (defcustom org-auto-align-tags t
1957 "Non-nil means, realign tags after pro/demotion of TODO state change.
1958 These operations change the length of a headline and therefore shift
1959 the tags around. With this options turned on, after each such operation
1960 the tags are again aligned to `org-tags-column'."
1961 :group 'org-tags
1962 :type 'boolean)
1964 (defcustom org-use-tag-inheritance t
1965 "Non-nil means, tags in levels apply also for sublevels.
1966 When nil, only the tags directly given in a specific line apply there.
1967 If you turn off this option, you very likely want to turn on the
1968 companion option `org-tags-match-list-sublevels'."
1969 :group 'org-tags
1970 :type 'boolean)
1972 (defcustom org-tags-match-list-sublevels nil
1973 "Non-nil means list also sublevels of headlines matching tag search.
1974 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1975 the sublevels of a headline matching a tag search often also match
1976 the same search. Listing all of them can create very long lists.
1977 Setting this variable to nil causes subtrees of a match to be skipped.
1978 This option is off by default, because inheritance in on. If you turn
1979 inheritance off, you very likely want to turn this option on.
1981 As a special case, if the tag search is restricted to TODO items, the
1982 value of this variable is ignored and sublevels are always checked, to
1983 make sure all corresponding TODO items find their way into the list."
1984 :group 'org-tags
1985 :type 'boolean)
1987 (defvar org-tags-history nil
1988 "History of minibuffer reads for tags.")
1989 (defvar org-last-tags-completion-table nil
1990 "The last used completion table for tags.")
1991 (defvar org-after-tags-change-hook nil
1992 "Hook that is run after the tags in a line have changed.")
1994 (defgroup org-properties nil
1995 "Options concerning properties in Org-mode."
1996 :tag "Org Properties"
1997 :group 'org)
1999 (defcustom org-property-format "%-10s %s"
2000 "How property key/value pairs should be formatted by `indent-line'.
2001 When `indent-line' hits a property definition, it will format the line
2002 according to this format, mainly to make sure that the values are
2003 lined-up with respect to each other."
2004 :group 'org-properties
2005 :type 'string)
2007 (defcustom org-use-property-inheritance nil
2008 "Non-nil means, properties apply also for sublevels.
2009 This setting is only relevant during property searches, not when querying
2010 an entry with `org-entry-get'. To retrieve a property with inheritance,
2011 you need to call `org-entry-get' with the inheritance flag.
2012 Turning this on can cause significant overhead when doing a search, so
2013 this is turned off by default.
2014 When nil, only the properties directly given in the current entry count.
2015 The value may also be a list of properties that shouldhave inheritance.
2017 However, note that some special properties use inheritance under special
2018 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2019 and the properties ending in \"_ALL\" when they are used as descriptor
2020 for valid values of a property."
2021 :group 'org-properties
2022 :type '(choice
2023 (const :tag "Not" nil)
2024 (const :tag "Always" nil)
2025 (repeat :tag "Specific properties")))
2027 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2028 "The default column format, if no other format has been defined.
2029 This variable can be set on the per-file basis by inserting a line
2031 #+COLUMNS: %25ITEM ....."
2032 :group 'org-properties
2033 :type 'string)
2035 (defcustom org-global-properties nil
2036 "List of property/value pairs that can be inherited by any entry.
2037 You can set buffer-local values for this by adding lines like
2039 #+PROPERTY: NAME VALUE"
2040 :group 'org-properties
2041 :type '(repeat
2042 (cons (string :tag "Property")
2043 (string :tag "Value"))))
2045 (defvar org-local-properties nil
2046 "List of property/value pairs that can be inherited by any entry.
2047 Valid for the current buffer.
2048 This variable is populated from #+PROPERTY lines.")
2050 (defgroup org-agenda nil
2051 "Options concerning agenda views in Org-mode."
2052 :tag "Org Agenda"
2053 :group 'org)
2055 (defvar org-category nil
2056 "Variable used by org files to set a category for agenda display.
2057 Such files should use a file variable to set it, for example
2059 # -*- mode: org; org-category: \"ELisp\"
2061 or contain a special line
2063 #+CATEGORY: ELisp
2065 If the file does not specify a category, then file's base name
2066 is used instead.")
2067 (make-variable-buffer-local 'org-category)
2069 (defcustom org-agenda-files nil
2070 "The files to be used for agenda display.
2071 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2072 \\[org-remove-file]. You can also use customize to edit the list.
2074 If an entry is a directory, all files in that directory that are matched by
2075 `org-agenda-file-regexp' will be part of the file list.
2077 If the value of the variable is not a list but a single file name, then
2078 the list of agenda files is actually stored and maintained in that file, one
2079 agenda file per line."
2080 :group 'org-agenda
2081 :type '(choice
2082 (repeat :tag "List of files and directories" file)
2083 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2085 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2086 "Regular expression to match files for `org-agenda-files'.
2087 If any element in the list in that variable contains a directory instead
2088 of a normal file, all files in that directory that are matched by this
2089 regular expression will be included."
2090 :group 'org-agenda
2091 :type 'regexp)
2093 (defcustom org-agenda-skip-unavailable-files nil
2094 "t means to just skip non-reachable files in `org-agenda-files'.
2095 Nil means to remove them, after a query, from the list."
2096 :group 'org-agenda
2097 :type 'boolean)
2099 (defcustom org-agenda-multi-occur-extra-files nil
2100 "List of extra files to be searched by `org-occur-in-agenda-files'.
2101 The files in `org-agenda-files' are always searched."
2102 :group 'org-agenda
2103 :type '(repeat file))
2105 (defcustom org-agenda-confirm-kill 1
2106 "When set, remote killing from the agenda buffer needs confirmation.
2107 When t, a confirmation is always needed. When a number N, confirmation is
2108 only needed when the text to be killed contains more than N non-white lines."
2109 :group 'org-agenda
2110 :type '(choice
2111 (const :tag "Never" nil)
2112 (const :tag "Always" t)
2113 (number :tag "When more than N lines")))
2115 (defcustom org-calendar-to-agenda-key [?c]
2116 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2117 The command `org-calendar-goto-agenda' will be bound to this key. The
2118 default is the character `c' because then `c' can be used to switch back and
2119 forth between agenda and calendar."
2120 :group 'org-agenda
2121 :type 'sexp)
2123 (defcustom org-agenda-compact-blocks nil
2124 "Non-nil means, make the block agenda more compact.
2125 This is done by leaving out unnecessary lines."
2126 :group 'org-agenda
2127 :type nil)
2129 (defgroup org-agenda-export nil
2130 "Options concerning exporting agenda views in Org-mode."
2131 :tag "Org Agenda Export"
2132 :group 'org-agenda)
2134 (defcustom org-agenda-with-colors t
2135 "Non-nil means, use colors in agenda views."
2136 :group 'org-agenda-export
2137 :type 'boolean)
2139 (defcustom org-agenda-exporter-settings nil
2140 "Alist of variable/value pairs that should be active during agenda export.
2141 This is a good place to set uptions for ps-print and for htmlize."
2142 :group 'org-agenda-export
2143 :type '(repeat
2144 (list
2145 (variable)
2146 (sexp :tag "Value"))))
2148 (defcustom org-agenda-export-html-style ""
2149 "The style specification for exported HTML Agenda files.
2150 If this variable contains a string, it will replace the default <style>
2151 section as produced by `htmlize'.
2152 Since there are different ways of setting style information, this variable
2153 needs to contain the full HTML structure to provide a style, including the
2154 surrounding HTML tags. The style specifications should include definitions
2155 the fonts used by the agenda, here is an example:
2157 <style type=\"text/css\">
2158 p { font-weight: normal; color: gray; }
2159 .org-agenda-structure {
2160 font-size: 110%;
2161 color: #003399;
2162 font-weight: 600;
2164 .org-todo {
2165 color: #cc6666;Week-agenda:
2166 font-weight: bold;
2168 .org-done {
2169 color: #339933;
2171 .title { text-align: center; }
2172 .todo, .deadline { color: red; }
2173 .done { color: green; }
2174 </style>
2176 or, if you want to keep the style in a file,
2178 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2180 As the value of this option simply gets inserted into the HTML <head> header,
2181 you can \"misuse\" it to also add other text to the header. However,
2182 <style>...</style> is required, if not present the variable will be ignored."
2183 :group 'org-agenda-export
2184 :group 'org-export-html
2185 :type 'string)
2187 (defgroup org-agenda-custom-commands nil
2188 "Options concerning agenda views in Org-mode."
2189 :tag "Org Agenda Custom Commands"
2190 :group 'org-agenda)
2192 (defcustom org-agenda-custom-commands nil
2193 "Custom commands for the agenda.
2194 These commands will be offered on the splash screen displayed by the
2195 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2197 (key desc type match options files)
2199 key The key (one or more characters as a string) to be associated
2200 with the command.
2201 desc A description of the commend, when omitted or nil, a default
2202 description is built using MATCH.
2203 type The command type, any of the following symbols:
2204 todo Entries with a specific TODO keyword, in all agenda files.
2205 tags Tags match in all agenda files.
2206 tags-todo Tags match in all agenda files, TODO entries only.
2207 todo-tree Sparse tree of specific TODO keyword in *current* file.
2208 tags-tree Sparse tree with all tags matches in *current* file.
2209 occur-tree Occur sparse tree for *current* file.
2210 ... A user-defined function.
2211 match What to search for:
2212 - a single keyword for TODO keyword searches
2213 - a tags match expression for tags searches
2214 - a regular expression for occur searches
2215 options A list of option settings, similar to that in a let form, so like
2216 this: ((opt1 val1) (opt2 val2) ...)
2217 files A list of files file to write the produced agenda buffer to
2218 with the command `org-store-agenda-views'.
2219 If a file name ends in \".html\", an HTML version of the buffer
2220 is written out. If it ends in \".ps\", a postscript version is
2221 produced. Otherwide, only the plain text is written to the file.
2223 You can also define a set of commands, to create a composite agenda buffer.
2224 In this case, an entry looks like this:
2226 (key desc (cmd1 cmd2 ...) general-options file)
2228 where
2230 desc A description string to be displayed in the dispatcher menu.
2231 cmd An agenda command, similar to the above. However, tree commands
2232 are no allowed, but instead you can get agenda and global todo list.
2233 So valid commands for a set are:
2234 (agenda)
2235 (alltodo)
2236 (stuck)
2237 (todo \"match\" options files)
2238 (tags \"match\" options files)
2239 (tags-todo \"match\" options files)
2241 Each command can carry a list of options, and another set of options can be
2242 given for the whole set of commands. Individual command options take
2243 precedence over the general options.
2245 When using several characters as key to a command, the first characters
2246 are prefix commands. For the dispatcher to display useful information, you
2247 should provide a description for the prefix, like
2249 (setq org-agenda-custom-commands
2250 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2251 (\"hl\" tags \"+HOME+Lisa\")
2252 (\"hp\" tags \"+HOME+Peter\")
2253 (\"hk\" tags \"+HOME+Kim\")))"
2254 :group 'org-agenda-custom-commands
2255 :type '(repeat
2256 (choice :value ("a" "" tags "" nil)
2257 (list :tag "Single command"
2258 (string :tag "Access Key(s) ")
2259 (option (string :tag "Description"))
2260 (choice
2261 (const :tag "Agenda" agenda)
2262 (const :tag "TODO list" alltodo)
2263 (const :tag "Stuck projects" stuck)
2264 (const :tag "Tags search (all agenda files)" tags)
2265 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2266 (const :tag "TODO keyword search (all agenda files)" todo)
2267 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2268 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2269 (const :tag "Occur tree (current buffer)" occur-tree)
2270 (sexp :tag "Other, user-defined function"))
2271 (string :tag "Match")
2272 (repeat :tag "Local options"
2273 (list (variable :tag "Option") (sexp :tag "Value")))
2274 (option (repeat :tag "Export" (file :tag "Export to"))))
2275 (list :tag "Command series, all agenda files"
2276 (string :tag "Access Key(s)")
2277 (string :tag "Description ")
2278 (repeat
2279 (choice
2280 (const :tag "Agenda" (agenda))
2281 (const :tag "TODO list" (alltodo))
2282 (const :tag "Stuck projects" (stuck))
2283 (list :tag "Tags search"
2284 (const :format "" tags)
2285 (string :tag "Match")
2286 (repeat :tag "Local options"
2287 (list (variable :tag "Option")
2288 (sexp :tag "Value"))))
2290 (list :tag "Tags search, TODO entries only"
2291 (const :format "" tags-todo)
2292 (string :tag "Match")
2293 (repeat :tag "Local options"
2294 (list (variable :tag "Option")
2295 (sexp :tag "Value"))))
2297 (list :tag "TODO keyword search"
2298 (const :format "" todo)
2299 (string :tag "Match")
2300 (repeat :tag "Local options"
2301 (list (variable :tag "Option")
2302 (sexp :tag "Value"))))
2304 (list :tag "Other, user-defined function"
2305 (symbol :tag "function")
2306 (string :tag "Match")
2307 (repeat :tag "Local options"
2308 (list (variable :tag "Option")
2309 (sexp :tag "Value"))))))
2311 (repeat :tag "General options"
2312 (list (variable :tag "Option")
2313 (sexp :tag "Value")))
2314 (option (repeat :tag "Export" (file :tag "Export to"))))
2315 (cons :tag "Prefix key documentation"
2316 (string :tag "Access Key(s)")
2317 (string :tag "Description ")))))
2319 (defcustom org-stuck-projects
2320 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2321 "How to identify stuck projects.
2322 This is a list of four items:
2323 1. A tags/todo matcher string that is used to identify a project.
2324 The entire tree below a headline matched by this is considered one project.
2325 2. A list of TODO keywords identifying non-stuck projects.
2326 If the project subtree contains any headline with one of these todo
2327 keywords, the project is considered to be not stuck. If you specify
2328 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2329 3. A list of tags identifying non-stuck projects.
2330 If the project subtree contains any headline with one of these tags,
2331 the project is considered to be not stuck. If you specify \"*\" as
2332 a tag, any tag will mark the project unstuck.
2333 4. An arbitrary regular expression matching non-stuck projects.
2335 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2336 or `C-c a #' to produce the list."
2337 :group 'org-agenda-custom-commands
2338 :type '(list
2339 (string :tag "Tags/TODO match to identify a project")
2340 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2341 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2342 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2345 (defgroup org-agenda-skip nil
2346 "Options concerning skipping parts of agenda files."
2347 :tag "Org Agenda Skip"
2348 :group 'org-agenda)
2350 (defcustom org-agenda-todo-list-sublevels t
2351 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2352 When nil, the sublevels of a TODO entry are not checked, resulting in
2353 potentially much shorter TODO lists."
2354 :group 'org-agenda-skip
2355 :group 'org-todo
2356 :type 'boolean)
2358 (defcustom org-agenda-todo-ignore-with-date nil
2359 "Non-nil means, don't show entries with a date in the global todo list.
2360 You can use this if you prefer to mark mere appointments with a TODO keyword,
2361 but don't want them to show up in the TODO list.
2362 When this is set, it also covers deadlines and scheduled items, the settings
2363 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2364 will be ignored."
2365 :group 'org-agenda-skip
2366 :group 'org-todo
2367 :type 'boolean)
2369 (defcustom org-agenda-todo-ignore-scheduled nil
2370 "Non-nil means, don't show scheduled entries in the global todo list.
2371 The idea behind this is that by scheduling it, you have already taken care
2372 of this item.
2373 See also `org-agenda-todo-ignore-with-date'."
2374 :group 'org-agenda-skip
2375 :group 'org-todo
2376 :type 'boolean)
2378 (defcustom org-agenda-todo-ignore-deadlines nil
2379 "Non-nil means, don't show near deadline entries in the global todo list.
2380 Near means closer than `org-deadline-warning-days' days.
2381 The idea behind this is that such items will appear in the agenda anyway.
2382 See also `org-agenda-todo-ignore-with-date'."
2383 :group 'org-agenda-skip
2384 :group 'org-todo
2385 :type 'boolean)
2387 (defcustom org-agenda-skip-scheduled-if-done nil
2388 "Non-nil means don't show scheduled items in agenda when they are done.
2389 This is relevant for the daily/weekly agenda, not for the TODO list. And
2390 it applies only to the actual date of the scheduling. Warnings about
2391 an item with a past scheduling dates are always turned off when the item
2392 is DONE."
2393 :group 'org-agenda-skip
2394 :type 'boolean)
2396 (defcustom org-agenda-skip-deadline-if-done nil
2397 "Non-nil means don't show deadines when the corresponding item is done.
2398 When nil, the deadline is still shown and should give you a happy feeling.
2399 This is relevant for the daily/weekly agenda. And it applied only to the
2400 actualy date of the deadline. Warnings about approching and past-due
2401 deadlines are always turned off when the item is DONE."
2402 :group 'org-agenda-skip
2403 :type 'boolean)
2405 (defcustom org-agenda-skip-timestamp-if-done nil
2406 "Non-nil means don't don't select item by timestamp or -range if it is DONE."
2407 :group 'org-agenda-skip
2408 :type 'boolean)
2410 (defcustom org-timeline-show-empty-dates 3
2411 "Non-nil means, `org-timeline' also shows dates without an entry.
2412 When nil, only the days which actually have entries are shown.
2413 When t, all days between the first and the last date are shown.
2414 When an integer, show also empty dates, but if there is a gap of more than
2415 N days, just insert a special line indicating the size of the gap."
2416 :group 'org-agenda-skip
2417 :type '(choice
2418 (const :tag "None" nil)
2419 (const :tag "All" t)
2420 (number :tag "at most")))
2423 (defgroup org-agenda-startup nil
2424 "Options concerning initial settings in the Agenda in Org Mode."
2425 :tag "Org Agenda Startup"
2426 :group 'org-agenda)
2428 (defcustom org-finalize-agenda-hook nil
2429 "Hook run just before displaying an agenda buffer."
2430 :group 'org-agenda-startup
2431 :type 'hook)
2433 (defcustom org-agenda-mouse-1-follows-link nil
2434 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2435 A longer mouse click will still set point. Does not wortk on XEmacs.
2436 Needs to be set before org.el is loaded."
2437 :group 'org-agenda-startup
2438 :type 'boolean)
2440 (defcustom org-agenda-start-with-follow-mode nil
2441 "The initial value of follow-mode in a newly created agenda window."
2442 :group 'org-agenda-startup
2443 :type 'boolean)
2445 (defgroup org-agenda-windows nil
2446 "Options concerning the windows used by the Agenda in Org Mode."
2447 :tag "Org Agenda Windows"
2448 :group 'org-agenda)
2450 (defcustom org-agenda-window-setup 'reorganize-frame
2451 "How the agenda buffer should be displayed.
2452 Possible values for this option are:
2454 current-window Show agenda in the current window, keeping all other windows.
2455 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2456 other-window Use `switch-to-buffer-other-window' to display agenda.
2457 reorganize-frame Show only two windows on the current frame, the current
2458 window and the agenda.
2459 See also the variable `org-agenda-restore-windows-after-quit'."
2460 :group 'org-agenda-windows
2461 :type '(choice
2462 (const current-window)
2463 (const other-frame)
2464 (const other-window)
2465 (const reorganize-frame)))
2467 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2468 "The min and max height of the agenda window as a fraction of frame height.
2469 The value of the variable is a cons cell with two numbers between 0 and 1.
2470 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2471 :group 'org-agenda-windows
2472 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2474 (defcustom org-agenda-restore-windows-after-quit nil
2475 "Non-nil means, restore window configuration open exiting agenda.
2476 Before the window configuration is changed for displaying the agenda,
2477 the current status is recorded. When the agenda is exited with
2478 `q' or `x' and this option is set, the old state is restored. If
2479 `org-agenda-window-setup' is `other-frame', the value of this
2480 option will be ignored.."
2481 :group 'org-agenda-windows
2482 :type 'boolean)
2484 (defcustom org-indirect-buffer-display 'other-window
2485 "How should indirect tree buffers be displayed?
2486 This applies to indirect buffers created with the commands
2487 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2488 Valid values are:
2489 current-window Display in the current window
2490 other-window Just display in another window.
2491 dedicated-frame Create one new frame, and re-use it each time.
2492 new-frame Make a new frame each time. Note that in this case
2493 previously-made indirect buffers are kept, and you need to
2494 kill these buffers yourself."
2495 :group 'org-structure
2496 :group 'org-agenda-windows
2497 :type '(choice
2498 (const :tag "In current window" current-window)
2499 (const :tag "In current frame, other window" other-window)
2500 (const :tag "Each time a new frame" new-frame)
2501 (const :tag "One dedicated frame" dedicated-frame)))
2503 (defgroup org-agenda-daily/weekly nil
2504 "Options concerning the daily/weekly agenda."
2505 :tag "Org Agenda Daily/Weekly"
2506 :group 'org-agenda)
2508 (defcustom org-agenda-ndays 7
2509 "Number of days to include in overview display.
2510 Should be 1 or 7."
2511 :group 'org-agenda-daily/weekly
2512 :type 'number)
2514 (defcustom org-agenda-start-on-weekday 1
2515 "Non-nil means, start the overview always on the specified weekday.
2516 0 denotes Sunday, 1 denotes Monday etc.
2517 When nil, always start on the current day."
2518 :group 'org-agenda-daily/weekly
2519 :type '(choice (const :tag "Today" nil)
2520 (number :tag "Weekday No.")))
2522 (defcustom org-agenda-show-all-dates t
2523 "Non-nil means, `org-agenda' shows every day in the selected range.
2524 When nil, only the days which actually have entries are shown."
2525 :group 'org-agenda-daily/weekly
2526 :type 'boolean)
2528 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2529 "Format string for displaying dates in the agenda.
2530 Used by the daily/weekly agenda and by the timeline. This should be
2531 a format string understood by `format-time-string', or a function returning
2532 the formatted date as a string. The function must take a single argument,
2533 a calendar-style date list like (month day year)."
2534 :group 'org-agenda-daily/weekly
2535 :type '(choice
2536 (string :tag "Format string")
2537 (function :tag "Function")))
2539 (defun org-agenda-format-date-aligned (date)
2540 "Format a date string for display in the daily/weekly agenda, or timeline.
2541 This function makes sure that dates are aligned for easy reading."
2542 (format "%-9s %2d %s %4d"
2543 (calendar-day-name date)
2544 (extract-calendar-day date)
2545 (calendar-month-name (extract-calendar-month date))
2546 (extract-calendar-year date)))
2548 (defcustom org-agenda-include-diary nil
2549 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2550 :group 'org-agenda-daily/weekly
2551 :type 'boolean)
2553 (defcustom org-agenda-include-all-todo nil
2554 "Set means weekly/daily agenda will always contain all TODO entries.
2555 The TODO entries will be listed at the top of the agenda, before
2556 the entries for specific days."
2557 :group 'org-agenda-daily/weekly
2558 :type 'boolean)
2560 (defcustom org-agenda-repeating-timestamp-show-all t
2561 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2562 When nil, only one occurence is shown, either today or the
2563 nearest into the future."
2564 :group 'org-agenda-daily/weekly
2565 :type 'boolean)
2567 (defcustom org-deadline-warning-days 14
2568 "No. of days before expiration during which a deadline becomes active.
2569 This variable governs the display in sparse trees and in the agenda.
2570 When negative, it means use this number (the absolute value of it)
2571 even if a deadline has a different individual lead time specified."
2572 :group 'org-time
2573 :group 'org-agenda-daily/weekly
2574 :type 'number)
2576 (defcustom org-scheduled-past-days 10000
2577 "No. of days to continue listing scheduled items that are not marked DONE.
2578 When an item is scheduled on a date, it shows up in the agenda on this
2579 day and will be listed until it is marked done for the number of days
2580 given here."
2581 :group 'org-agenda-daily/weekly
2582 :type 'number)
2584 (defgroup org-agenda-time-grid nil
2585 "Options concerning the time grid in the Org-mode Agenda."
2586 :tag "Org Agenda Time Grid"
2587 :group 'org-agenda)
2589 (defcustom org-agenda-use-time-grid t
2590 "Non-nil means, show a time grid in the agenda schedule.
2591 A time grid is a set of lines for specific times (like every two hours between
2592 8:00 and 20:00). The items scheduled for a day at specific times are
2593 sorted in between these lines.
2594 For details about when the grid will be shown, and what it will look like, see
2595 the variable `org-agenda-time-grid'."
2596 :group 'org-agenda-time-grid
2597 :type 'boolean)
2599 (defcustom org-agenda-time-grid
2600 '((daily today require-timed)
2601 "----------------"
2602 (800 1000 1200 1400 1600 1800 2000))
2604 "The settings for time grid for agenda display.
2605 This is a list of three items. The first item is again a list. It contains
2606 symbols specifying conditions when the grid should be displayed:
2608 daily if the agenda shows a single day
2609 weekly if the agenda shows an entire week
2610 today show grid on current date, independent of daily/weekly display
2611 require-timed show grid only if at least one item has a time specification
2613 The second item is a string which will be places behing the grid time.
2615 The third item is a list of integers, indicating the times that should have
2616 a grid line."
2617 :group 'org-agenda-time-grid
2618 :type
2619 '(list
2620 (set :greedy t :tag "Grid Display Options"
2621 (const :tag "Show grid in single day agenda display" daily)
2622 (const :tag "Show grid in weekly agenda display" weekly)
2623 (const :tag "Always show grid for today" today)
2624 (const :tag "Show grid only if any timed entries are present"
2625 require-timed)
2626 (const :tag "Skip grid times already present in an entry"
2627 remove-match))
2628 (string :tag "Grid String")
2629 (repeat :tag "Grid Times" (integer :tag "Time"))))
2631 (defgroup org-agenda-sorting nil
2632 "Options concerning sorting in the Org-mode Agenda."
2633 :tag "Org Agenda Sorting"
2634 :group 'org-agenda)
2636 (let ((sorting-choice
2637 '(choice
2638 (const time-up) (const time-down)
2639 (const category-keep) (const category-up) (const category-down)
2640 (const tag-down) (const tag-up)
2641 (const priority-up) (const priority-down))))
2643 (defcustom org-agenda-sorting-strategy
2644 '((agenda time-up category-keep priority-down)
2645 (todo category-keep priority-down)
2646 (tags category-keep priority-down))
2647 "Sorting structure for the agenda items of a single day.
2648 This is a list of symbols which will be used in sequence to determine
2649 if an entry should be listed before another entry. The following
2650 symbols are recognized:
2652 time-up Put entries with time-of-day indications first, early first
2653 time-down Put entries with time-of-day indications first, late first
2654 category-keep Keep the default order of categories, corresponding to the
2655 sequence in `org-agenda-files'.
2656 category-up Sort alphabetically by category, A-Z.
2657 category-down Sort alphabetically by category, Z-A.
2658 tag-up Sort alphabetically by last tag, A-Z.
2659 tag-down Sort alphabetically by last tag, Z-A.
2660 priority-up Sort numerically by priority, high priority last.
2661 priority-down Sort numerically by priority, high priority first.
2663 The different possibilities will be tried in sequence, and testing stops
2664 if one comparison returns a \"not-equal\". For example, the default
2665 '(time-up category-keep priority-down)
2666 means: Pull out all entries having a specified time of day and sort them,
2667 in order to make a time schedule for the current day the first thing in the
2668 agenda listing for the day. Of the entries without a time indication, keep
2669 the grouped in categories, don't sort the categories, but keep them in
2670 the sequence given in `org-agenda-files'. Within each category sort by
2671 priority.
2673 Leaving out `category-keep' would mean that items will be sorted across
2674 categories by priority.
2676 Instead of a single list, this can also be a set of list for specific
2677 contents, with a context symbol in the car of the list, any of
2678 `agenda', `todo', `tags' for the corresponding agenda views."
2679 :group 'org-agenda-sorting
2680 :type `(choice
2681 (repeat :tag "General" ,sorting-choice)
2682 (list :tag "Individually"
2683 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2684 (repeat ,sorting-choice))
2685 (cons (const :tag "Strategy for TODO lists" todo)
2686 (repeat ,sorting-choice))
2687 (cons (const :tag "Strategy for Tags matches" tags)
2688 (repeat ,sorting-choice))))))
2690 (defcustom org-sort-agenda-notime-is-late t
2691 "Non-nil means, items without time are considered late.
2692 This is only relevant for sorting. When t, items which have no explicit
2693 time like 15:30 will be considered as 99:01, i.e. later than any items which
2694 do have a time. When nil, the default time is before 0:00. You can use this
2695 option to decide if the schedule for today should come before or after timeless
2696 agenda entries."
2697 :group 'org-agenda-sorting
2698 :type 'boolean)
2700 (defgroup org-agenda-line-format nil
2701 "Options concerning the entry prefix in the Org-mode agenda display."
2702 :tag "Org Agenda Line Format"
2703 :group 'org-agenda)
2705 (defcustom org-agenda-prefix-format
2706 '((agenda . " %-12:c%?-12t% s")
2707 (timeline . " % s")
2708 (todo . " %-12:c")
2709 (tags . " %-12:c"))
2710 "Format specifications for the prefix of items in the agenda views.
2711 An alist with four entries, for the different agenda types. The keys to the
2712 sublists are `agenda', `timeline', `todo', and `tags'. The values
2713 are format strings.
2714 This format works similar to a printf format, with the following meaning:
2716 %c the category of the item, \"Diary\" for entries from the diary, or
2717 as given by the CATEGORY keyword or derived from the file name.
2718 %T the *last* tag of the item. Last because inherited tags come
2719 first in the list.
2720 %t the time-of-day specification if one applies to the entry, in the
2721 format HH:MM
2722 %s Scheduling/Deadline information, a short string
2724 All specifiers work basically like the standard `%s' of printf, but may
2725 contain two additional characters: A question mark just after the `%' and
2726 a whitespace/punctuation character just before the final letter.
2728 If the first character after `%' is a question mark, the entire field
2729 will only be included if the corresponding value applies to the
2730 current entry. This is useful for fields which should have fixed
2731 width when present, but zero width when absent. For example,
2732 \"%?-12t\" will result in a 12 character time field if a time of the
2733 day is specified, but will completely disappear in entries which do
2734 not contain a time.
2736 If there is punctuation or whitespace character just before the final
2737 format letter, this character will be appended to the field value if
2738 the value is not empty. For example, the format \"%-12:c\" leads to
2739 \"Diary: \" if the category is \"Diary\". If the category were be
2740 empty, no additional colon would be interted.
2742 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2743 - Indent the line with two space characters
2744 - Give the category in a 12 chars wide field, padded with whitespace on
2745 the right (because of `-'). Append a colon if there is a category
2746 (because of `:').
2747 - If there is a time-of-day, put it into a 12 chars wide field. If no
2748 time, don't put in an empty field, just skip it (because of '?').
2749 - Finally, put the scheduling information and append a whitespace.
2751 As another example, if you don't want the time-of-day of entries in
2752 the prefix, you could use:
2754 (setq org-agenda-prefix-format \" %-11:c% s\")
2756 See also the variables `org-agenda-remove-times-when-in-prefix' and
2757 `org-agenda-remove-tags'."
2758 :type '(choice
2759 (string :tag "General format")
2760 (list :greedy t :tag "View dependent"
2761 (cons (const agenda) (string :tag "Format"))
2762 (cons (const timeline) (string :tag "Format"))
2763 (cons (const todo) (string :tag "Format"))
2764 (cons (const tags) (string :tag "Format"))))
2765 :group 'org-agenda-line-format)
2767 (defvar org-prefix-format-compiled nil
2768 "The compiled version of the most recently used prefix format.
2769 See the variable `org-agenda-prefix-format'.")
2771 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
2772 "Text preceeding scheduled items in the agenda view.
2773 THis is a list with two strings. The first applies when the item is
2774 scheduled on the current day. The second applies when it has been scheduled
2775 previously, it may contain a %d to capture how many days ago the item was
2776 scheduled."
2777 :group 'org-agenda-line-format
2778 :type '(list
2779 (string :tag "Scheduled today ")
2780 (string :tag "Scheduled previously")))
2782 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
2783 "Text preceeding deadline items in the agenda view.
2784 This is a list with two strings. The first applies when the item has its
2785 deadline on the current day. The second applies when it is in the past or
2786 in the future, it may contain %d to capture how many days away the deadline
2787 is (was)."
2788 :group 'org-agenda-line-format
2789 :type '(list
2790 (string :tag "Deadline today ")
2791 (string :tag "Deadline relative")))
2793 (defcustom org-agenda-remove-times-when-in-prefix t
2794 "Non-nil means, remove duplicate time specifications in agenda items.
2795 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
2796 time-of-day specification in a headline or diary entry is extracted and
2797 placed into the prefix. If this option is non-nil, the original specification
2798 \(a timestamp or -range, or just a plain time(range) specification like
2799 11:30-4pm) will be removed for agenda display. This makes the agenda less
2800 cluttered.
2801 The option can be t or nil. It may also be the symbol `beg', indicating
2802 that the time should only be removed what it is located at the beginning of
2803 the headline/diary entry."
2804 :group 'org-agenda-line-format
2805 :type '(choice
2806 (const :tag "Always" t)
2807 (const :tag "Never" nil)
2808 (const :tag "When at beginning of entry" beg)))
2811 (defcustom org-agenda-default-appointment-duration nil
2812 "Default duration for appointments that only have a starting time.
2813 When nil, no duration is specified in such cases.
2814 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
2815 :group 'org-agenda-line-format
2816 :type '(choice
2817 (integer :tag "Minutes")
2818 (const :tag "No default duration")))
2821 (defcustom org-agenda-remove-tags nil
2822 "Non-nil means, remove the tags from the headline copy in the agenda.
2823 When this is the symbol `prefix', only remove tags when
2824 `org-agenda-prefix-format' contains a `%T' specifier."
2825 :group 'org-agenda-line-format
2826 :type '(choice
2827 (const :tag "Always" t)
2828 (const :tag "Never" nil)
2829 (const :tag "When prefix format contains %T" prefix)))
2831 (if (fboundp 'defvaralias)
2832 (defvaralias 'org-agenda-remove-tags-when-in-prefix
2833 'org-agenda-remove-tags))
2835 (defcustom org-agenda-tags-column -80
2836 "Shift tags in agenda items to this column.
2837 If this number is positive, it specifies the column. If it is negative,
2838 it means that the tags should be flushright to that column. For example,
2839 -80 works well for a normal 80 character screen."
2840 :group 'org-agenda-line-format
2841 :type 'integer)
2843 (if (fboundp 'defvaralias)
2844 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
2846 (defcustom org-agenda-fontify-priorities t
2847 "Non-nil means, highlight low and high priorities in agenda.
2848 When t, the highest priority entries are bold, lowest priority italic.
2849 This may also be an association list of priority faces. The face may be
2850 a names face, or a list like `(:background \"Red\")'."
2851 :group 'org-agenda-line-format
2852 :type '(choice
2853 (const :tag "Never" nil)
2854 (const :tag "Defaults" t)
2855 (repeat :tag "Specify"
2856 (list (character :tag "Priority" :value ?A)
2857 (sexp :tag "face")))))
2859 (defgroup org-latex nil
2860 "Options for embedding LaTeX code into Org-mode"
2861 :tag "Org LaTeX"
2862 :group 'org)
2864 (defcustom org-format-latex-options
2865 '(:foreground default :background default :scale 1.0
2866 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2867 :matchers ("begin" "$" "$$" "\\(" "\\["))
2868 "Options for creating images from LaTeX fragments.
2869 This is a property list with the following properties:
2870 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
2871 `default' means use the forground of the default face.
2872 :background the background color, or \"Transparent\".
2873 `default' means use the background of the default face.
2874 :scale a scaling factor for the size of the images
2875 :html-foreground, :html-background, :html-scale
2876 The same numbers for HTML export.
2877 :matchers a list indicating which matchers should be used to
2878 find LaTeX fragments. Valid members of this list are:
2879 \"begin\" find environments
2880 \"$\" find math expressions surrounded by $...$
2881 \"$$\" find math expressions surrounded by $$....$$
2882 \"\\(\" find math expressions surrounded by \\(...\\)
2883 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2884 :group 'org-latex
2885 :type 'plist)
2887 (defcustom org-format-latex-header "\\documentclass{article}
2888 \\usepackage{fullpage} % do not remove
2889 \\usepackage{amssymb}
2890 \\usepackage[usenames]{color}
2891 \\usepackage{amsmath}
2892 \\usepackage{latexsym}
2893 \\usepackage[mathscr]{eucal}
2894 \\pagestyle{empty} % do not remove"
2895 "The document header used for processing LaTeX fragments."
2896 :group 'org-latex
2897 :type 'string)
2899 (defgroup org-export nil
2900 "Options for exporting org-listings."
2901 :tag "Org Export"
2902 :group 'org)
2904 (defgroup org-export-general nil
2905 "General options for exporting Org-mode files."
2906 :tag "Org Export General"
2907 :group 'org-export)
2909 ;; FIXME
2910 (defvar org-export-publishing-directory nil)
2912 (defcustom org-export-with-special-strings t
2913 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
2914 When this option is turned on, these strings will be exported as:
2916 Org HTML LaTeX
2917 -----+----------+--------
2918 \\- &shy; \\-
2919 -- &ndash; --
2920 --- &mdash; ---
2921 ... &hellip; \ldots
2923 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
2924 :group 'org-export-translation
2925 :type 'boolean)
2927 (defcustom org-export-language-setup
2928 '(("en" "Author" "Date" "Table of Contents")
2929 ("cs" "Autor" "Datum" "Obsah")
2930 ("da" "Ophavsmand" "Dato" "Indhold")
2931 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
2932 ("es" "Autor" "Fecha" "\xcdndice")
2933 ("fr" "Auteur" "Date" "Table des mati\xe8res")
2934 ("it" "Autore" "Data" "Indice")
2935 ("nl" "Auteur" "Datum" "Inhoudsopgave")
2936 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
2937 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
2938 "Terms used in export text, translated to different languages.
2939 Use the variable `org-export-default-language' to set the language,
2940 or use the +OPTION lines for a per-file setting."
2941 :group 'org-export-general
2942 :type '(repeat
2943 (list
2944 (string :tag "HTML language tag")
2945 (string :tag "Author")
2946 (string :tag "Date")
2947 (string :tag "Table of Contents"))))
2949 (defcustom org-export-default-language "en"
2950 "The default language of HTML export, as a string.
2951 This should have an association in `org-export-language-setup'."
2952 :group 'org-export-general
2953 :type 'string)
2955 (defcustom org-export-skip-text-before-1st-heading t
2956 "Non-nil means, skip all text before the first headline when exporting.
2957 When nil, that text is exported as well."
2958 :group 'org-export-general
2959 :type 'boolean)
2961 (defcustom org-export-headline-levels 3
2962 "The last level which is still exported as a headline.
2963 Inferior levels will produce itemize lists when exported.
2964 Note that a numeric prefix argument to an exporter function overrides
2965 this setting.
2967 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
2968 :group 'org-export-general
2969 :type 'number)
2971 (defcustom org-export-with-section-numbers t
2972 "Non-nil means, add section numbers to headlines when exporting.
2974 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
2975 :group 'org-export-general
2976 :type 'boolean)
2978 (defcustom org-export-with-toc t
2979 "Non-nil means, create a table of contents in exported files.
2980 The TOC contains headlines with levels up to`org-export-headline-levels'.
2981 When an integer, include levels up to N in the toc, this may then be
2982 different from `org-export-headline-levels', but it will not be allowed
2983 to be larger than the number of headline levels.
2984 When nil, no table of contents is made.
2986 Headlines which contain any TODO items will be marked with \"(*)\" in
2987 ASCII export, and with red color in HTML output, if the option
2988 `org-export-mark-todo-in-toc' is set.
2990 In HTML output, the TOC will be clickable.
2992 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
2993 or \"toc:3\"."
2994 :group 'org-export-general
2995 :type '(choice
2996 (const :tag "No Table of Contents" nil)
2997 (const :tag "Full Table of Contents" t)
2998 (integer :tag "TOC to level")))
3000 (defcustom org-export-mark-todo-in-toc nil
3001 "Non-nil means, mark TOC lines that contain any open TODO items."
3002 :group 'org-export-general
3003 :type 'boolean)
3005 (defcustom org-export-preserve-breaks nil
3006 "Non-nil means, preserve all line breaks when exporting.
3007 Normally, in HTML output paragraphs will be reformatted. In ASCII
3008 export, line breaks will always be preserved, regardless of this variable.
3010 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3011 :group 'org-export-general
3012 :type 'boolean)
3014 (defcustom org-export-with-archived-trees 'headline
3015 "Whether subtrees with the ARCHIVE tag should be exported.
3016 This can have three different values
3017 nil Do not export, pretend this tree is not present
3018 t Do export the entire tree
3019 headline Only export the headline, but skip the tree below it."
3020 :group 'org-export-general
3021 :group 'org-archive
3022 :type '(choice
3023 (const :tag "not at all" nil)
3024 (const :tag "headline only" 'headline)
3025 (const :tag "entirely" t)))
3027 (defcustom org-export-author-info t
3028 "Non-nil means, insert author name and email into the exported file.
3030 This option can also be set with the +OPTIONS line,
3031 e.g. \"author-info:nil\"."
3032 :group 'org-export-general
3033 :type 'boolean)
3035 (defcustom org-export-time-stamp-file t
3036 "Non-nil means, insert a time stamp into the exported file.
3037 The time stamp shows when the file was created.
3039 This option can also be set with the +OPTIONS line,
3040 e.g. \"timestamp:nil\"."
3041 :group 'org-export-general
3042 :type 'boolean)
3044 (defcustom org-export-with-timestamps t
3045 "If nil, do not export time stamps and associated keywords."
3046 :group 'org-export-general
3047 :type 'boolean)
3049 (defcustom org-export-remove-timestamps-from-toc t
3050 "If nil, remove timestamps from the table of contents entries."
3051 :group 'org-export-general
3052 :type 'boolean)
3054 (defcustom org-export-with-tags 'not-in-toc
3055 "If nil, do not export tags, just remove them from headlines.
3056 If this is the symbol `not-in-toc', tags will be removed from table of
3057 contents entries, but still be shown in the headlines of the document.
3059 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3060 :group 'org-export-general
3061 :type '(choice
3062 (const :tag "Off" nil)
3063 (const :tag "Not in TOC" not-in-toc)
3064 (const :tag "On" t)))
3066 (defcustom org-export-with-drawers nil
3067 "Non-nil means, export with drawers like the property drawer.
3068 When t, all drawers are exported. This may also be a list of
3069 drawer names to export."
3070 :group 'org-export-general
3071 :type '(choice
3072 (const :tag "All drawers" t)
3073 (const :tag "None" nil)
3074 (repeat :tag "Selected drawers"
3075 (string :tag "Drawer name"))))
3077 (defgroup org-export-translation nil
3078 "Options for translating special ascii sequences for the export backends."
3079 :tag "Org Export Translation"
3080 :group 'org-export)
3082 (defcustom org-export-with-emphasize t
3083 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3084 If the export target supports emphasizing text, the word will be
3085 typeset in bold, italic, or underlined, respectively. Works only for
3086 single words, but you can say: I *really* *mean* *this*.
3087 Not all export backends support this.
3089 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3090 :group 'org-export-translation
3091 :type 'boolean)
3093 (defcustom org-export-with-footnotes t
3094 "If nil, export [1] as a footnote marker.
3095 Lines starting with [1] will be formatted as footnotes.
3097 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3098 :group 'org-export-translation
3099 :type 'boolean)
3101 (defcustom org-export-with-sub-superscripts t
3102 "Non-nil means, interpret \"_\" and \"^\" for export.
3103 When this option is turned on, you can use TeX-like syntax for sub- and
3104 superscripts. Several characters after \"_\" or \"^\" will be
3105 considered as a single item - so grouping with {} is normally not
3106 needed. For example, the following things will be parsed as single
3107 sub- or superscripts.
3109 10^24 or 10^tau several digits will be considered 1 item.
3110 10^-12 or 10^-tau a leading sign with digits or a word
3111 x^2-y^3 will be read as x^2 - y^3, because items are
3112 terminated by almost any nonword/nondigit char.
3113 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3115 Still, ambiguity is possible - so when in doubt use {} to enclose the
3116 sub/superscript. If you set this variable to the symbol `{}',
3117 the braces are *required* in order to trigger interpretations as
3118 sub/superscript. This can be helpful in documents that need \"_\"
3119 frequently in plain text.
3121 Not all export backends support this, but HTML does.
3123 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3124 :group 'org-export-translation
3125 :type '(choice
3126 (const :tag "Always interpret" t)
3127 (const :tag "Only with braces" {})
3128 (const :tag "Never interpret" nil)))
3130 (defcustom org-export-with-special-strings t
3131 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3132 When this option is turned on, these strings will be exported as:
3134 \\- : &shy;
3135 -- : &ndash;
3136 --- : &mdash;
3138 Not all export backends support this, but HTML does.
3140 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3141 :group 'org-export-translation
3142 :type 'boolean)
3144 (defcustom org-export-with-TeX-macros t
3145 "Non-nil means, interpret simple TeX-like macros when exporting.
3146 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3147 No only real TeX macros will work here, but the standard HTML entities
3148 for math can be used as macro names as well. For a list of supported
3149 names in HTML export, see the constant `org-html-entities'.
3150 Not all export backends support this.
3152 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3153 :group 'org-export-translation
3154 :group 'org-export-latex
3155 :type 'boolean)
3157 (defcustom org-export-with-LaTeX-fragments nil
3158 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3159 When set, the exporter will find LaTeX environments if the \\begin line is
3160 the first non-white thing on a line. It will also find the math delimiters
3161 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3162 display math.
3164 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3165 :group 'org-export-translation
3166 :group 'org-export-latex
3167 :type 'boolean)
3169 (defcustom org-export-with-fixed-width t
3170 "Non-nil means, lines starting with \":\" will be in fixed width font.
3171 This can be used to have pre-formatted text, fragments of code etc. For
3172 example:
3173 : ;; Some Lisp examples
3174 : (while (defc cnt)
3175 : (ding))
3176 will be looking just like this in also HTML. See also the QUOTE keyword.
3177 Not all export backends support this.
3179 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3180 :group 'org-export-translation
3181 :type 'boolean)
3183 (defcustom org-match-sexp-depth 3
3184 "Number of stacked braces for sub/superscript matching.
3185 This has to be set before loading org.el to be effective."
3186 :group 'org-export-translation
3187 :type 'integer)
3189 (defgroup org-export-tables nil
3190 "Options for exporting tables in Org-mode."
3191 :tag "Org Export Tables"
3192 :group 'org-export)
3194 (defcustom org-export-with-tables t
3195 "If non-nil, lines starting with \"|\" define a table.
3196 For example:
3198 | Name | Address | Birthday |
3199 |-------------+----------+-----------|
3200 | Arthur Dent | England | 29.2.2100 |
3202 Not all export backends support this.
3204 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3205 :group 'org-export-tables
3206 :type 'boolean)
3208 (defcustom org-export-highlight-first-table-line t
3209 "Non-nil means, highlight the first table line.
3210 In HTML export, this means use <th> instead of <td>.
3211 In tables created with table.el, this applies to the first table line.
3212 In Org-mode tables, all lines before the first horizontal separator
3213 line will be formatted with <th> tags."
3214 :group 'org-export-tables
3215 :type 'boolean)
3217 (defcustom org-export-table-remove-special-lines t
3218 "Remove special lines and marking characters in calculating tables.
3219 This removes the special marking character column from tables that are set
3220 up for spreadsheet calculations. It also removes the entire lines
3221 marked with `!', `_', or `^'. The lines with `$' are kept, because
3222 the values of constants may be useful to have."
3223 :group 'org-export-tables
3224 :type 'boolean)
3226 (defcustom org-export-prefer-native-exporter-for-tables nil
3227 "Non-nil means, always export tables created with table.el natively.
3228 Natively means, use the HTML code generator in table.el.
3229 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3230 the table does not use row- or column-spanning). This has the
3231 advantage, that the automatic HTML conversions for math symbols and
3232 sub/superscripts can be applied. Org-mode's HTML generator is also
3233 much faster."
3234 :group 'org-export-tables
3235 :type 'boolean)
3237 (defgroup org-export-ascii nil
3238 "Options specific for ASCII export of Org-mode files."
3239 :tag "Org Export ASCII"
3240 :group 'org-export)
3242 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3243 "Characters for underlining headings in ASCII export.
3244 In the given sequence, these characters will be used for level 1, 2, ..."
3245 :group 'org-export-ascii
3246 :type '(repeat character))
3248 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3249 "Bullet characters for headlines converted to lists in ASCII export.
3250 The first character is is used for the first lest level generated in this
3251 way, and so on. If there are more levels than characters given here,
3252 the list will be repeated.
3253 Note that plain lists will keep the same bullets as the have in the
3254 Org-mode file."
3255 :group 'org-export-ascii
3256 :type '(repeat character))
3258 (defgroup org-export-xml nil
3259 "Options specific for XML export of Org-mode files."
3260 :tag "Org Export XML"
3261 :group 'org-export)
3263 (defgroup org-export-html nil
3264 "Options specific for HTML export of Org-mode files."
3265 :tag "Org Export HTML"
3266 :group 'org-export)
3268 (defcustom org-export-html-coding-system nil
3270 :group 'org-export-html
3271 :type 'coding-system)
3273 (defcustom org-export-html-extension "html"
3274 "The extension for exported HTML files."
3275 :group 'org-export-html
3276 :type 'string)
3278 (defcustom org-export-html-style
3279 "<style type=\"text/css\">
3280 html {
3281 font-family: Times, serif;
3282 font-size: 12pt;
3284 .title { text-align: center; }
3285 .todo { color: red; }
3286 .done { color: green; }
3287 .timestamp { color: grey }
3288 .timestamp-kwd { color: CadetBlue }
3289 .tag { background-color:lightblue; font-weight:normal }
3290 .target { background-color: lavender; }
3291 pre {
3292 border: 1pt solid #AEBDCC;
3293 background-color: #F3F5F7;
3294 padding: 5pt;
3295 font-family: courier, monospace;
3297 table { border-collapse: collapse; }
3298 td, th {
3299 vertical-align: top;
3300 <!--border: 1pt solid #ADB9CC;-->
3302 </style>"
3303 "The default style specification for exported HTML files.
3304 Since there are different ways of setting style information, this variable
3305 needs to contain the full HTML structure to provide a style, including the
3306 surrounding HTML tags. The style specifications should include definitions
3307 for new classes todo, done, title, and deadline. For example, legal values
3308 would be:
3310 <style type=\"text/css\">
3311 p { font-weight: normal; color: gray; }
3312 h1 { color: black; }
3313 .title { text-align: center; }
3314 .todo, .deadline { color: red; }
3315 .done { color: green; }
3316 </style>
3318 or, if you want to keep the style in a file,
3320 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3322 As the value of this option simply gets inserted into the HTML <head> header,
3323 you can \"misuse\" it to add arbitrary text to the header."
3324 :group 'org-export-html
3325 :type 'string)
3328 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3329 "Format for typesetting the document title in HTML export."
3330 :group 'org-export-html
3331 :type 'string)
3333 (defcustom org-export-html-toplevel-hlevel 2
3334 "The <H> level for level 1 headings in HTML export."
3335 :group 'org-export-html
3336 :type 'string)
3338 (defcustom org-export-html-link-org-files-as-html t
3339 "Non-nil means, make file links to `file.org' point to `file.html'.
3340 When org-mode is exporting an org-mode file to HTML, links to
3341 non-html files are directly put into a href tag in HTML.
3342 However, links to other Org-mode files (recognized by the
3343 extension `.org.) should become links to the corresponding html
3344 file, assuming that the linked org-mode file will also be
3345 converted to HTML.
3346 When nil, the links still point to the plain `.org' file."
3347 :group 'org-export-html
3348 :type 'boolean)
3350 (defcustom org-export-html-inline-images 'maybe
3351 "Non-nil means, inline images into exported HTML pages.
3352 This is done using an <img> tag. When nil, an anchor with href is used to
3353 link to the image. If this option is `maybe', then images in links with
3354 an empty description will be inlined, while images with a description will
3355 be linked only."
3356 :group 'org-export-html
3357 :type '(choice (const :tag "Never" nil)
3358 (const :tag "Always" t)
3359 (const :tag "When there is no description" maybe)))
3361 ;; FIXME: rename
3362 (defcustom org-export-html-expand t
3363 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3364 When nil, these tags will be exported as plain text and therefore
3365 not be interpreted by a browser.
3367 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3368 :group 'org-export-html
3369 :type 'boolean)
3371 (defcustom org-export-html-table-tag
3372 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3373 "The HTML tag that is used to start a table.
3374 This must be a <table> tag, but you may change the options like
3375 borders and spacing."
3376 :group 'org-export-html
3377 :type 'string)
3379 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3380 "The opening tag for table header fields.
3381 This is customizable so that alignment options can be specified."
3382 :group 'org-export-tables
3383 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3385 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3386 "The opening tag for table data fields.
3387 This is customizable so that alignment options can be specified."
3388 :group 'org-export-tables
3389 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3391 (defcustom org-export-html-with-timestamp nil
3392 "If non-nil, write `org-export-html-html-helper-timestamp'
3393 into the exported HTML text. Otherwise, the buffer will just be saved
3394 to a file."
3395 :group 'org-export-html
3396 :type 'boolean)
3398 (defcustom org-export-html-html-helper-timestamp
3399 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3400 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3401 :group 'org-export-html
3402 :type 'string)
3404 (defgroup org-export-icalendar nil
3405 "Options specific for iCalendar export of Org-mode files."
3406 :tag "Org Export iCalendar"
3407 :group 'org-export)
3409 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3410 "The file name for the iCalendar file covering all agenda files.
3411 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3412 The file name should be absolute, the file will be overwritten without warning."
3413 :group 'org-export-icalendar
3414 :type 'file)
3416 (defcustom org-icalendar-include-todo nil
3417 "Non-nil means, export to iCalendar files should also cover TODO items."
3418 :group 'org-export-icalendar
3419 :type '(choice
3420 (const :tag "None" nil)
3421 (const :tag "Unfinished" t)
3422 (const :tag "All" all)))
3424 (defcustom org-icalendar-include-sexps t
3425 "Non-nil means, export to iCalendar files should also cover sexp entries.
3426 These are entries like in the diary, but directly in an Org-mode file."
3427 :group 'org-export-icalendar
3428 :type 'boolean)
3430 (defcustom org-icalendar-include-body 100
3431 "Amount of text below headline to be included in iCalendar export.
3432 This is a number of characters that should maximally be included.
3433 Properties, scheduling and clocking lines will always be removed.
3434 The text will be inserted into the DESCRIPTION field."
3435 :group 'org-export-icalendar
3436 :type '(choice
3437 (const :tag "Nothing" nil)
3438 (const :tag "Everything" t)
3439 (integer :tag "Max characters")))
3441 (defcustom org-icalendar-combined-name "OrgMode"
3442 "Calendar name for the combined iCalendar representing all agenda files."
3443 :group 'org-export-icalendar
3444 :type 'string)
3446 (defgroup org-font-lock nil
3447 "Font-lock settings for highlighting in Org-mode."
3448 :tag "Org Font Lock"
3449 :group 'org)
3451 (defcustom org-level-color-stars-only nil
3452 "Non-nil means fontify only the stars in each headline.
3453 When nil, the entire headline is fontified.
3454 Changing it requires restart of `font-lock-mode' to become effective
3455 also in regions already fontified."
3456 :group 'org-font-lock
3457 :type 'boolean)
3459 (defcustom org-hide-leading-stars nil
3460 "Non-nil means, hide the first N-1 stars in a headline.
3461 This works by using the face `org-hide' for these stars. This
3462 face is white for a light background, and black for a dark
3463 background. You may have to customize the face `org-hide' to
3464 make this work.
3465 Changing it requires restart of `font-lock-mode' to become effective
3466 also in regions already fontified.
3467 You may also set this on a per-file basis by adding one of the following
3468 lines to the buffer:
3470 #+STARTUP: hidestars
3471 #+STARTUP: showstars"
3472 :group 'org-font-lock
3473 :type 'boolean)
3475 (defcustom org-fontify-done-headline nil
3476 "Non-nil means, change the face of a headline if it is marked DONE.
3477 Normally, only the TODO/DONE keyword indicates the state of a headline.
3478 When this is non-nil, the headline after the keyword is set to the
3479 `org-headline-done' as an additional indication."
3480 :group 'org-font-lock
3481 :type 'boolean)
3483 (defcustom org-fontify-emphasized-text t
3484 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3485 Changing this variable requires a restart of Emacs to take effect."
3486 :group 'org-font-lock
3487 :type 'boolean)
3489 (defcustom org-hide-emphasis-markers nil
3490 "Non-nil measn font-lock should hide the emphasis marker characters."
3491 :group 'org-font-lock
3492 :type 'boolean)
3494 (defvar org-emph-re nil
3495 "Regular expression for matching emphasis.")
3496 (defvar org-verbatim-re nil
3497 "Regular expression for matching verbatim text.")
3498 (defvar org-emphasis-regexp-components) ; defined just below
3499 (defvar org-emphasis-alist) ; defined just below
3500 (defun org-set-emph-re (var val)
3501 "Set variable and compute the emphasis regular expression."
3502 (set var val)
3503 (when (and (boundp 'org-emphasis-alist)
3504 (boundp 'org-emphasis-regexp-components)
3505 org-emphasis-alist org-emphasis-regexp-components)
3506 (let* ((e org-emphasis-regexp-components)
3507 (pre (car e))
3508 (post (nth 1 e))
3509 (border (nth 2 e))
3510 (body (nth 3 e))
3511 (nl (nth 4 e))
3512 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3513 (body1 (concat body "*?"))
3514 (markers (mapconcat 'car org-emphasis-alist ""))
3515 (vmarkers (mapconcat
3516 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3517 org-emphasis-alist "")))
3518 ;; make sure special characters appear at the right position in the class
3519 (if (string-match "\\^" markers)
3520 (setq markers (concat (replace-match "" t t markers) "^")))
3521 (if (string-match "-" markers)
3522 (setq markers (concat (replace-match "" t t markers) "-")))
3523 (if (string-match "\\^" vmarkers)
3524 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3525 (if (string-match "-" vmarkers)
3526 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3527 (if (> nl 0)
3528 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3529 (int-to-string nl) "\\}")))
3530 ;; Make the regexp
3531 (setq org-emph-re
3532 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3533 "\\("
3534 "\\([" markers "]\\)"
3535 "\\("
3536 "[^" border "]\\|"
3537 "[^" border (if (and nil stacked) markers) "]"
3538 body1
3539 "[^" border (if (and nil stacked) markers) "]"
3540 "\\)"
3541 "\\3\\)"
3542 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3543 (setq org-verbatim-re
3544 (concat "\\([" pre "]\\|^\\)"
3545 "\\("
3546 "\\([" vmarkers "]\\)"
3547 "\\("
3548 "[^" border "]\\|"
3549 "[^" border "]"
3550 body1
3551 "[^" border "]"
3552 "\\)"
3553 "\\3\\)"
3554 "\\([" post "]\\|$\\)")))))
3556 (defcustom org-emphasis-regexp-components
3557 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3558 "Components used to build the regular expression for emphasis.
3559 This is a list with 6 entries. Terminology: In an emphasis string
3560 like \" *strong word* \", we call the initial space PREMATCH, the final
3561 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3562 and \"trong wor\" is the body. The different components in this variable
3563 specify what is allowed/forbidden in each part:
3565 pre Chars allowed as prematch. Beginning of line will be allowed too.
3566 post Chars allowed as postmatch. End of line will be allowed too.
3567 border The chars *forbidden* as border characters.
3568 body-regexp A regexp like \".\" to match a body character. Don't use
3569 non-shy groups here, and don't allow newline here.
3570 newline The maximum number of newlines allowed in an emphasis exp.
3572 Use customize to modify this, or restart Emacs after changing it."
3573 :group 'org-font-lock
3574 :set 'org-set-emph-re
3575 :type '(list
3576 (sexp :tag "Allowed chars in pre ")
3577 (sexp :tag "Allowed chars in post ")
3578 (sexp :tag "Forbidden chars in border ")
3579 (sexp :tag "Regexp for body ")
3580 (integer :tag "number of newlines allowed")
3581 (option (boolean :tag "Stacking (DISABLED) "))))
3583 (defcustom org-emphasis-alist
3584 '(("*" bold "<b>" "</b>")
3585 ("/" italic "<i>" "</i>")
3586 ("_" underline "<u>" "</u>")
3587 ("=" org-code "<code>" "</code>" verbatim)
3588 ("~" org-verbatim "" "" verbatim)
3589 ("+" (:strike-through t) "<del>" "</del>")
3591 "Special syntax for emphasized text.
3592 Text starting and ending with a special character will be emphasized, for
3593 example *bold*, _underlined_ and /italic/. This variable sets the marker
3594 characters, the face to be used by font-lock for highlighting in Org-mode
3595 Emacs buffers, and the HTML tags to be used for this.
3596 Use customize to modify this, or restart Emacs after changing it."
3597 :group 'org-font-lock
3598 :set 'org-set-emph-re
3599 :type '(repeat
3600 (list
3601 (string :tag "Marker character")
3602 (choice
3603 (face :tag "Font-lock-face")
3604 (plist :tag "Face property list"))
3605 (string :tag "HTML start tag")
3606 (string :tag "HTML end tag")
3607 (option (const verbatim)))))
3609 ;;; The faces
3611 (defgroup org-faces nil
3612 "Faces in Org-mode."
3613 :tag "Org Faces"
3614 :group 'org-font-lock)
3616 (defun org-compatible-face (inherits specs)
3617 "Make a compatible face specification.
3618 If INHERITS is an existing face and if the Emacs version supports it,
3619 just inherit the face. If not, use SPECS to define the face.
3620 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3621 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3622 to the top of the list. The `min-colors' attribute will be removed from
3623 any other entries, and any resulting duplicates will be removed entirely."
3624 (cond
3625 ((and inherits (facep inherits)
3626 (not (featurep 'xemacs)) (> emacs-major-version 22))
3627 ;; In Emacs 23, we use inheritance where possible.
3628 ;; We only do this in Emacs 23, because only there the outline
3629 ;; faces have been changed to the original org-mode-level-faces.
3630 (list (list t :inherit inherits)))
3631 ((or (featurep 'xemacs) (< emacs-major-version 22))
3632 ;; These do not understand the `min-colors' attribute.
3633 (let (r e a)
3634 (while (setq e (pop specs))
3635 (cond
3636 ((memq (car e) '(t default)) (push e r))
3637 ((setq a (member '(min-colors 8) (car e)))
3638 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3639 (cdr e)))))
3640 ((setq a (assq 'min-colors (car e)))
3641 (setq e (cons (delq a (car e)) (cdr e)))
3642 (or (assoc (car e) r) (push e r)))
3643 (t (or (assoc (car e) r) (push e r)))))
3644 (nreverse r)))
3645 (t specs)))
3647 (defface org-hide
3648 '((((background light)) (:foreground "white"))
3649 (((background dark)) (:foreground "black")))
3650 "Face used to hide leading stars in headlines.
3651 The forground color of this face should be equal to the background
3652 color of the frame."
3653 :group 'org-faces)
3655 (defface org-level-1 ;; font-lock-function-name-face
3656 (org-compatible-face
3657 'outline-1
3658 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3659 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3660 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3661 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3662 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3663 (t (:bold t))))
3664 "Face used for level 1 headlines."
3665 :group 'org-faces)
3667 (defface org-level-2 ;; font-lock-variable-name-face
3668 (org-compatible-face
3669 'outline-2
3670 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3671 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3672 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3673 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3674 (t (:bold t))))
3675 "Face used for level 2 headlines."
3676 :group 'org-faces)
3678 (defface org-level-3 ;; font-lock-keyword-face
3679 (org-compatible-face
3680 'outline-3
3681 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3682 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3683 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3684 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3685 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3686 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3687 (t (:bold t))))
3688 "Face used for level 3 headlines."
3689 :group 'org-faces)
3691 (defface org-level-4 ;; font-lock-comment-face
3692 (org-compatible-face
3693 'outline-4
3694 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3695 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3696 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3697 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3698 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3699 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3700 (t (:bold t))))
3701 "Face used for level 4 headlines."
3702 :group 'org-faces)
3704 (defface org-level-5 ;; font-lock-type-face
3705 (org-compatible-face
3706 'outline-5
3707 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3708 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3709 (((class color) (min-colors 8)) (:foreground "green"))))
3710 "Face used for level 5 headlines."
3711 :group 'org-faces)
3713 (defface org-level-6 ;; font-lock-constant-face
3714 (org-compatible-face
3715 'outline-6
3716 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3717 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3718 (((class color) (min-colors 8)) (:foreground "magenta"))))
3719 "Face used for level 6 headlines."
3720 :group 'org-faces)
3722 (defface org-level-7 ;; font-lock-builtin-face
3723 (org-compatible-face
3724 'outline-7
3725 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3726 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3727 (((class color) (min-colors 8)) (:foreground "blue"))))
3728 "Face used for level 7 headlines."
3729 :group 'org-faces)
3731 (defface org-level-8 ;; font-lock-string-face
3732 (org-compatible-face
3733 'outline-8
3734 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3735 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3736 (((class color) (min-colors 8)) (:foreground "green"))))
3737 "Face used for level 8 headlines."
3738 :group 'org-faces)
3740 (defface org-special-keyword ;; font-lock-string-face
3741 (org-compatible-face
3743 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3744 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3745 (t (:italic t))))
3746 "Face used for special keywords."
3747 :group 'org-faces)
3749 (defface org-drawer ;; font-lock-function-name-face
3750 (org-compatible-face
3752 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3753 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3754 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3755 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3756 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3757 (t (:bold t))))
3758 "Face used for drawers."
3759 :group 'org-faces)
3761 (defface org-property-value nil
3762 "Face used for the value of a property."
3763 :group 'org-faces)
3765 (defface org-column
3766 (org-compatible-face
3768 '((((class color) (min-colors 16) (background light))
3769 (:background "grey90"))
3770 (((class color) (min-colors 16) (background dark))
3771 (:background "grey30"))
3772 (((class color) (min-colors 8))
3773 (:background "cyan" :foreground "black"))
3774 (t (:inverse-video t))))
3775 "Face for column display of entry properties."
3776 :group 'org-faces)
3778 (when (fboundp 'set-face-attribute)
3779 ;; Make sure that a fixed-width face is used when we have a column table.
3780 (set-face-attribute 'org-column nil
3781 :height (face-attribute 'default :height)
3782 :family (face-attribute 'default :family)))
3784 (defface org-warning
3785 (org-compatible-face
3786 'font-lock-warning-face
3787 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3788 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3789 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3790 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3791 (t (:bold t))))
3792 "Face for deadlines and TODO keywords."
3793 :group 'org-faces)
3795 (defface org-archived ; similar to shadow
3796 (org-compatible-face
3797 'shadow
3798 '((((class color grayscale) (min-colors 88) (background light))
3799 (:foreground "grey50"))
3800 (((class color grayscale) (min-colors 88) (background dark))
3801 (:foreground "grey70"))
3802 (((class color) (min-colors 8) (background light))
3803 (:foreground "green"))
3804 (((class color) (min-colors 8) (background dark))
3805 (:foreground "yellow"))))
3806 "Face for headline with the ARCHIVE tag."
3807 :group 'org-faces)
3809 (defface org-link
3810 '((((class color) (background light)) (:foreground "Purple" :underline t))
3811 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3812 (t (:underline t)))
3813 "Face for links."
3814 :group 'org-faces)
3816 (defface org-ellipsis
3817 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
3818 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
3819 (t (:strike-through t)))
3820 "Face for the ellipsis in folded text."
3821 :group 'org-faces)
3823 (defface org-target
3824 '((((class color) (background light)) (:underline t))
3825 (((class color) (background dark)) (:underline t))
3826 (t (:underline t)))
3827 "Face for links."
3828 :group 'org-faces)
3830 (defface org-date
3831 '((((class color) (background light)) (:foreground "Purple" :underline t))
3832 (((class color) (background dark)) (:foreground "Cyan" :underline t))
3833 (t (:underline t)))
3834 "Face for links."
3835 :group 'org-faces)
3837 (defface org-sexp-date
3838 '((((class color) (background light)) (:foreground "Purple"))
3839 (((class color) (background dark)) (:foreground "Cyan"))
3840 (t (:underline t)))
3841 "Face for links."
3842 :group 'org-faces)
3844 (defface org-tag
3845 '((t (:bold t)))
3846 "Face for tags."
3847 :group 'org-faces)
3849 (defface org-todo ; font-lock-warning-face
3850 (org-compatible-face
3852 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
3853 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
3854 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3855 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3856 (t (:inverse-video t :bold t))))
3857 "Face for TODO keywords."
3858 :group 'org-faces)
3860 (defface org-done ;; font-lock-type-face
3861 (org-compatible-face
3863 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
3864 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
3865 (((class color) (min-colors 8)) (:foreground "green"))
3866 (t (:bold t))))
3867 "Face used for todo keywords that indicate DONE items."
3868 :group 'org-faces)
3870 (defface org-headline-done ;; font-lock-string-face
3871 (org-compatible-face
3873 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3874 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3875 (((class color) (min-colors 8) (background light)) (:bold nil))))
3876 "Face used to indicate that a headline is DONE.
3877 This face is only used if `org-fontify-done-headline' is set. If applies
3878 to the part of the headline after the DONE keyword."
3879 :group 'org-faces)
3881 (defcustom org-todo-keyword-faces nil
3882 "Faces for specific TODO keywords.
3883 This is a list of cons cells, with TODO keywords in the car
3884 and faces in the cdr. The face can be a symbol, or a property
3885 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
3886 :group 'org-faces
3887 :group 'org-todo
3888 :type '(repeat
3889 (cons
3890 (string :tag "keyword")
3891 (sexp :tag "face"))))
3893 (defface org-table ;; font-lock-function-name-face
3894 (org-compatible-face
3896 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3897 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3898 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3899 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3900 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
3901 (((class color) (min-colors 8) (background dark)))))
3902 "Face used for tables."
3903 :group 'org-faces)
3905 (defface org-formula
3906 (org-compatible-face
3908 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3909 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3910 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3911 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
3912 (t (:bold t :italic t))))
3913 "Face for formulas."
3914 :group 'org-faces)
3916 (defface org-code
3917 (org-compatible-face
3919 '((((class color grayscale) (min-colors 88) (background light))
3920 (:foreground "grey50"))
3921 (((class color grayscale) (min-colors 88) (background dark))
3922 (:foreground "grey70"))
3923 (((class color) (min-colors 8) (background light))
3924 (:foreground "green"))
3925 (((class color) (min-colors 8) (background dark))
3926 (:foreground "yellow"))))
3927 "Face for fixed-with text like code snippets."
3928 :group 'org-faces
3929 :version "22.1")
3931 (defface org-verbatim
3932 (org-compatible-face
3934 '((((class color grayscale) (min-colors 88) (background light))
3935 (:foreground "grey50" :underline t))
3936 (((class color grayscale) (min-colors 88) (background dark))
3937 (:foreground "grey70" :underline t))
3938 (((class color) (min-colors 8) (background light))
3939 (:foreground "green" :underline t))
3940 (((class color) (min-colors 8) (background dark))
3941 (:foreground "yellow" :underline t))))
3942 "Face for fixed-with text like code snippets."
3943 :group 'org-faces
3944 :version "22.1")
3946 (defface org-agenda-structure ;; font-lock-function-name-face
3947 (org-compatible-face
3949 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3950 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3951 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3952 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3953 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3954 (t (:bold t))))
3955 "Face used in agenda for captions and dates."
3956 :group 'org-faces)
3958 (defface org-scheduled-today
3959 (org-compatible-face
3961 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
3962 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
3963 (((class color) (min-colors 8)) (:foreground "green"))
3964 (t (:bold t :italic t))))
3965 "Face for items scheduled for a certain day."
3966 :group 'org-faces)
3968 (defface org-scheduled-previously
3969 (org-compatible-face
3971 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3972 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3973 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3974 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3975 (t (:bold t))))
3976 "Face for items scheduled previously, and not yet done."
3977 :group 'org-faces)
3979 (defface org-upcoming-deadline
3980 (org-compatible-face
3982 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3983 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3984 (((class color) (min-colors 8) (background light)) (:foreground "red"))
3985 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3986 (t (:bold t))))
3987 "Face for items scheduled previously, and not yet done."
3988 :group 'org-faces)
3990 (defcustom org-agenda-deadline-faces
3991 '((1.0 . org-warning)
3992 (0.5 . org-upcoming-deadline)
3993 (0.0 . default))
3994 "Faces for showing deadlines in the agenda.
3995 This is a list of cons cells. The cdr of each cess is a face to be used,
3996 and it can also just be a like like '(:foreground \"yellow\").
3997 Each car is a fraction of the head-warning time that must have passed for
3998 this the face in the cdr to be used for display. The numbers must be
3999 given in descending order. The head-warning time is normally taken
4000 from `org-deadline-warning-days', but can also be specified in the deadline
4001 timestamp itself, like this:
4003 DEADLINE: <2007-08-13 Mon -8d>
4005 You may use d for days, w for weeks, m for months and y for years. Months
4006 and years will only be treated in an approximate fashion (30.4 days for a
4007 month and 365.24 days for a year)."
4008 :group 'org-faces
4009 :group 'org-agenda-daily/weekly
4010 :type '(repeat
4011 (cons
4012 (number :tag "Fraction of head-warning time passed")
4013 (sexp :tag "Face"))))
4015 (defface org-time-grid ;; font-lock-variable-name-face
4016 (org-compatible-face
4018 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4019 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4020 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4021 "Face used for time grids."
4022 :group 'org-faces)
4024 (defconst org-level-faces
4025 '(org-level-1 org-level-2 org-level-3 org-level-4
4026 org-level-5 org-level-6 org-level-7 org-level-8
4029 (defcustom org-n-level-faces (length org-level-faces)
4030 "The number different faces to be used for headlines.
4031 Org-mode defines 8 different headline faces, so this can be at most 8.
4032 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4033 :type 'number
4034 :group 'org-faces)
4036 ;;; Variables for pre-computed regular expressions, all buffer local
4038 (defvar org-drawer-regexp nil
4039 "Matches first line of a hidden block.")
4040 (make-variable-buffer-local 'org-drawer-regexp)
4041 (defvar org-todo-regexp nil
4042 "Matches any of the TODO state keywords.")
4043 (make-variable-buffer-local 'org-todo-regexp)
4044 (defvar org-not-done-regexp nil
4045 "Matches any of the TODO state keywords except the last one.")
4046 (make-variable-buffer-local 'org-not-done-regexp)
4047 (defvar org-todo-line-regexp nil
4048 "Matches a headline and puts TODO state into group 2 if present.")
4049 (make-variable-buffer-local 'org-todo-line-regexp)
4050 (defvar org-complex-heading-regexp nil
4051 "Matches a headline and puts everything into groups:
4052 group 1: the stars
4053 group 2: The todo keyword, maybe
4054 group 3: Priority cookie
4055 group 4: True headline
4056 group 5: Tags")
4057 (make-variable-buffer-local 'org-complex-heading-regexp)
4058 (defvar org-todo-line-tags-regexp nil
4059 "Matches a headline and puts TODO state into group 2 if present.
4060 Also put tags into group 4 if tags are present.")
4061 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4062 (defvar org-nl-done-regexp nil
4063 "Matches newline followed by a headline with the DONE keyword.")
4064 (make-variable-buffer-local 'org-nl-done-regexp)
4065 (defvar org-looking-at-done-regexp nil
4066 "Matches the DONE keyword a point.")
4067 (make-variable-buffer-local 'org-looking-at-done-regexp)
4068 (defvar org-ds-keyword-length 12
4069 "Maximum length of the Deadline and SCHEDULED keywords.")
4070 (make-variable-buffer-local 'org-ds-keyword-length)
4071 (defvar org-deadline-regexp nil
4072 "Matches the DEADLINE keyword.")
4073 (make-variable-buffer-local 'org-deadline-regexp)
4074 (defvar org-deadline-time-regexp nil
4075 "Matches the DEADLINE keyword together with a time stamp.")
4076 (make-variable-buffer-local 'org-deadline-time-regexp)
4077 (defvar org-deadline-line-regexp nil
4078 "Matches the DEADLINE keyword and the rest of the line.")
4079 (make-variable-buffer-local 'org-deadline-line-regexp)
4080 (defvar org-scheduled-regexp nil
4081 "Matches the SCHEDULED keyword.")
4082 (make-variable-buffer-local 'org-scheduled-regexp)
4083 (defvar org-scheduled-time-regexp nil
4084 "Matches the SCHEDULED keyword together with a time stamp.")
4085 (make-variable-buffer-local 'org-scheduled-time-regexp)
4086 (defvar org-closed-time-regexp nil
4087 "Matches the CLOSED keyword together with a time stamp.")
4088 (make-variable-buffer-local 'org-closed-time-regexp)
4090 (defvar org-keyword-time-regexp nil
4091 "Matches any of the 4 keywords, together with the time stamp.")
4092 (make-variable-buffer-local 'org-keyword-time-regexp)
4093 (defvar org-keyword-time-not-clock-regexp nil
4094 "Matches any of the 3 keywords, together with the time stamp.")
4095 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4096 (defvar org-maybe-keyword-time-regexp nil
4097 "Matches a timestamp, possibly preceeded by a keyword.")
4098 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4099 (defvar org-planning-or-clock-line-re nil
4100 "Matches a line with planning or clock info.")
4101 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4103 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4104 rear-nonsticky t mouse-map t fontified t)
4105 "Properties to remove when a string without properties is wanted.")
4107 (defsubst org-match-string-no-properties (num &optional string)
4108 (if (featurep 'xemacs)
4109 (let ((s (match-string num string)))
4110 (remove-text-properties 0 (length s) org-rm-props s)
4112 (match-string-no-properties num string)))
4114 (defsubst org-no-properties (s)
4115 (if (fboundp 'set-text-properties)
4116 (set-text-properties 0 (length s) nil s)
4117 (remove-text-properties 0 (length s) org-rm-props s))
4120 (defsubst org-get-alist-option (option key)
4121 (cond ((eq key t) t)
4122 ((eq option t) t)
4123 ((assoc key option) (cdr (assoc key option)))
4124 (t (cdr (assq 'default option)))))
4126 (defsubst org-inhibit-invisibility ()
4127 "Modified `buffer-invisibility-spec' for Emacs 21.
4128 Some ops with invisible text do not work correctly on Emacs 21. For these
4129 we turn off invisibility temporarily. Use this in a `let' form."
4130 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4132 (defsubst org-set-local (var value)
4133 "Make VAR local in current buffer and set it to VALUE."
4134 (set (make-variable-buffer-local var) value))
4136 (defsubst org-mode-p ()
4137 "Check if the current buffer is in Org-mode."
4138 (eq major-mode 'org-mode))
4140 (defsubst org-last (list)
4141 "Return the last element of LIST."
4142 (car (last list)))
4144 (defun org-let (list &rest body)
4145 (eval (cons 'let (cons list body))))
4146 (put 'org-let 'lisp-indent-function 1)
4148 (defun org-let2 (list1 list2 &rest body)
4149 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4150 (put 'org-let2 'lisp-indent-function 2)
4151 (defconst org-startup-options
4152 '(("fold" org-startup-folded t)
4153 ("overview" org-startup-folded t)
4154 ("nofold" org-startup-folded nil)
4155 ("showall" org-startup-folded nil)
4156 ("content" org-startup-folded content)
4157 ("hidestars" org-hide-leading-stars t)
4158 ("showstars" org-hide-leading-stars nil)
4159 ("odd" org-odd-levels-only t)
4160 ("oddeven" org-odd-levels-only nil)
4161 ("align" org-startup-align-all-tables t)
4162 ("noalign" org-startup-align-all-tables nil)
4163 ("customtime" org-display-custom-times t)
4164 ("logging" org-log-done t)
4165 ("logdone" org-log-done t)
4166 ("nologging" org-log-done nil)
4167 ("lognotedone" org-log-done done push)
4168 ("lognotestate" org-log-done state push)
4169 ("lognoteclock-out" org-log-done clock-out push)
4170 ("logrepeat" org-log-repeat t)
4171 ("nologrepeat" org-log-repeat nil)
4172 ("constcgs" constants-unit-system cgs)
4173 ("constSI" constants-unit-system SI))
4174 "Variable associated with STARTUP options for org-mode.
4175 Each element is a list of three items: The startup options as written
4176 in the #+STARTUP line, the corresponding variable, and the value to
4177 set this variable to if the option is found. An optional forth element PUSH
4178 means to push this value onto the list in the variable.")
4180 (defun org-set-regexps-and-options ()
4181 "Precompute regular expressions for current buffer."
4182 (when (org-mode-p)
4183 (org-set-local 'org-todo-kwd-alist nil)
4184 (org-set-local 'org-todo-key-alist nil)
4185 (org-set-local 'org-todo-key-trigger nil)
4186 (org-set-local 'org-todo-keywords-1 nil)
4187 (org-set-local 'org-done-keywords nil)
4188 (org-set-local 'org-todo-heads nil)
4189 (org-set-local 'org-todo-sets nil)
4190 (org-set-local 'org-todo-log-states nil)
4191 (let ((re (org-make-options-regexp
4192 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4193 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4194 "CONSTANTS" "PROPERTY" "DRAWERS")))
4195 (splitre "[ \t]+")
4196 kwds kws0 kwsa key value cat arch tags const links hw dws
4197 tail sep kws1 prio props drawers
4198 ex log)
4199 (save-excursion
4200 (save-restriction
4201 (widen)
4202 (goto-char (point-min))
4203 (while (re-search-forward re nil t)
4204 (setq key (match-string 1) value (org-match-string-no-properties 2))
4205 (cond
4206 ((equal key "CATEGORY")
4207 (if (string-match "[ \t]+$" value)
4208 (setq value (replace-match "" t t value)))
4209 (setq cat value))
4210 ((member key '("SEQ_TODO" "TODO"))
4211 (push (cons 'sequence (org-split-string value splitre)) kwds))
4212 ((equal key "TYP_TODO")
4213 (push (cons 'type (org-split-string value splitre)) kwds))
4214 ((equal key "TAGS")
4215 (setq tags (append tags (org-split-string value splitre))))
4216 ((equal key "COLUMNS")
4217 (org-set-local 'org-columns-default-format value))
4218 ((equal key "LINK")
4219 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4220 (push (cons (match-string 1 value)
4221 (org-trim (match-string 2 value)))
4222 links)))
4223 ((equal key "PRIORITIES")
4224 (setq prio (org-split-string value " +")))
4225 ((equal key "PROPERTY")
4226 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4227 (push (cons (match-string 1 value) (match-string 2 value))
4228 props)))
4229 ((equal key "DRAWERS")
4230 (setq drawers (org-split-string value splitre)))
4231 ((equal key "CONSTANTS")
4232 (setq const (append const (org-split-string value splitre))))
4233 ((equal key "STARTUP")
4234 (let ((opts (org-split-string value splitre))
4235 l var val)
4236 (while (setq l (pop opts))
4237 (when (setq l (assoc l org-startup-options))
4238 (setq var (nth 1 l) val (nth 2 l))
4239 (if (not (nth 3 l))
4240 (set (make-local-variable var) val)
4241 (if (not (listp (symbol-value var)))
4242 (set (make-local-variable var) nil))
4243 (set (make-local-variable var) (symbol-value var))
4244 (add-to-list var val))))))
4245 ((equal key "ARCHIVE")
4246 (string-match " *$" value)
4247 (setq arch (replace-match "" t t value))
4248 (remove-text-properties 0 (length arch)
4249 '(face t fontified t) arch)))
4251 (when cat
4252 (org-set-local 'org-category (intern cat))
4253 (push (cons "CATEGORY" cat) props))
4254 (when prio
4255 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4256 (setq prio (mapcar 'string-to-char prio))
4257 (org-set-local 'org-highest-priority (nth 0 prio))
4258 (org-set-local 'org-lowest-priority (nth 1 prio))
4259 (org-set-local 'org-default-priority (nth 2 prio)))
4260 (and props (org-set-local 'org-local-properties (nreverse props)))
4261 (and drawers (org-set-local 'org-drawers drawers))
4262 (and arch (org-set-local 'org-archive-location arch))
4263 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4264 ;; Process the TODO keywords
4265 (unless kwds
4266 ;; Use the global values as if they had been given locally.
4267 (setq kwds (default-value 'org-todo-keywords))
4268 (if (stringp (car kwds))
4269 (setq kwds (list (cons org-todo-interpretation
4270 (default-value 'org-todo-keywords)))))
4271 (setq kwds (reverse kwds)))
4272 (setq kwds (nreverse kwds))
4273 (let (inter kws kw)
4274 (while (setq kws (pop kwds))
4275 (setq inter (pop kws) sep (member "|" kws)
4276 kws0 (delete "|" (copy-sequence kws))
4277 kwsa nil
4278 kws1 (mapcar
4279 (lambda (x)
4280 (if (string-match "^\\(.*?\\)\\(?:(\\(..?\\))\\)?$" x)
4281 (progn
4282 (setq kw (match-string 1 x)
4283 ex (and (match-end 2) (match-string 2 x))
4284 log (and ex (string-match "@" ex))
4285 key (and ex (substring ex 0 1)))
4286 (if (equal key "@") (setq key nil))
4287 (push (cons kw (and key (string-to-char key))) kwsa)
4288 (and log (push kw org-todo-log-states))
4290 (error "Invalid TODO keyword %s" x)))
4291 kws0)
4292 kwsa (if kwsa (append '((:startgroup))
4293 (nreverse kwsa)
4294 '((:endgroup))))
4295 hw (car kws1)
4296 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4297 tail (list inter hw (car dws) (org-last dws)))
4298 (add-to-list 'org-todo-heads hw 'append)
4299 ;????????????????? (setq org-todo-heads (append org-todo-heads (list hw)))
4300 (add-to-list 'org-todo-heads hw 'append)
4301 (push kws1 org-todo-sets)
4302 (setq org-done-keywords (append org-done-keywords dws nil))
4303 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4304 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4305 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4306 (setq org-todo-sets (nreverse org-todo-sets)
4307 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4308 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4309 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4310 ;; Process the constants
4311 (when const
4312 (let (e cst)
4313 (while (setq e (pop const))
4314 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4315 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4316 (setq org-table-formula-constants-local cst)))
4318 ;; Process the tags.
4319 (when tags
4320 (let (e tgs)
4321 (while (setq e (pop tags))
4322 (cond
4323 ((equal e "{") (push '(:startgroup) tgs))
4324 ((equal e "}") (push '(:endgroup) tgs))
4325 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4326 (push (cons (match-string 1 e)
4327 (string-to-char (match-string 2 e)))
4328 tgs))
4329 (t (push (list e) tgs))))
4330 (org-set-local 'org-tag-alist nil)
4331 (while (setq e (pop tgs))
4332 (or (and (stringp (car e))
4333 (assoc (car e) org-tag-alist))
4334 (push e org-tag-alist))))))
4336 ;; Compute the regular expressions and other local variables
4337 (if (not org-done-keywords)
4338 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4339 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4340 (length org-scheduled-string)))
4341 org-drawer-regexp
4342 (concat "^[ \t]*:\\("
4343 (mapconcat 'regexp-quote org-drawers "\\|")
4344 "\\):[ \t]*$")
4345 org-not-done-keywords
4346 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4347 org-todo-regexp
4348 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4349 "\\|") "\\)\\>")
4350 org-not-done-regexp
4351 (concat "\\<\\("
4352 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4353 "\\)\\>")
4354 org-todo-line-regexp
4355 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4356 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4357 "\\)\\>\\)?[ \t]*\\(.*\\)")
4358 org-complex-heading-regexp
4359 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4360 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4361 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4362 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4363 org-nl-done-regexp
4364 (concat "\n\\*+[ \t]+"
4365 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4366 "\\)" "\\>")
4367 org-todo-line-tags-regexp
4368 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4369 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4370 (org-re
4371 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4372 org-looking-at-done-regexp
4373 (concat "^" "\\(?:"
4374 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4375 "\\>")
4376 org-deadline-regexp (concat "\\<" org-deadline-string)
4377 org-deadline-time-regexp
4378 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4379 org-deadline-line-regexp
4380 (concat "\\<\\(" org-deadline-string "\\).*")
4381 org-scheduled-regexp
4382 (concat "\\<" org-scheduled-string)
4383 org-scheduled-time-regexp
4384 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4385 org-closed-time-regexp
4386 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4387 org-keyword-time-regexp
4388 (concat "\\<\\(" org-scheduled-string
4389 "\\|" org-deadline-string
4390 "\\|" org-closed-string
4391 "\\|" org-clock-string "\\)"
4392 " *[[<]\\([^]>]+\\)[]>]")
4393 org-keyword-time-not-clock-regexp
4394 (concat "\\<\\(" org-scheduled-string
4395 "\\|" org-deadline-string
4396 "\\|" org-closed-string
4397 "\\)"
4398 " *[[<]\\([^]>]+\\)[]>]")
4399 org-maybe-keyword-time-regexp
4400 (concat "\\(\\<\\(" org-scheduled-string
4401 "\\|" org-deadline-string
4402 "\\|" org-closed-string
4403 "\\|" org-clock-string "\\)\\)?"
4404 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4405 org-planning-or-clock-line-re
4406 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4407 "\\|" org-deadline-string
4408 "\\|" org-closed-string "\\|" org-clock-string
4409 "\\)\\>\\)")
4411 (org-compute-latex-and-specials-regexp)
4412 (org-set-font-lock-defaults)))
4414 (defun org-remove-keyword-keys (list)
4415 (mapcar (lambda (x)
4416 (if (string-match "(..?)$" x)
4417 (substring x 0 (match-beginning 0))
4419 list))
4421 ;;; Some variables ujsed in various places
4423 (defvar org-window-configuration nil
4424 "Used in various places to store a window configuration.")
4425 (defvar org-finish-function nil
4426 "Function to be called when `C-c C-c' is used.
4427 This is for getting out of special buffers like remember.")
4429 ;;; Foreign variables, to inform the compiler
4431 ;; XEmacs only
4432 (defvar outline-mode-menu-heading)
4433 (defvar outline-mode-menu-show)
4434 (defvar outline-mode-menu-hide)
4435 (defvar zmacs-regions) ; XEmacs regions
4436 ;; Emacs only
4437 (defvar mark-active)
4439 ;; Packages that org-mode interacts with
4440 (defvar calc-embedded-close-formula)
4441 (defvar calc-embedded-open-formula)
4442 (defvar font-lock-unfontify-region-function)
4443 (defvar org-goto-start-pos)
4444 (defvar vm-message-pointer)
4445 (defvar vm-folder-directory)
4446 (defvar wl-summary-buffer-elmo-folder)
4447 (defvar wl-summary-buffer-folder-name)
4448 (defvar gnus-other-frame-object)
4449 (defvar gnus-group-name)
4450 (defvar gnus-article-current)
4451 (defvar w3m-current-url)
4452 (defvar w3m-current-title)
4453 (defvar mh-progs)
4454 (defvar mh-current-folder)
4455 (defvar mh-show-folder-buffer)
4456 (defvar mh-index-folder)
4457 (defvar mh-searcher)
4458 (defvar calendar-mode-map)
4459 (defvar Info-current-file)
4460 (defvar Info-current-node)
4461 (defvar texmathp-why)
4462 (defvar remember-save-after-remembering)
4463 (defvar remember-data-file)
4464 (defvar remember-register)
4465 (defvar remember-buffer)
4466 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
4467 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
4468 (defvar org-latex-regexps)
4469 (defvar constants-unit-system)
4471 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4473 ;; FIXME: Occasionally check by commenting these, to make sure
4474 ;; no other functions uses these, forgetting to let-bind them.
4475 (defvar entry)
4476 (defvar state)
4477 (defvar last-state)
4478 (defvar date)
4479 (defvar description)
4481 ;; Defined somewhere in this file, but used before definition.
4482 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4483 (defvar org-agenda-buffer-name)
4484 (defvar org-agenda-undo-list)
4485 (defvar org-agenda-pending-undo-list)
4486 (defvar org-agenda-overriding-header)
4487 (defvar orgtbl-mode)
4488 (defvar org-html-entities)
4489 (defvar org-struct-menu)
4490 (defvar org-org-menu)
4491 (defvar org-tbl-menu)
4492 (defvar org-agenda-keymap)
4494 ;;;; Emacs/XEmacs compatibility
4496 ;; Overlay compatibility functions
4497 (defun org-make-overlay (beg end &optional buffer)
4498 (if (featurep 'xemacs)
4499 (make-extent beg end buffer)
4500 (make-overlay beg end buffer)))
4501 (defun org-delete-overlay (ovl)
4502 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4503 (defun org-detach-overlay (ovl)
4504 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4505 (defun org-move-overlay (ovl beg end &optional buffer)
4506 (if (featurep 'xemacs)
4507 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4508 (move-overlay ovl beg end buffer)))
4509 (defun org-overlay-put (ovl prop value)
4510 (if (featurep 'xemacs)
4511 (set-extent-property ovl prop value)
4512 (overlay-put ovl prop value)))
4513 (defun org-overlay-display (ovl text &optional face evap)
4514 "Make overlay OVL display TEXT with face FACE."
4515 (if (featurep 'xemacs)
4516 (let ((gl (make-glyph text)))
4517 (and face (set-glyph-face gl face))
4518 (set-extent-property ovl 'invisible t)
4519 (set-extent-property ovl 'end-glyph gl))
4520 (overlay-put ovl 'display text)
4521 (if face (overlay-put ovl 'face face))
4522 (if evap (overlay-put ovl 'evaporate t))))
4523 (defun org-overlay-before-string (ovl text &optional face evap)
4524 "Make overlay OVL display TEXT with face FACE."
4525 (if (featurep 'xemacs)
4526 (let ((gl (make-glyph text)))
4527 (and face (set-glyph-face gl face))
4528 (set-extent-property ovl 'begin-glyph gl))
4529 (if face (org-add-props text nil 'face face))
4530 (overlay-put ovl 'before-string text)
4531 (if evap (overlay-put ovl 'evaporate t))))
4532 (defun org-overlay-get (ovl prop)
4533 (if (featurep 'xemacs)
4534 (extent-property ovl prop)
4535 (overlay-get ovl prop)))
4536 (defun org-overlays-at (pos)
4537 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4538 (defun org-overlays-in (&optional start end)
4539 (if (featurep 'xemacs)
4540 (extent-list nil start end)
4541 (overlays-in start end)))
4542 (defun org-overlay-start (o)
4543 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4544 (defun org-overlay-end (o)
4545 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4546 (defun org-find-overlays (prop &optional pos delete)
4547 "Find all overlays specifying PROP at POS or point.
4548 If DELETE is non-nil, delete all those overlays."
4549 (let ((overlays (org-overlays-at (or pos (point))))
4550 ov found)
4551 (while (setq ov (pop overlays))
4552 (if (org-overlay-get ov prop)
4553 (if delete (org-delete-overlay ov) (push ov found))))
4554 found))
4556 ;; Region compatibility
4558 (defun org-add-hook (hook function &optional append local)
4559 "Add-hook, compatible with both Emacsen."
4560 (if (and local (featurep 'xemacs))
4561 (add-local-hook hook function append)
4562 (add-hook hook function append local)))
4564 (defvar org-ignore-region nil
4565 "To temporarily disable the active region.")
4567 (defun org-region-active-p ()
4568 "Is `transient-mark-mode' on and the region active?
4569 Works on both Emacs and XEmacs."
4570 (if org-ignore-region
4572 (if (featurep 'xemacs)
4573 (and zmacs-regions (region-active-p))
4574 (and transient-mark-mode mark-active))))
4576 ;; Invisibility compatibility
4578 (defun org-add-to-invisibility-spec (arg)
4579 "Add elements to `buffer-invisibility-spec'.
4580 See documentation for `buffer-invisibility-spec' for the kind of elements
4581 that can be added."
4582 (cond
4583 ((fboundp 'add-to-invisibility-spec)
4584 (add-to-invisibility-spec arg))
4585 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4586 (setq buffer-invisibility-spec (list arg)))
4588 (setq buffer-invisibility-spec
4589 (cons arg buffer-invisibility-spec)))))
4591 (defun org-remove-from-invisibility-spec (arg)
4592 "Remove elements from `buffer-invisibility-spec'."
4593 (if (fboundp 'remove-from-invisibility-spec)
4594 (remove-from-invisibility-spec arg)
4595 (if (consp buffer-invisibility-spec)
4596 (setq buffer-invisibility-spec
4597 (delete arg buffer-invisibility-spec)))))
4599 (defun org-in-invisibility-spec-p (arg)
4600 "Is ARG a member of `buffer-invisibility-spec'?"
4601 (if (consp buffer-invisibility-spec)
4602 (member arg buffer-invisibility-spec)
4603 nil))
4605 ;;;; Define the Org-mode
4607 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4608 (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."))
4611 ;; We use a before-change function to check if a table might need
4612 ;; an update.
4613 (defvar org-table-may-need-update t
4614 "Indicates that a table might need an update.
4615 This variable is set by `org-before-change-function'.
4616 `org-table-align' sets it back to nil.")
4617 (defvar org-mode-map)
4618 (defvar org-mode-hook nil)
4619 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4620 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4621 (defvar org-table-buffer-is-an nil)
4622 (defconst org-outline-regexp "\\*+ ")
4624 ;;;###autoload
4625 (define-derived-mode org-mode outline-mode "Org"
4626 "Outline-based notes management and organizer, alias
4627 \"Carsten's outline-mode for keeping track of everything.\"
4629 Org-mode develops organizational tasks around a NOTES file which
4630 contains information about projects as plain text. Org-mode is
4631 implemented on top of outline-mode, which is ideal to keep the content
4632 of large files well structured. It supports ToDo items, deadlines and
4633 time stamps, which magically appear in the diary listing of the Emacs
4634 calendar. Tables are easily created with a built-in table editor.
4635 Plain text URL-like links connect to websites, emails (VM), Usenet
4636 messages (Gnus), BBDB entries, and any files related to the project.
4637 For printing and sharing of notes, an Org-mode file (or a part of it)
4638 can be exported as a structured ASCII or HTML file.
4640 The following commands are available:
4642 \\{org-mode-map}"
4644 ;; Get rid of Outline menus, they are not needed
4645 ;; Need to do this here because define-derived-mode sets up
4646 ;; the keymap so late. Still, it is a waste to call this each time
4647 ;; we switch another buffer into org-mode.
4648 (if (featurep 'xemacs)
4649 (when (boundp 'outline-mode-menu-heading)
4650 ;; Assume this is Greg's port, it used easymenu
4651 (easy-menu-remove outline-mode-menu-heading)
4652 (easy-menu-remove outline-mode-menu-show)
4653 (easy-menu-remove outline-mode-menu-hide))
4654 (define-key org-mode-map [menu-bar headings] 'undefined)
4655 (define-key org-mode-map [menu-bar hide] 'undefined)
4656 (define-key org-mode-map [menu-bar show] 'undefined))
4658 (easy-menu-add org-org-menu)
4659 (easy-menu-add org-tbl-menu)
4660 (org-install-agenda-files-menu)
4661 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4662 (org-add-to-invisibility-spec '(org-cwidth))
4663 (when (featurep 'xemacs)
4664 (org-set-local 'line-move-ignore-invisible t))
4665 (org-set-local 'outline-regexp org-outline-regexp)
4666 (org-set-local 'outline-level 'org-outline-level)
4667 (when (and org-ellipsis
4668 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4669 (fboundp 'make-glyph-code))
4670 (unless org-display-table
4671 (setq org-display-table (make-display-table)))
4672 (set-display-table-slot
4673 org-display-table 4
4674 (vconcat (mapcar
4675 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4676 org-ellipsis)))
4677 (if (stringp org-ellipsis) org-ellipsis "..."))))
4678 (setq buffer-display-table org-display-table))
4679 (org-set-regexps-and-options)
4680 ;; Calc embedded
4681 (org-set-local 'calc-embedded-open-mode "# ")
4682 (modify-syntax-entry ?# "<")
4683 (modify-syntax-entry ?@ "w")
4684 (if org-startup-truncated (setq truncate-lines t))
4685 (org-set-local 'font-lock-unfontify-region-function
4686 'org-unfontify-region)
4687 ;; Activate before-change-function
4688 (org-set-local 'org-table-may-need-update t)
4689 (org-add-hook 'before-change-functions 'org-before-change-function nil
4690 'local)
4691 ;; Check for running clock before killing a buffer
4692 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4693 ;; Paragraphs and auto-filling
4694 (org-set-autofill-regexps)
4695 (setq indent-line-function 'org-indent-line-function)
4696 (org-update-radio-target-regexp)
4698 ;; Comment characters
4699 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4700 (org-set-local 'comment-padding " ")
4702 ;; Make isearch reveal context
4703 (if (or (featurep 'xemacs)
4704 (not (boundp 'outline-isearch-open-invisible-function)))
4705 ;; Emacs 21 and XEmacs make use of the hook
4706 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4707 ;; Emacs 22 deals with this through a special variable
4708 (org-set-local 'outline-isearch-open-invisible-function
4709 (lambda (&rest ignore) (org-show-context 'isearch))))
4711 ;; If empty file that did not turn on org-mode automatically, make it to.
4712 (if (and org-insert-mode-line-in-empty-file
4713 (interactive-p)
4714 (= (point-min) (point-max)))
4715 (insert "# -*- mode: org -*-\n\n"))
4717 (unless org-inhibit-startup
4718 (when org-startup-align-all-tables
4719 (let ((bmp (buffer-modified-p)))
4720 (org-table-map-tables 'org-table-align)
4721 (set-buffer-modified-p bmp)))
4722 (org-cycle-hide-drawers 'all)
4723 (cond
4724 ((eq org-startup-folded t)
4725 (org-cycle '(4)))
4726 ((eq org-startup-folded 'content)
4727 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4728 (org-cycle '(4)) (org-cycle '(4)))))))
4730 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4732 (defsubst org-call-with-arg (command arg)
4733 "Call COMMAND interactively, but pretend prefix are was ARG."
4734 (let ((current-prefix-arg arg)) (call-interactively command)))
4736 (defsubst org-current-line (&optional pos)
4737 (save-excursion
4738 (and pos (goto-char pos))
4739 ;; works also in narrowed buffer, because we start at 1, not point-min
4740 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
4742 (defun org-current-time ()
4743 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4744 (if (> org-time-stamp-rounding-minutes 0)
4745 (let ((r org-time-stamp-rounding-minutes)
4746 (time (decode-time)))
4747 (apply 'encode-time
4748 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4749 (nthcdr 2 time))))
4750 (current-time)))
4752 (defun org-add-props (string plist &rest props)
4753 "Add text properties to entire string, from beginning to end.
4754 PLIST may be a list of properties, PROPS are individual properties and values
4755 that will be added to PLIST. Returns the string that was modified."
4756 (add-text-properties
4757 0 (length string) (if props (append plist props) plist) string)
4758 string)
4759 (put 'org-add-props 'lisp-indent-function 2)
4762 ;;;; Font-Lock stuff, including the activators
4764 (defvar org-mouse-map (make-sparse-keymap))
4765 (org-defkey org-mouse-map
4766 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4767 (org-defkey org-mouse-map
4768 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4769 (when org-mouse-1-follows-link
4770 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4771 (when org-tab-follows-link
4772 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4773 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4774 (when org-return-follows-link
4775 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
4776 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
4778 (require 'font-lock)
4780 (defconst org-non-link-chars "]\t\n\r<>")
4781 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
4782 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
4783 (defvar org-link-re-with-space nil
4784 "Matches a link with spaces, optional angular brackets around it.")
4785 (defvar org-link-re-with-space2 nil
4786 "Matches a link with spaces, optional angular brackets around it.")
4787 (defvar org-angle-link-re nil
4788 "Matches link with angular brackets, spaces are allowed.")
4789 (defvar org-plain-link-re nil
4790 "Matches plain link, without spaces.")
4791 (defvar org-bracket-link-regexp nil
4792 "Matches a link in double brackets.")
4793 (defvar org-bracket-link-analytic-regexp nil
4794 "Regular expression used to analyze links.
4795 Here is what the match groups contain after a match:
4796 1: http:
4797 2: http
4798 3: path
4799 4: [desc]
4800 5: desc")
4801 (defvar org-any-link-re nil
4802 "Regular expression matching any link.")
4804 (defun org-make-link-regexps ()
4805 "Update the link regular expressions.
4806 This should be called after the variable `org-link-types' has changed."
4807 (setq org-link-re-with-space
4808 (concat
4809 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4810 "\\([^" org-non-link-chars " ]"
4811 "[^" org-non-link-chars "]*"
4812 "[^" org-non-link-chars " ]\\)>?")
4813 org-link-re-with-space2
4814 (concat
4815 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4816 "\\([^" org-non-link-chars " ]"
4817 "[^]\t\n\r]*"
4818 "[^" org-non-link-chars " ]\\)>?")
4819 org-angle-link-re
4820 (concat
4821 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4822 "\\([^" org-non-link-chars " ]"
4823 "[^" org-non-link-chars "]*"
4824 "\\)>")
4825 org-plain-link-re
4826 (concat
4827 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4828 "\\([^]\t\n\r<>,;() ]+\\)")
4829 org-bracket-link-regexp
4830 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4831 org-bracket-link-analytic-regexp
4832 (concat
4833 "\\[\\["
4834 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4835 "\\([^]]+\\)"
4836 "\\]"
4837 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4838 "\\]")
4839 org-any-link-re
4840 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4841 org-angle-link-re "\\)\\|\\("
4842 org-plain-link-re "\\)")))
4844 (org-make-link-regexps)
4846 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4847 "Regular expression for fast time stamp matching.")
4848 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4849 "Regular expression for fast time stamp matching.")
4850 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4851 "Regular expression matching time strings for analysis.
4852 This one does not require the space after the date.")
4853 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4854 "Regular expression matching time strings for analysis.")
4855 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4856 "Regular expression matching time stamps, with groups.")
4857 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4858 "Regular expression matching time stamps (also [..]), with groups.")
4859 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4860 "Regular expression matching a time stamp range.")
4861 (defconst org-tr-regexp-both
4862 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4863 "Regular expression matching a time stamp range.")
4864 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4865 org-ts-regexp "\\)?")
4866 "Regular expression matching a time stamp or time stamp range.")
4867 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4868 org-ts-regexp-both "\\)?")
4869 "Regular expression matching a time stamp or time stamp range.
4870 The time stamps may be either active or inactive.")
4872 (defvar org-emph-face nil)
4874 (defun org-do-emphasis-faces (limit)
4875 "Run through the buffer and add overlays to links."
4876 (let (rtn)
4877 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4878 (if (not (= (char-after (match-beginning 3))
4879 (char-after (match-beginning 4))))
4880 (progn
4881 (setq rtn t)
4882 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4883 'face
4884 (nth 1 (assoc (match-string 3)
4885 org-emphasis-alist)))
4886 (add-text-properties (match-beginning 2) (match-end 2)
4887 '(font-lock-multiline t))
4888 (when org-hide-emphasis-markers
4889 (add-text-properties (match-end 4) (match-beginning 5)
4890 '(invisible org-link))
4891 (add-text-properties (match-beginning 3) (match-end 3)
4892 '(invisible org-link)))))
4893 (backward-char 1))
4894 rtn))
4896 (defun org-emphasize (&optional char)
4897 "Insert or change an emphasis, i.e. a font like bold or italic.
4898 If there is an active region, change that region to a new emphasis.
4899 If there is no region, just insert the marker characters and position
4900 the cursor between them.
4901 CHAR should be either the marker character, or the first character of the
4902 HTML tag associated with that emphasis. If CHAR is a space, the means
4903 to remove the emphasis of the selected region.
4904 If char is not given (for example in an interactive call) it
4905 will be prompted for."
4906 (interactive)
4907 (let ((eal org-emphasis-alist) e det
4908 (erc org-emphasis-regexp-components)
4909 (prompt "")
4910 (string "") beg end move tag c s)
4911 (if (org-region-active-p)
4912 (setq beg (region-beginning) end (region-end)
4913 string (buffer-substring beg end))
4914 (setq move t))
4916 (while (setq e (pop eal))
4917 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4918 c (aref tag 0))
4919 (push (cons c (string-to-char (car e))) det)
4920 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4921 (substring tag 1)))))
4922 (unless char
4923 (message "%s" (concat "Emphasis marker or tag:" prompt))
4924 (setq char (read-char-exclusive)))
4925 (setq char (or (cdr (assoc char det)) char))
4926 (if (equal char ?\ )
4927 (setq s "" move nil)
4928 (unless (assoc (char-to-string char) org-emphasis-alist)
4929 (error "No such emphasis marker: \"%c\"" char))
4930 (setq s (char-to-string char)))
4931 (while (and (> (length string) 1)
4932 (equal (substring string 0 1) (substring string -1))
4933 (assoc (substring string 0 1) org-emphasis-alist))
4934 (setq string (substring string 1 -1)))
4935 (setq string (concat s string s))
4936 (if beg (delete-region beg end))
4937 (unless (or (bolp)
4938 (string-match (concat "[" (nth 0 erc) "\n]")
4939 (char-to-string (char-before (point)))))
4940 (insert " "))
4941 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4942 (char-to-string (char-after (point))))
4943 (insert " ") (backward-char 1))
4944 (insert string)
4945 (and move (backward-char 1))))
4947 (defconst org-nonsticky-props
4948 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4951 (defun org-activate-plain-links (limit)
4952 "Run through the buffer and add overlays to links."
4953 (catch 'exit
4954 (let (f)
4955 (while (re-search-forward org-plain-link-re limit t)
4956 (setq f (get-text-property (match-beginning 0) 'face))
4957 (if (or (eq f 'org-tag)
4958 (and (listp f) (memq 'org-tag f)))
4960 (add-text-properties (match-beginning 0) (match-end 0)
4961 (list 'mouse-face 'highlight
4962 'rear-nonsticky org-nonsticky-props
4963 'keymap org-mouse-map
4965 (throw 'exit t))))))
4967 (defun org-activate-code (limit)
4968 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
4969 (unless (get-text-property (match-beginning 1) 'face)
4970 (remove-text-properties (match-beginning 0) (match-end 0)
4971 '(display t invisible t intangible t))
4972 t)))
4974 (defun org-activate-angle-links (limit)
4975 "Run through the buffer and add overlays to links."
4976 (if (re-search-forward org-angle-link-re limit t)
4977 (progn
4978 (add-text-properties (match-beginning 0) (match-end 0)
4979 (list 'mouse-face 'highlight
4980 'rear-nonsticky org-nonsticky-props
4981 'keymap org-mouse-map
4983 t)))
4985 (defmacro org-maybe-intangible (props)
4986 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
4987 In emacs 21, invisible text is not avoided by the command loop, so the
4988 intangible property is needed to make sure point skips this text.
4989 In Emacs 22, this is not necessary. The intangible text property has
4990 led to problems with flyspell. These problems are fixed in flyspell.el,
4991 but we still avoid setting the property in Emacs 22 and later.
4992 We use a macro so that the test can happen at compilation time."
4993 (if (< emacs-major-version 22)
4994 `(append '(intangible t) ,props)
4995 props))
4997 (defun org-activate-bracket-links (limit)
4998 "Run through the buffer and add overlays to bracketed links."
4999 (if (re-search-forward org-bracket-link-regexp limit t)
5000 (let* ((help (concat "LINK: "
5001 (org-match-string-no-properties 1)))
5002 ;; FIXME: above we should remove the escapes.
5003 ;; but that requires another match, protecting match data,
5004 ;; a lot of overhead for font-lock.
5005 (ip (org-maybe-intangible
5006 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5007 'keymap org-mouse-map 'mouse-face 'highlight
5008 'font-lock-multiline t 'help-echo help)))
5009 (vp (list 'rear-nonsticky org-nonsticky-props
5010 'keymap org-mouse-map 'mouse-face 'highlight
5011 ' font-lock-multiline t 'help-echo help)))
5012 ;; We need to remove the invisible property here. Table narrowing
5013 ;; may have made some of this invisible.
5014 (remove-text-properties (match-beginning 0) (match-end 0)
5015 '(invisible nil))
5016 (if (match-end 3)
5017 (progn
5018 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5019 (add-text-properties (match-beginning 3) (match-end 3) vp)
5020 (add-text-properties (match-end 3) (match-end 0) ip))
5021 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5022 (add-text-properties (match-beginning 1) (match-end 1) vp)
5023 (add-text-properties (match-end 1) (match-end 0) ip))
5024 t)))
5026 (defun org-activate-dates (limit)
5027 "Run through the buffer and add overlays to dates."
5028 (if (re-search-forward org-tsr-regexp-both limit t)
5029 (progn
5030 (add-text-properties (match-beginning 0) (match-end 0)
5031 (list 'mouse-face 'highlight
5032 'rear-nonsticky org-nonsticky-props
5033 'keymap org-mouse-map))
5034 (when org-display-custom-times
5035 (if (match-end 3)
5036 (org-display-custom-time (match-beginning 3) (match-end 3)))
5037 (org-display-custom-time (match-beginning 1) (match-end 1)))
5038 t)))
5040 (defvar org-target-link-regexp nil
5041 "Regular expression matching radio targets in plain text.")
5042 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5043 "Regular expression matching a link target.")
5044 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5045 "Regular expression matching a radio target.")
5046 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5047 "Regular expression matching any target.")
5049 (defun org-activate-target-links (limit)
5050 "Run through the buffer and add overlays to target matches."
5051 (when org-target-link-regexp
5052 (let ((case-fold-search t))
5053 (if (re-search-forward org-target-link-regexp limit t)
5054 (progn
5055 (add-text-properties (match-beginning 0) (match-end 0)
5056 (list 'mouse-face 'highlight
5057 'rear-nonsticky org-nonsticky-props
5058 'keymap org-mouse-map
5059 'help-echo "Radio target link"
5060 'org-linked-text t))
5061 t)))))
5063 (defun org-update-radio-target-regexp ()
5064 "Find all radio targets in this file and update the regular expression."
5065 (interactive)
5066 (when (memq 'radio org-activate-links)
5067 (setq org-target-link-regexp
5068 (org-make-target-link-regexp (org-all-targets 'radio)))
5069 (org-restart-font-lock)))
5071 (defun org-hide-wide-columns (limit)
5072 (let (s e)
5073 (setq s (text-property-any (point) (or limit (point-max))
5074 'org-cwidth t))
5075 (when s
5076 (setq e (next-single-property-change s 'org-cwidth))
5077 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5078 (goto-char e)
5079 t)))
5081 (defun org-restart-font-lock ()
5082 "Restart font-lock-mode, to force refontification."
5083 (when (and (boundp 'font-lock-mode) font-lock-mode)
5084 (font-lock-mode -1)
5085 (font-lock-mode 1)))
5087 (defun org-all-targets (&optional radio)
5088 "Return a list of all targets in this file.
5089 With optional argument RADIO, only find radio targets."
5090 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5091 rtn)
5092 (save-excursion
5093 (goto-char (point-min))
5094 (while (re-search-forward re nil t)
5095 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5096 rtn)))
5098 (defun org-make-target-link-regexp (targets)
5099 "Make regular expression matching all strings in TARGETS.
5100 The regular expression finds the targets also if there is a line break
5101 between words."
5102 (and targets
5103 (concat
5104 "\\<\\("
5105 (mapconcat
5106 (lambda (x)
5107 (while (string-match " +" x)
5108 (setq x (replace-match "\\s-+" t t x)))
5110 targets
5111 "\\|")
5112 "\\)\\>")))
5114 (defun org-activate-tags (limit)
5115 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5116 (progn
5117 (add-text-properties (match-beginning 1) (match-end 1)
5118 (list 'mouse-face 'highlight
5119 'rear-nonsticky org-nonsticky-props
5120 'keymap org-mouse-map))
5121 t)))
5123 (defun org-outline-level ()
5124 (save-excursion
5125 (looking-at outline-regexp)
5126 (if (match-beginning 1)
5127 (+ (org-get-string-indentation (match-string 1)) 1000)
5128 (1- (- (match-end 0) (match-beginning 0))))))
5130 (defvar org-font-lock-keywords nil)
5132 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5133 "Regular expression matching a property line.")
5135 (defun org-set-font-lock-defaults ()
5136 (let* ((em org-fontify-emphasized-text)
5137 (lk org-activate-links)
5138 (org-font-lock-extra-keywords
5139 (list
5140 ;; Headlines
5141 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5142 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5143 ;; Table lines
5144 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5145 (1 'org-table t))
5146 ;; Table internals
5147 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5148 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5149 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5150 ;; Drawers
5151 (list org-drawer-regexp '(0 'org-special-keyword t))
5152 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5153 ;; Properties
5154 (list org-property-re
5155 '(1 'org-special-keyword t)
5156 '(3 'org-property-value t))
5157 (if org-format-transports-properties-p
5158 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5159 ;; Links
5160 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5161 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5162 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5163 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5164 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5165 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5166 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5167 '(org-hide-wide-columns (0 nil append))
5168 ;; TODO lines
5169 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5170 '(1 (org-get-todo-face 1) t))
5171 ;; DONE
5172 (if org-fontify-done-headline
5173 (list (concat "^[*]+ +\\<\\("
5174 (mapconcat 'regexp-quote org-done-keywords "\\|")
5175 "\\)\\(.*\\)")
5176 '(2 'org-headline-done t))
5177 nil)
5178 ;; Priorities
5179 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5180 ;; Special keywords
5181 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5182 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5183 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5184 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5185 ;; Emphasis
5186 (if em
5187 (if (featurep 'xemacs)
5188 '(org-do-emphasis-faces (0 nil append))
5189 '(org-do-emphasis-faces)))
5190 ;; Checkboxes
5191 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5192 2 'bold prepend)
5193 (if org-provide-checkbox-statistics
5194 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5195 (0 (org-get-checkbox-statistics-face) t)))
5196 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5197 '(1 'org-archived prepend))
5198 ;; Specials
5199 '(org-do-latex-and-special-faces)
5200 ;; Code
5201 '(org-activate-code (1 'org-code t))
5202 ;; COMMENT
5203 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5204 "\\|" org-quote-string "\\)\\>")
5205 '(1 'org-special-keyword t))
5206 '("^#.*" (0 'font-lock-comment-face t))
5208 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5209 ;; Now set the full font-lock-keywords
5210 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5211 (org-set-local 'font-lock-defaults
5212 '(org-font-lock-keywords t nil nil backward-paragraph))
5213 (kill-local-variable 'font-lock-keywords) nil))
5215 (defvar org-m nil)
5216 (defvar org-l nil)
5217 (defvar org-f nil)
5218 (defun org-get-level-face (n)
5219 "Get the right face for match N in font-lock matching of healdines."
5220 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5221 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5222 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5223 (cond
5224 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5225 ((eq n 2) org-f)
5226 (t (if org-level-color-stars-only nil org-f))))
5228 (defun org-get-todo-face (kwd)
5229 "Get the right face for a TODO keyword KWD.
5230 If KWD is a number, get the corresponding match group."
5231 (if (numberp kwd) (setq kwd (match-string kwd)))
5232 (or (cdr (assoc kwd org-todo-keyword-faces))
5233 (and (member kwd org-done-keywords) 'org-done)
5234 'org-todo))
5236 (defun org-unfontify-region (beg end &optional maybe_loudly)
5237 "Remove fontification and activation overlays from links."
5238 (font-lock-default-unfontify-region beg end)
5239 (let* ((buffer-undo-list t)
5240 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5241 (inhibit-modification-hooks t)
5242 deactivate-mark buffer-file-name buffer-file-truename)
5243 (remove-text-properties beg end
5244 '(mouse-face t keymap t org-linked-text t
5245 invisible t intangible t))))
5247 ;;;; Visibility cycling, including org-goto and indirect buffer
5249 ;;; Cycling
5251 (defvar org-cycle-global-status nil)
5252 (make-variable-buffer-local 'org-cycle-global-status)
5253 (defvar org-cycle-subtree-status nil)
5254 (make-variable-buffer-local 'org-cycle-subtree-status)
5256 ;;;###autoload
5257 (defun org-cycle (&optional arg)
5258 "Visibility cycling for Org-mode.
5260 - When this function is called with a prefix argument, rotate the entire
5261 buffer through 3 states (global cycling)
5262 1. OVERVIEW: Show only top-level headlines.
5263 2. CONTENTS: Show all headlines of all levels, but no body text.
5264 3. SHOW ALL: Show everything.
5266 - When point is at the beginning of a headline, rotate the subtree started
5267 by this line through 3 different states (local cycling)
5268 1. FOLDED: Only the main headline is shown.
5269 2. CHILDREN: The main headline and the direct children are shown.
5270 From this state, you can move to one of the children
5271 and zoom in further.
5272 3. SUBTREE: Show the entire subtree, including body text.
5274 - When there is a numeric prefix, go up to a heading with level ARG, do
5275 a `show-subtree' and return to the previous cursor position. If ARG
5276 is negative, go up that many levels.
5278 - When point is not at the beginning of a headline, execute
5279 `indent-relative', like TAB normally does. See the option
5280 `org-cycle-emulate-tab' for details.
5282 - Special case: if point is at the beginning of the buffer and there is
5283 no headline in line 1, this function will act as if called with prefix arg.
5284 But only if also the variable `org-cycle-global-at-bob' is t."
5285 (interactive "P")
5286 (let* ((outline-regexp
5287 (if (and (org-mode-p) org-cycle-include-plain-lists)
5288 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5289 outline-regexp))
5290 (bob-special (and org-cycle-global-at-bob (bobp)
5291 (not (looking-at outline-regexp))))
5292 (org-cycle-hook
5293 (if bob-special
5294 (delq 'org-optimize-window-after-visibility-change
5295 (copy-sequence org-cycle-hook))
5296 org-cycle-hook))
5297 (pos (point)))
5299 (if (or bob-special (equal arg '(4)))
5300 ;; special case: use global cycling
5301 (setq arg t))
5303 (cond
5305 ((org-at-table-p 'any)
5306 ;; Enter the table or move to the next field in the table
5307 (or (org-table-recognize-table.el)
5308 (progn
5309 (if arg (org-table-edit-field t)
5310 (org-table-justify-field-maybe)
5311 (call-interactively 'org-table-next-field)))))
5313 ((eq arg t) ;; Global cycling
5315 (cond
5316 ((and (eq last-command this-command)
5317 (eq org-cycle-global-status 'overview))
5318 ;; We just created the overview - now do table of contents
5319 ;; This can be slow in very large buffers, so indicate action
5320 (message "CONTENTS...")
5321 (org-content)
5322 (message "CONTENTS...done")
5323 (setq org-cycle-global-status 'contents)
5324 (run-hook-with-args 'org-cycle-hook 'contents))
5326 ((and (eq last-command this-command)
5327 (eq org-cycle-global-status 'contents))
5328 ;; We just showed the table of contents - now show everything
5329 (show-all)
5330 (message "SHOW ALL")
5331 (setq org-cycle-global-status 'all)
5332 (run-hook-with-args 'org-cycle-hook 'all))
5335 ;; Default action: go to overview
5336 (org-overview)
5337 (message "OVERVIEW")
5338 (setq org-cycle-global-status 'overview)
5339 (run-hook-with-args 'org-cycle-hook 'overview))))
5341 ((and org-drawers org-drawer-regexp
5342 (save-excursion
5343 (beginning-of-line 1)
5344 (looking-at org-drawer-regexp)))
5345 ;; Toggle block visibility
5346 (org-flag-drawer
5347 (not (get-char-property (match-end 0) 'invisible))))
5349 ((integerp arg)
5350 ;; Show-subtree, ARG levels up from here.
5351 (save-excursion
5352 (org-back-to-heading)
5353 (outline-up-heading (if (< arg 0) (- arg)
5354 (- (funcall outline-level) arg)))
5355 (org-show-subtree)))
5357 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5358 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5359 ;; At a heading: rotate between three different views
5360 (org-back-to-heading)
5361 (let ((goal-column 0) eoh eol eos)
5362 ;; First, some boundaries
5363 (save-excursion
5364 (org-back-to-heading)
5365 (save-excursion
5366 (beginning-of-line 2)
5367 (while (and (not (eobp)) ;; this is like `next-line'
5368 (get-char-property (1- (point)) 'invisible))
5369 (beginning-of-line 2)) (setq eol (point)))
5370 (outline-end-of-heading) (setq eoh (point))
5371 (org-end-of-subtree t)
5372 (unless (eobp)
5373 (skip-chars-forward " \t\n")
5374 (beginning-of-line 1) ; in case this is an item
5376 (setq eos (1- (point))))
5377 ;; Find out what to do next and set `this-command'
5378 (cond
5379 ((= eos eoh)
5380 ;; Nothing is hidden behind this heading
5381 (message "EMPTY ENTRY")
5382 (setq org-cycle-subtree-status nil)
5383 (save-excursion
5384 (goto-char eos)
5385 (outline-next-heading)
5386 (if (org-invisible-p) (org-flag-heading nil))))
5387 ((or (>= eol eos)
5388 (not (string-match "\\S-" (buffer-substring eol eos))))
5389 ;; Entire subtree is hidden in one line: open it
5390 (org-show-entry)
5391 (show-children)
5392 (message "CHILDREN")
5393 (save-excursion
5394 (goto-char eos)
5395 (outline-next-heading)
5396 (if (org-invisible-p) (org-flag-heading nil)))
5397 (setq org-cycle-subtree-status 'children)
5398 (run-hook-with-args 'org-cycle-hook 'children))
5399 ((and (eq last-command this-command)
5400 (eq org-cycle-subtree-status 'children))
5401 ;; We just showed the children, now show everything.
5402 (org-show-subtree)
5403 (message "SUBTREE")
5404 (setq org-cycle-subtree-status 'subtree)
5405 (run-hook-with-args 'org-cycle-hook 'subtree))
5407 ;; Default action: hide the subtree.
5408 (hide-subtree)
5409 (message "FOLDED")
5410 (setq org-cycle-subtree-status 'folded)
5411 (run-hook-with-args 'org-cycle-hook 'folded)))))
5413 ;; TAB emulation
5414 (buffer-read-only (org-back-to-heading))
5416 ((org-try-cdlatex-tab))
5418 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5419 (or (not (bolp))
5420 (not (looking-at outline-regexp))))
5421 (call-interactively (global-key-binding "\t")))
5423 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5424 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5425 (or (and (eq org-cycle-emulate-tab 'white)
5426 (= (match-end 0) (point-at-eol)))
5427 (and (eq org-cycle-emulate-tab 'whitestart)
5428 (>= (match-end 0) pos))))
5430 (eq org-cycle-emulate-tab t))
5431 ; (if (and (looking-at "[ \n\r\t]")
5432 ; (string-match "^[ \t]*$" (buffer-substring
5433 ; (point-at-bol) (point))))
5434 ; (progn
5435 ; (beginning-of-line 1)
5436 ; (and (looking-at "[ \t]+") (replace-match ""))))
5437 (call-interactively (global-key-binding "\t")))
5439 (t (save-excursion
5440 (org-back-to-heading)
5441 (org-cycle))))))
5443 ;;;###autoload
5444 (defun org-global-cycle (&optional arg)
5445 "Cycle the global visibility. For details see `org-cycle'."
5446 (interactive "P")
5447 (let ((org-cycle-include-plain-lists
5448 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5449 (if (integerp arg)
5450 (progn
5451 (show-all)
5452 (hide-sublevels arg)
5453 (setq org-cycle-global-status 'contents))
5454 (org-cycle '(4)))))
5456 (defun org-overview ()
5457 "Switch to overview mode, shoing only top-level headlines.
5458 Really, this shows all headlines with level equal or greater than the level
5459 of the first headline in the buffer. This is important, because if the
5460 first headline is not level one, then (hide-sublevels 1) gives confusing
5461 results."
5462 (interactive)
5463 (let ((level (save-excursion
5464 (goto-char (point-min))
5465 (if (re-search-forward (concat "^" outline-regexp) nil t)
5466 (progn
5467 (goto-char (match-beginning 0))
5468 (funcall outline-level))))))
5469 (and level (hide-sublevels level))))
5471 (defun org-content (&optional arg)
5472 "Show all headlines in the buffer, like a table of contents.
5473 With numerical argument N, show content up to level N."
5474 (interactive "P")
5475 (save-excursion
5476 ;; Visit all headings and show their offspring
5477 (and (integerp arg) (org-overview))
5478 (goto-char (point-max))
5479 (catch 'exit
5480 (while (and (progn (condition-case nil
5481 (outline-previous-visible-heading 1)
5482 (error (goto-char (point-min))))
5484 (looking-at outline-regexp))
5485 (if (integerp arg)
5486 (show-children (1- arg))
5487 (show-branches))
5488 (if (bobp) (throw 'exit nil))))))
5491 (defun org-optimize-window-after-visibility-change (state)
5492 "Adjust the window after a change in outline visibility.
5493 This function is the default value of the hook `org-cycle-hook'."
5494 (when (get-buffer-window (current-buffer))
5495 (cond
5496 ; ((eq state 'overview) (org-first-headline-recenter 1))
5497 ; ((eq state 'overview) (org-beginning-of-line))
5498 ((eq state 'content) nil)
5499 ((eq state 'all) nil)
5500 ((eq state 'folded) nil)
5501 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5502 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5505 (defun org-cycle-show-empty-lines (state)
5506 "Show empty lines above all visible headlines.
5507 The region to be covered depends on STATE when called through
5508 `org-cycle-hook'. Lisp program can use t for STATE to get the
5509 entire buffer covered. Note that an empty line is only shown if there
5510 are at least `org-cycle-separator-lines' empty lines before the headeline."
5511 (when (> org-cycle-separator-lines 0)
5512 (save-excursion
5513 (let* ((n org-cycle-separator-lines)
5514 (re (cond
5515 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5516 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5517 (t (let ((ns (number-to-string (- n 2))))
5518 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5519 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5520 beg end)
5521 (cond
5522 ((memq state '(overview contents t))
5523 (setq beg (point-min) end (point-max)))
5524 ((memq state '(children folded))
5525 (setq beg (point) end (progn (org-end-of-subtree t t)
5526 (beginning-of-line 2)
5527 (point)))))
5528 (when beg
5529 (goto-char beg)
5530 (while (re-search-forward re end t)
5531 (if (not (get-char-property (match-end 1) 'invisible))
5532 (outline-flag-region
5533 (match-beginning 1) (match-end 1) nil)))))))
5534 ;; Never hide empty lines at the end of the file.
5535 (save-excursion
5536 (goto-char (point-max))
5537 (outline-previous-heading)
5538 (outline-end-of-heading)
5539 (if (and (looking-at "[ \t\n]+")
5540 (= (match-end 0) (point-max)))
5541 (outline-flag-region (point) (match-end 0) nil))))
5543 (defun org-subtree-end-visible-p ()
5544 "Is the end of the current subtree visible?"
5545 (pos-visible-in-window-p
5546 (save-excursion (org-end-of-subtree t) (point))))
5548 (defun org-first-headline-recenter (&optional N)
5549 "Move cursor to the first headline and recenter the headline.
5550 Optional argument N means, put the headline into the Nth line of the window."
5551 (goto-char (point-min))
5552 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5553 (beginning-of-line)
5554 (recenter (prefix-numeric-value N))))
5556 ;;; Org-goto
5558 (defvar org-goto-window-configuration nil)
5559 (defvar org-goto-marker nil)
5560 (defvar org-goto-map
5561 (let ((map (make-sparse-keymap)))
5562 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5563 (while (setq cmd (pop cmds))
5564 (substitute-key-definition cmd cmd map global-map)))
5565 (suppress-keymap map)
5566 (org-defkey map "\C-m" 'org-goto-ret)
5567 (org-defkey map [(left)] 'org-goto-left)
5568 (org-defkey map [(right)] 'org-goto-right)
5569 (org-defkey map [(?q)] 'org-goto-quit)
5570 (org-defkey map [(control ?g)] 'org-goto-quit)
5571 (org-defkey map "\C-i" 'org-cycle)
5572 (org-defkey map [(tab)] 'org-cycle)
5573 (org-defkey map [(down)] 'outline-next-visible-heading)
5574 (org-defkey map [(up)] 'outline-previous-visible-heading)
5575 (org-defkey map "n" 'outline-next-visible-heading)
5576 (org-defkey map "p" 'outline-previous-visible-heading)
5577 (org-defkey map "f" 'outline-forward-same-level)
5578 (org-defkey map "b" 'outline-backward-same-level)
5579 (org-defkey map "u" 'outline-up-heading)
5580 (org-defkey map "/" 'org-occur)
5581 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5582 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5583 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5584 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5585 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5586 map))
5588 (defconst org-goto-help
5589 "Browse copy of buffer to find location or copy text.
5590 RET=jump to location [Q]uit and return to previous location
5591 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur"
5594 (defun org-goto ()
5595 "Look up a different location in the current file, keeping current visibility.
5597 When you want look-up or go to a different location in a document, the
5598 fastest way is often to fold the entire buffer and then dive into the tree.
5599 This method has the disadvantage, that the previous location will be folded,
5600 which may not be what you want.
5602 This command works around this by showing a copy of the current buffer
5603 in an indirect buffer, in overview mode. You can dive into the tree in
5604 that copy, use org-occur and incremental search to find a location.
5605 When pressing RET or `Q', the command returns to the original buffer in
5606 which the visibility is still unchanged. After RET is will also jump to
5607 the location selected in the indirect buffer and expose the
5608 the headline hierarchy above."
5609 (interactive)
5610 (let* ((org-goto-start-pos (point))
5611 (selected-point
5612 (car (org-get-location (current-buffer) org-goto-help))))
5613 (if selected-point
5614 (progn
5615 (org-mark-ring-push org-goto-start-pos)
5616 (goto-char selected-point)
5617 (if (or (org-invisible-p) (org-invisible-p2))
5618 (org-show-context 'org-goto)))
5619 (message "Quit"))))
5621 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5622 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5624 (defun org-get-location (buf help)
5625 "Let the user select a location in the Org-mode buffer BUF.
5626 This function uses a recursive edit. It returns the selected position
5627 or nil."
5628 (let (org-goto-selected-point org-goto-exit-command)
5629 (save-excursion
5630 (save-window-excursion
5631 (delete-other-windows)
5632 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5633 (switch-to-buffer
5634 (condition-case nil
5635 (make-indirect-buffer (current-buffer) "*org-goto*")
5636 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5637 (with-output-to-temp-buffer "*Help*"
5638 (princ help))
5639 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
5640 (setq buffer-read-only nil)
5641 (let ((org-startup-truncated t)
5642 (org-startup-folded nil)
5643 (org-startup-align-all-tables nil))
5644 (org-mode)
5645 (org-overview))
5646 (setq buffer-read-only t)
5647 (if (and (boundp 'org-goto-start-pos)
5648 (integer-or-marker-p org-goto-start-pos))
5649 (let ((org-show-hierarchy-above t)
5650 (org-show-siblings t)
5651 (org-show-following-heading t))
5652 (goto-char org-goto-start-pos)
5653 (and (org-invisible-p) (org-show-context)))
5654 (goto-char (point-min)))
5655 (org-beginning-of-line)
5656 (message "Select location and press RET")
5657 ;; now we make sure that during selection, ony very few keys work
5658 ;; and that it is impossible to switch to another window.
5659 ; (let ((gm (current-global-map))
5660 ; (overriding-local-map org-goto-map))
5661 ; (unwind-protect
5662 ; (progn
5663 ; (use-global-map org-goto-map)
5664 ; (recursive-edit))
5665 ; (use-global-map gm)))
5666 (use-local-map org-goto-map)
5667 (recursive-edit)
5669 (kill-buffer "*org-goto*")
5670 (cons org-goto-selected-point org-goto-exit-command)))
5672 (defun org-goto-ret (&optional arg)
5673 "Finish `org-goto' by going to the new location."
5674 (interactive "P")
5675 (setq org-goto-selected-point (point)
5676 org-goto-exit-command 'return)
5677 (throw 'exit nil))
5679 (defun org-goto-left ()
5680 "Finish `org-goto' by going to the new location."
5681 (interactive)
5682 (if (org-on-heading-p)
5683 (progn
5684 (beginning-of-line 1)
5685 (setq org-goto-selected-point (point)
5686 org-goto-exit-command 'left)
5687 (throw 'exit nil))
5688 (error "Not on a heading")))
5690 (defun org-goto-right ()
5691 "Finish `org-goto' by going to the new location."
5692 (interactive)
5693 (if (org-on-heading-p)
5694 (progn
5695 (setq org-goto-selected-point (point)
5696 org-goto-exit-command 'right)
5697 (throw 'exit nil))
5698 (error "Not on a heading")))
5700 (defun org-goto-quit ()
5701 "Finish `org-goto' without cursor motion."
5702 (interactive)
5703 (setq org-goto-selected-point nil)
5704 (setq org-goto-exit-command 'quit)
5705 (throw 'exit nil))
5707 ;;; Indirect buffer display of subtrees
5709 (defvar org-indirect-dedicated-frame nil
5710 "This is the frame being used for indirect tree display.")
5711 (defvar org-last-indirect-buffer nil)
5713 (defun org-tree-to-indirect-buffer (&optional arg)
5714 "Create indirect buffer and narrow it to current subtree.
5715 With numerical prefix ARG, go up to this level and then take that tree.
5716 If ARG is negative, go up that many levels.
5717 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5718 indirect buffer previously made with this command, to avoid proliferation of
5719 indirect buffers. However, when you call the command with a `C-u' prefix, or
5720 when `org-indirect-buffer-display' is `new-frame', the last buffer
5721 is kept so that you can work with several indirect buffers at the same time.
5722 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5723 requests that a new frame be made for the new buffer, so that the dedicated
5724 frame is not changed."
5725 (interactive "P")
5726 (let ((cbuf (current-buffer))
5727 (cwin (selected-window))
5728 (pos (point))
5729 beg end level heading ibuf)
5730 (save-excursion
5731 (org-back-to-heading t)
5732 (when (numberp arg)
5733 (setq level (org-outline-level))
5734 (if (< arg 0) (setq arg (+ level arg)))
5735 (while (> (setq level (org-outline-level)) arg)
5736 (outline-up-heading 1 t)))
5737 (setq beg (point)
5738 heading (org-get-heading))
5739 (org-end-of-subtree t) (setq end (point)))
5740 (if (and (buffer-live-p org-last-indirect-buffer)
5741 (not (eq org-indirect-buffer-display 'new-frame))
5742 (not arg))
5743 (kill-buffer org-last-indirect-buffer))
5744 (setq ibuf (org-get-indirect-buffer cbuf)
5745 org-last-indirect-buffer ibuf)
5746 (cond
5747 ((or (eq org-indirect-buffer-display 'new-frame)
5748 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5749 (select-frame (make-frame))
5750 (delete-other-windows)
5751 (switch-to-buffer ibuf)
5752 (org-set-frame-title heading))
5753 ((eq org-indirect-buffer-display 'dedicated-frame)
5754 (raise-frame
5755 (select-frame (or (and org-indirect-dedicated-frame
5756 (frame-live-p org-indirect-dedicated-frame)
5757 org-indirect-dedicated-frame)
5758 (setq org-indirect-dedicated-frame (make-frame)))))
5759 (delete-other-windows)
5760 (switch-to-buffer ibuf)
5761 (org-set-frame-title (concat "Indirect: " heading)))
5762 ((eq org-indirect-buffer-display 'current-window)
5763 (switch-to-buffer ibuf))
5764 ((eq org-indirect-buffer-display 'other-window)
5765 (pop-to-buffer ibuf))
5766 (t (error "Invalid value.")))
5767 (if (featurep 'xemacs)
5768 (save-excursion (org-mode) (turn-on-font-lock)))
5769 (narrow-to-region beg end)
5770 (show-all)
5771 (goto-char pos)
5772 (and (window-live-p cwin) (select-window cwin))))
5774 (defun org-get-indirect-buffer (&optional buffer)
5775 (setq buffer (or buffer (current-buffer)))
5776 (let ((n 1) (base (buffer-name buffer)) bname)
5777 (while (buffer-live-p
5778 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5779 (setq n (1+ n)))
5780 (condition-case nil
5781 (make-indirect-buffer buffer bname 'clone)
5782 (error (make-indirect-buffer buffer bname)))))
5784 (defun org-set-frame-title (title)
5785 "Set the title of the current frame to the string TITLE."
5786 ;; FIXME: how to name a single frame in XEmacs???
5787 (unless (featurep 'xemacs)
5788 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5790 ;;;; Structure editing
5792 ;;; Inserting headlines
5794 (defun org-insert-heading (&optional force-heading)
5795 "Insert a new heading or item with same depth at point.
5796 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5797 If point is at the beginning of a headline, insert a sibling before the
5798 current headline. If point is in the middle of a headline, split the headline
5799 at that position and make the rest of the headline part of the sibling below
5800 the current headline."
5801 (interactive "P")
5802 (if (= (buffer-size) 0)
5803 (insert "\n* ")
5804 (when (or force-heading (not (org-insert-item)))
5805 (let* ((head (save-excursion
5806 (condition-case nil
5807 (progn
5808 (org-back-to-heading)
5809 (match-string 0))
5810 (error "*"))))
5811 (blank (cdr (assq 'heading org-blank-before-new-entry)))
5812 pos)
5813 (cond
5814 ((and (org-on-heading-p) (bolp)
5815 (or (bobp)
5816 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5817 (open-line (if blank 2 1)))
5818 ((and (bolp)
5819 (or (bobp)
5820 (save-excursion
5821 (backward-char 1) (not (org-invisible-p)))))
5822 nil)
5823 (t (newline (if blank 2 1))))
5824 (insert head) (just-one-space)
5825 (setq pos (point))
5826 (end-of-line 1)
5827 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5828 (run-hooks 'org-insert-heading-hook)))))
5830 (defun org-insert-heading-after-current ()
5831 "Insert a new heading with same level as current, after current subtree."
5832 (interactive)
5833 (org-back-to-heading)
5834 (org-insert-heading)
5835 (org-move-subtree-down)
5836 (end-of-line 1))
5838 (defun org-insert-todo-heading (arg)
5839 "Insert a new heading with the same level and TODO state as current heading.
5840 If the heading has no TODO state, or if the state is DONE, use the first
5841 state (TODO by default). Also with prefix arg, force first state."
5842 (interactive "P")
5843 (when (not (org-insert-item 'checkbox))
5844 (org-insert-heading)
5845 (save-excursion
5846 (org-back-to-heading)
5847 (outline-previous-heading)
5848 (looking-at org-todo-line-regexp))
5849 (if (or arg
5850 (not (match-beginning 2))
5851 (member (match-string 2) org-done-keywords))
5852 (insert (car org-todo-keywords-1) " ")
5853 (insert (match-string 2) " "))))
5855 (defun org-insert-subheading (arg)
5856 "Insert a new subheading and demote it.
5857 Works for outline headings and for plain lists alike."
5858 (interactive "P")
5859 (org-insert-heading arg)
5860 (cond
5861 ((org-on-heading-p) (org-do-demote))
5862 ((org-at-item-p) (org-indent-item 1))))
5864 (defun org-insert-todo-subheading (arg)
5865 "Insert a new subheading with TODO keyword or checkbox and demote it.
5866 Works for outline headings and for plain lists alike."
5867 (interactive "P")
5868 (org-insert-todo-heading arg)
5869 (cond
5870 ((org-on-heading-p) (org-do-demote))
5871 ((org-at-item-p) (org-indent-item 1))))
5873 ;;; Promotion and Demotion
5875 (defun org-promote-subtree ()
5876 "Promote the entire subtree.
5877 See also `org-promote'."
5878 (interactive)
5879 (save-excursion
5880 (org-map-tree 'org-promote))
5881 (org-fix-position-after-promote))
5883 (defun org-demote-subtree ()
5884 "Demote the entire subtree. See `org-demote'.
5885 See also `org-promote'."
5886 (interactive)
5887 (save-excursion
5888 (org-map-tree 'org-demote))
5889 (org-fix-position-after-promote))
5892 (defun org-do-promote ()
5893 "Promote the current heading higher up the tree.
5894 If the region is active in `transient-mark-mode', promote all headings
5895 in the region."
5896 (interactive)
5897 (save-excursion
5898 (if (org-region-active-p)
5899 (org-map-region 'org-promote (region-beginning) (region-end))
5900 (org-promote)))
5901 (org-fix-position-after-promote))
5903 (defun org-do-demote ()
5904 "Demote the current heading lower down the tree.
5905 If the region is active in `transient-mark-mode', demote all headings
5906 in the region."
5907 (interactive)
5908 (save-excursion
5909 (if (org-region-active-p)
5910 (org-map-region 'org-demote (region-beginning) (region-end))
5911 (org-demote)))
5912 (org-fix-position-after-promote))
5914 (defun org-fix-position-after-promote ()
5915 "Make sure that after pro/demotion cursor position is right."
5916 (let ((pos (point)))
5917 (when (save-excursion
5918 (beginning-of-line 1)
5919 (looking-at org-todo-line-regexp)
5920 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5921 (cond ((eobp) (insert " "))
5922 ((eolp) (insert " "))
5923 ((equal (char-after) ?\ ) (forward-char 1))))))
5925 (defun org-reduced-level (l)
5926 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5928 (defun org-get-legal-level (level &optional change)
5929 "Rectify a level change under the influence of `org-odd-levels-only'
5930 LEVEL is a current level, CHANGE is by how much the level should be
5931 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5932 even level numbers will become the next higher odd number."
5933 (if org-odd-levels-only
5934 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5935 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5936 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5937 (max 1 (+ level change))))
5939 (defun org-promote ()
5940 "Promote the current heading higher up the tree.
5941 If the region is active in `transient-mark-mode', promote all headings
5942 in the region."
5943 (org-back-to-heading t)
5944 (let* ((level (save-match-data (funcall outline-level)))
5945 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
5946 (diff (abs (- level (length up-head) -1))))
5947 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5948 (replace-match up-head nil t)
5949 ;; Fixup tag positioning
5950 (and org-auto-align-tags (org-set-tags nil t))
5951 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5953 (defun org-demote ()
5954 "Demote the current heading lower down the tree.
5955 If the region is active in `transient-mark-mode', demote all headings
5956 in the region."
5957 (org-back-to-heading t)
5958 (let* ((level (save-match-data (funcall outline-level)))
5959 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
5960 (diff (abs (- level (length down-head) -1))))
5961 (replace-match down-head nil t)
5962 ;; Fixup tag positioning
5963 (and org-auto-align-tags (org-set-tags nil t))
5964 (if org-adapt-indentation (org-fixup-indentation diff))))
5966 (defun org-map-tree (fun)
5967 "Call FUN for every heading underneath the current one."
5968 (org-back-to-heading)
5969 (let ((level (funcall outline-level)))
5970 (save-excursion
5971 (funcall fun)
5972 (while (and (progn
5973 (outline-next-heading)
5974 (> (funcall outline-level) level))
5975 (not (eobp)))
5976 (funcall fun)))))
5978 (defun org-map-region (fun beg end)
5979 "Call FUN for every heading between BEG and END."
5980 (let ((org-ignore-region t))
5981 (save-excursion
5982 (setq end (copy-marker end))
5983 (goto-char beg)
5984 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5985 (< (point) end))
5986 (funcall fun))
5987 (while (and (progn
5988 (outline-next-heading)
5989 (< (point) end))
5990 (not (eobp)))
5991 (funcall fun)))))
5993 (defun org-fixup-indentation (diff)
5994 "Change the indentation in the current entry by DIFF
5995 However, if any line in the current entry has no indentation, or if it
5996 would end up with no indentation after the change, nothing at all is done."
5997 (save-excursion
5998 (let ((end (save-excursion (outline-next-heading)
5999 (point-marker)))
6000 (prohibit (if (> diff 0)
6001 "^\\S-"
6002 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6003 col)
6004 (unless (save-excursion (end-of-line 1)
6005 (re-search-forward prohibit end t))
6006 (while (and (< (point) end)
6007 (re-search-forward "^[ \t]+" end t))
6008 (goto-char (match-end 0))
6009 (setq col (current-column))
6010 (if (< diff 0) (replace-match ""))
6011 (indent-to (+ diff col))))
6012 (move-marker end nil))))
6014 (defun org-convert-to-odd-levels ()
6015 "Convert an org-mode file with all levels allowed to one with odd levels.
6016 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6017 level 5 etc."
6018 (interactive)
6019 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6020 (let ((org-odd-levels-only nil) n)
6021 (save-excursion
6022 (goto-char (point-min))
6023 (while (re-search-forward "^\\*\\*+ " nil t)
6024 (setq n (- (length (match-string 0)) 2))
6025 (while (>= (setq n (1- n)) 0)
6026 (org-demote))
6027 (end-of-line 1))))))
6030 (defun org-convert-to-oddeven-levels ()
6031 "Convert an org-mode file with only odd levels to one with odd and even levels.
6032 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6033 section with an even level, conversion would destroy the structure of the file. An error
6034 is signaled in this case."
6035 (interactive)
6036 (goto-char (point-min))
6037 ;; First check if there are no even levels
6038 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6039 (org-show-context t)
6040 (error "Not all levels are odd in this file. Conversion not possible."))
6041 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6042 (let ((org-odd-levels-only nil) n)
6043 (save-excursion
6044 (goto-char (point-min))
6045 (while (re-search-forward "^\\*\\*+ " nil t)
6046 (setq n (/ (1- (length (match-string 0))) 2))
6047 (while (>= (setq n (1- n)) 0)
6048 (org-promote))
6049 (end-of-line 1))))))
6051 (defun org-tr-level (n)
6052 "Make N odd if required."
6053 (if org-odd-levels-only (1+ (/ n 2)) n))
6055 ;;; Vertical tree motion, cutting and pasting of subtrees
6057 (defun org-move-subtree-up (&optional arg)
6058 "Move the current subtree up past ARG headlines of the same level."
6059 (interactive "p")
6060 (org-move-subtree-down (- (prefix-numeric-value arg))))
6062 (defun org-move-subtree-down (&optional arg)
6063 "Move the current subtree down past ARG headlines of the same level."
6064 (interactive "p")
6065 (setq arg (prefix-numeric-value arg))
6066 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6067 'outline-get-last-sibling))
6068 (ins-point (make-marker))
6069 (cnt (abs arg))
6070 beg end txt folded)
6071 ;; Select the tree
6072 (org-back-to-heading)
6073 (setq beg (point))
6074 (save-match-data
6075 (save-excursion (outline-end-of-heading)
6076 (setq folded (org-invisible-p)))
6077 (outline-end-of-subtree))
6078 (outline-next-heading)
6079 (setq end (point))
6080 ;; Find insertion point, with error handling
6081 (goto-char beg)
6082 (while (> cnt 0)
6083 (or (and (funcall movfunc) (looking-at outline-regexp))
6084 (progn (goto-char beg)
6085 (error "Cannot move past superior level or buffer limit")))
6086 (setq cnt (1- cnt)))
6087 (if (> arg 0)
6088 ;; Moving forward - still need to move over subtree
6089 (progn (outline-end-of-subtree)
6090 (outline-next-heading)
6091 (if (not (or (looking-at (concat "^" outline-regexp))
6092 (bolp)))
6093 (newline))))
6094 (move-marker ins-point (point))
6095 (setq txt (buffer-substring beg end))
6096 (delete-region beg end)
6097 (insert txt)
6098 (or (bolp) (insert "\n"))
6099 (goto-char ins-point)
6100 (if folded (hide-subtree))
6101 (move-marker ins-point nil)))
6103 (defvar org-subtree-clip ""
6104 "Clipboard for cut and paste of subtrees.
6105 This is actually only a copy of the kill, because we use the normal kill
6106 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6108 (defvar org-subtree-clip-folded nil
6109 "Was the last copied subtree folded?
6110 This is used to fold the tree back after pasting.")
6112 (defun org-cut-subtree (&optional n)
6113 "Cut the current subtree into the clipboard.
6114 With prefix arg N, cut this many sequential subtrees.
6115 This is a short-hand for marking the subtree and then cutting it."
6116 (interactive "p")
6117 (org-copy-subtree n 'cut))
6119 (defun org-copy-subtree (&optional n cut)
6120 "Cut the current subtree into the clipboard.
6121 With prefix arg N, cut this many sequential subtrees.
6122 This is a short-hand for marking the subtree and then copying it.
6123 If CUT is non-nil, actually cut the subtree."
6124 (interactive "p")
6125 (let (beg end folded)
6126 (if (interactive-p)
6127 (org-back-to-heading nil) ; take what looks like a subtree
6128 (org-back-to-heading t)) ; take what is really there
6129 (setq beg (point))
6130 (save-match-data
6131 (save-excursion (outline-end-of-heading)
6132 (setq folded (org-invisible-p)))
6133 (condition-case nil
6134 (outline-forward-same-level (1- n))
6135 (error nil))
6136 (org-end-of-subtree t t))
6137 (setq end (point))
6138 (goto-char beg)
6139 (when (> end beg)
6140 (setq org-subtree-clip-folded folded)
6141 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6142 (setq org-subtree-clip (current-kill 0))
6143 (message "%s: Subtree(s) with %d characters"
6144 (if cut "Cut" "Copied")
6145 (length org-subtree-clip)))))
6147 (defun org-paste-subtree (&optional level tree)
6148 "Paste the clipboard as a subtree, with modification of headline level.
6149 The entire subtree is promoted or demoted in order to match a new headline
6150 level. By default, the new level is derived from the visible headings
6151 before and after the insertion point, and taken to be the inferior headline
6152 level of the two. So if the previous visible heading is level 3 and the
6153 next is level 4 (or vice versa), level 4 will be used for insertion.
6154 This makes sure that the subtree remains an independent subtree and does
6155 not swallow low level entries.
6157 You can also force a different level, either by using a numeric prefix
6158 argument, or by inserting the heading marker by hand. For example, if the
6159 cursor is after \"*****\", then the tree will be shifted to level 5.
6161 If you want to insert the tree as is, just use \\[yank].
6163 If optional TREE is given, use this text instead of the kill ring."
6164 (interactive "P")
6165 (unless (org-kill-is-subtree-p tree)
6166 (error
6167 (substitute-command-keys
6168 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6169 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6170 (^re (concat "^\\(" outline-regexp "\\)"))
6171 (re (concat "\\(" outline-regexp "\\)"))
6172 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6174 (old-level (if (string-match ^re txt)
6175 (- (match-end 0) (match-beginning 0) 1)
6176 -1))
6177 (force-level (cond (level (prefix-numeric-value level))
6178 ((string-match
6179 ^re_ (buffer-substring (point-at-bol) (point)))
6180 (- (match-end 1) (match-beginning 1)))
6181 (t nil)))
6182 (previous-level (save-excursion
6183 (condition-case nil
6184 (progn
6185 (outline-previous-visible-heading 1)
6186 (if (looking-at re)
6187 (- (match-end 0) (match-beginning 0) 1)
6189 (error 1))))
6190 (next-level (save-excursion
6191 (condition-case nil
6192 (progn
6193 (or (looking-at outline-regexp)
6194 (outline-next-visible-heading 1))
6195 (if (looking-at re)
6196 (- (match-end 0) (match-beginning 0) 1)
6198 (error 1))))
6199 (new-level (or force-level (max previous-level next-level)))
6200 (shift (if (or (= old-level -1)
6201 (= new-level -1)
6202 (= old-level new-level))
6204 (- new-level old-level)))
6205 (delta (if (> shift 0) -1 1))
6206 (func (if (> shift 0) 'org-demote 'org-promote))
6207 (org-odd-levels-only nil)
6208 beg end)
6209 ;; Remove the forced level indicator
6210 (if force-level
6211 (delete-region (point-at-bol) (point)))
6212 ;; Paste
6213 (beginning-of-line 1)
6214 (setq beg (point))
6215 (insert txt)
6216 (unless (string-match "\n\\'" txt) (insert "\n"))
6217 (setq end (point))
6218 (goto-char beg)
6219 ;; Shift if necessary
6220 (unless (= shift 0)
6221 (save-restriction
6222 (narrow-to-region beg end)
6223 (while (not (= shift 0))
6224 (org-map-region func (point-min) (point-max))
6225 (setq shift (+ delta shift)))
6226 (goto-char (point-min))))
6227 (when (interactive-p)
6228 (message "Clipboard pasted as level %d subtree" new-level))
6229 (if (and kill-ring
6230 (eq org-subtree-clip (current-kill 0))
6231 org-subtree-clip-folded)
6232 ;; The tree was folded before it was killed/copied
6233 (hide-subtree))))
6235 (defun org-kill-is-subtree-p (&optional txt)
6236 "Check if the current kill is an outline subtree, or a set of trees.
6237 Returns nil if kill does not start with a headline, or if the first
6238 headline level is not the largest headline level in the tree.
6239 So this will actually accept several entries of equal levels as well,
6240 which is OK for `org-paste-subtree'.
6241 If optional TXT is given, check this string instead of the current kill."
6242 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6243 (start-level (and kill
6244 (string-match (concat "\\`" org-outline-regexp) kill)
6245 (- (match-end 0) (match-beginning 0) 1)))
6246 (re (concat "^" org-outline-regexp))
6247 (start 1))
6248 (if (not start-level)
6249 (progn
6250 nil) ;; does not even start with a heading
6251 (catch 'exit
6252 (while (setq start (string-match re kill (1+ start)))
6253 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6254 (throw 'exit nil)))
6255 t))))
6257 (defun org-narrow-to-subtree ()
6258 "Narrow buffer to the current subtree."
6259 (interactive)
6260 (save-excursion
6261 (narrow-to-region
6262 (progn (org-back-to-heading) (point))
6263 (progn (org-end-of-subtree t t) (point)))))
6266 ;;; Outline Sorting
6268 (defun org-sort (with-case)
6269 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6270 Optional argument WITH-CASE means sort case-sensitively."
6271 (interactive "P")
6272 (if (org-at-table-p)
6273 (org-call-with-arg 'org-table-sort-lines with-case)
6274 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6276 (defvar org-priority-regexp) ; defined later in the file
6278 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6279 "Sort entries on a certain level of an outline tree.
6280 If there is an active region, the entries in the region are sorted.
6281 Else, if the cursor is before the first entry, sort the top-level items.
6282 Else, the children of the entry at point are sorted.
6284 Sorting can be alphabetically, numerically, and by date/time as given by
6285 the first time stamp in the entry. The command prompts for the sorting
6286 type unless it has been given to the function through the SORTING-TYPE
6287 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6288 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6289 called with point at the beginning of the record. It must return either
6290 a string or a number that should serve as the sorting key for that record.
6292 Comparing entries ignores case by default. However, with an optional argument
6293 WITH-CASE, the sorting considers case as well."
6294 (interactive "P")
6295 (let ((case-func (if with-case 'identity 'downcase))
6296 start beg end stars re re2
6297 txt what tmp plain-list-p)
6298 ;; Find beginning and end of region to sort
6299 (cond
6300 ((org-region-active-p)
6301 ;; we will sort the region
6302 (setq end (region-end)
6303 what "region")
6304 (goto-char (region-beginning))
6305 (if (not (org-on-heading-p)) (outline-next-heading))
6306 (setq start (point)))
6307 ((org-at-item-p)
6308 ;; we will sort this plain list
6309 (org-beginning-of-item-list) (setq start (point))
6310 (org-end-of-item-list) (setq end (point))
6311 (goto-char start)
6312 (setq plain-list-p t
6313 what "plain list"))
6314 ((or (org-on-heading-p)
6315 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6316 ;; we will sort the children of the current headline
6317 (org-back-to-heading)
6318 (setq start (point) end (org-end-of-subtree) what "children")
6319 (goto-char start)
6320 (show-subtree)
6321 (outline-next-heading))
6323 ;; we will sort the top-level entries in this file
6324 (goto-char (point-min))
6325 (or (org-on-heading-p) (outline-next-heading))
6326 (setq start (point) end (point-max) what "top-level")
6327 (goto-char start)
6328 (show-all)))
6330 (setq beg (point))
6331 (if (>= beg end) (error "Nothing to sort"))
6333 (unless plain-list-p
6334 (looking-at "\\(\\*+\\)")
6335 (setq stars (match-string 1)
6336 re (concat "^" (regexp-quote stars) " +")
6337 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6338 txt (buffer-substring beg end))
6339 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6340 (if (and (not (equal stars "*")) (string-match re2 txt))
6341 (error "Region to sort contains a level above the first entry")))
6343 (unless sorting-type
6344 (message
6345 (if plain-list-p
6346 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6347 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6348 what)
6349 (setq sorting-type (read-char-exclusive))
6351 (and (= (downcase sorting-type) ?f)
6352 (setq getkey-func
6353 (completing-read "Sort using function: "
6354 obarray 'fboundp t nil nil))
6355 (setq getkey-func (intern getkey-func)))
6357 (and (= (downcase sorting-type) ?r)
6358 (setq property
6359 (completing-read "Property: "
6360 (mapcar 'list (org-buffer-property-keys t))
6361 nil t))))
6363 (message "Sorting entries...")
6365 (save-restriction
6366 (narrow-to-region start end)
6368 (let ((dcst (downcase sorting-type))
6369 (now (current-time)))
6370 (sort-subr
6371 (/= dcst sorting-type)
6372 ;; This function moves to the beginning character of the "record" to
6373 ;; be sorted.
6374 (if plain-list-p
6375 (lambda nil
6376 (if (org-at-item-p) t (goto-char (point-max))))
6377 (lambda nil
6378 (if (re-search-forward re nil t)
6379 (goto-char (match-beginning 0))
6380 (goto-char (point-max)))))
6381 ;; This function moves to the last character of the "record" being
6382 ;; sorted.
6383 (if plain-list-p
6384 'org-end-of-item
6385 (lambda nil
6386 (save-match-data
6387 (condition-case nil
6388 (outline-forward-same-level 1)
6389 (error
6390 (goto-char (point-max)))))))
6392 ;; This function returns the value that gets sorted against.
6393 (if plain-list-p
6394 (lambda nil
6395 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6396 (cond
6397 ((= dcst ?n)
6398 (string-to-number (buffer-substring (match-end 0)
6399 (point-at-eol))))
6400 ((= dcst ?a)
6401 (buffer-substring (match-end 0) (point-at-eol)))
6402 ((= dcst ?t)
6403 (if (re-search-forward org-ts-regexp
6404 (point-at-eol) t)
6405 (org-time-string-to-time (match-string 0))
6406 now))
6407 ((= dcst ?f)
6408 (if getkey-func
6409 (progn
6410 (setq tmp (funcall getkey-func))
6411 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6412 tmp)
6413 (error "Invalid key function `%s'" getkey-func)))
6414 (t (error "Invalid sorting type `%c'" sorting-type)))))
6415 (lambda nil
6416 (cond
6417 ((= dcst ?n)
6418 (if (looking-at outline-regexp)
6419 (string-to-number (buffer-substring (match-end 0)
6420 (point-at-eol)))
6421 nil))
6422 ((= dcst ?a)
6423 (funcall case-func (buffer-substring (point-at-bol)
6424 (point-at-eol))))
6425 ((= dcst ?t)
6426 (if (re-search-forward org-ts-regexp
6427 (save-excursion
6428 (forward-line 2)
6429 (point)) t)
6430 (org-time-string-to-time (match-string 0))
6431 now))
6432 ((= dcst ?p)
6433 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6434 (string-to-char (match-string 2))
6435 org-default-priority))
6436 ((= dcst ?r)
6437 (or (org-entry-get nil property) ""))
6438 ((= dcst ?f)
6439 (if getkey-func
6440 (progn
6441 (setq tmp (funcall getkey-func))
6442 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6443 tmp)
6444 (error "Invalid key function `%s'" getkey-func)))
6445 (t (error "Invalid sorting type `%c'" sorting-type)))))
6447 (cond
6448 ((= dcst ?a) 'string<)
6449 ((= dcst ?t) 'time-less-p)
6450 (t nil)))))
6451 (message "Sorting entries...done")))
6453 (defun org-do-sort (table what &optional with-case sorting-type)
6454 "Sort TABLE of WHAT according to SORTING-TYPE.
6455 The user will be prompted for the SORTING-TYPE if the call to this
6456 function does not specify it. WHAT is only for the prompt, to indicate
6457 what is being sorted. The sorting key will be extracted from
6458 the car of the elements of the table.
6459 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6460 (unless sorting-type
6461 (message
6462 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6463 what)
6464 (setq sorting-type (read-char-exclusive)))
6465 (let ((dcst (downcase sorting-type))
6466 extractfun comparefun)
6467 ;; Define the appropriate functions
6468 (cond
6469 ((= dcst ?n)
6470 (setq extractfun 'string-to-number
6471 comparefun (if (= dcst sorting-type) '< '>)))
6472 ((= dcst ?a)
6473 (setq extractfun (if with-case 'identity 'downcase)
6474 comparefun (if (= dcst sorting-type)
6475 'string<
6476 (lambda (a b) (and (not (string< a b))
6477 (not (string= a b)))))))
6478 ((= dcst ?t)
6479 (setq extractfun
6480 (lambda (x)
6481 (if (string-match org-ts-regexp x)
6482 (time-to-seconds
6483 (org-time-string-to-time (match-string 0 x)))
6485 comparefun (if (= dcst sorting-type) '< '>)))
6486 (t (error "Invalid sorting type `%c'" sorting-type)))
6488 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6489 table)
6490 (lambda (a b) (funcall comparefun (car a) (car b))))))
6492 ;;;; Plain list items, including checkboxes
6494 ;;; Plain list items
6496 (defun org-at-item-p ()
6497 "Is point in a line starting a hand-formatted item?"
6498 (let ((llt org-plain-list-ordered-item-terminator))
6499 (save-excursion
6500 (goto-char (point-at-bol))
6501 (looking-at
6502 (cond
6503 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6504 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6505 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
6506 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
6508 (defun org-in-item-p ()
6509 "It the cursor inside a plain list item.
6510 Does not have to be the first line."
6511 (save-excursion
6512 (condition-case nil
6513 (progn
6514 (org-beginning-of-item)
6515 (org-at-item-p)
6517 (error nil))))
6519 (defun org-insert-item (&optional checkbox)
6520 "Insert a new item at the current level.
6521 Return t when things worked, nil when we are not in an item."
6522 (when (save-excursion
6523 (condition-case nil
6524 (progn
6525 (org-beginning-of-item)
6526 (org-at-item-p)
6527 (if (org-invisible-p) (error "Invisible item"))
6529 (error nil)))
6530 (let* ((bul (match-string 0))
6531 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
6532 (match-end 0)))
6533 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
6534 pos)
6535 (cond
6536 ((and (org-at-item-p) (<= (point) eow))
6537 ;; before the bullet
6538 (beginning-of-line 1)
6539 (open-line (if blank 2 1)))
6540 ((<= (point) eow)
6541 (beginning-of-line 1))
6542 (t (newline (if blank 2 1))))
6543 (insert bul (if checkbox "[ ]" ""))
6544 (just-one-space)
6545 (setq pos (point))
6546 (end-of-line 1)
6547 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
6548 (org-maybe-renumber-ordered-list)
6549 (and checkbox (org-update-checkbox-count-maybe))
6552 ;;; Checkboxes
6554 (defun org-at-item-checkbox-p ()
6555 "Is point at a line starting a plain-list item with a checklet?"
6556 (and (org-at-item-p)
6557 (save-excursion
6558 (goto-char (match-end 0))
6559 (skip-chars-forward " \t")
6560 (looking-at "\\[[- X]\\]"))))
6562 (defun org-toggle-checkbox (&optional arg)
6563 "Toggle the checkbox in the current line."
6564 (interactive "P")
6565 (catch 'exit
6566 (let (beg end status (firstnew 'unknown))
6567 (cond
6568 ((org-region-active-p)
6569 (setq beg (region-beginning) end (region-end)))
6570 ((org-on-heading-p)
6571 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
6572 ((org-at-item-checkbox-p)
6573 (let ((pos (point)))
6574 (replace-match
6575 (cond (arg "[-]")
6576 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
6577 (t "[ ]"))
6578 t t)
6579 (goto-char pos))
6580 (throw 'exit t))
6581 (t (error "Not at a checkbox or heading, and no active region")))
6582 (save-excursion
6583 (goto-char beg)
6584 (while (< (point) end)
6585 (when (org-at-item-checkbox-p)
6586 (setq status (equal (match-string 0) "[X]"))
6587 (when (eq firstnew 'unknown)
6588 (setq firstnew (not status)))
6589 (replace-match
6590 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
6591 (beginning-of-line 2)))))
6592 (org-update-checkbox-count-maybe))
6594 (defun org-update-checkbox-count-maybe ()
6595 "Update checkbox statistics unless turned off by user."
6596 (when org-provide-checkbox-statistics
6597 (org-update-checkbox-count)))
6599 (defun org-update-checkbox-count (&optional all)
6600 "Update the checkbox statistics in the current section.
6601 This will find all statistic cookies like [57%] and [6/12] and update them
6602 with the current numbers. With optional prefix argument ALL, do this for
6603 the whole buffer."
6604 (interactive "P")
6605 (save-excursion
6606 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
6607 (beg (condition-case nil
6608 (progn (outline-back-to-heading) (point))
6609 (error (point-min))))
6610 (end (move-marker (make-marker)
6611 (progn (outline-next-heading) (point))))
6612 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
6613 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
6614 b1 e1 f1 c-on c-off lim (cstat 0))
6615 (when all
6616 (goto-char (point-min))
6617 (outline-next-heading)
6618 (setq beg (point) end (point-max)))
6619 (goto-char beg)
6620 (while (re-search-forward re end t)
6621 (setq cstat (1+ cstat)
6622 b1 (match-beginning 0)
6623 e1 (match-end 0)
6624 f1 (match-beginning 1)
6625 lim (cond
6626 ((org-on-heading-p) (outline-next-heading) (point))
6627 ((org-at-item-p) (org-end-of-item) (point))
6628 (t nil))
6629 c-on 0 c-off 0)
6630 (goto-char e1)
6631 (when lim
6632 (while (re-search-forward re-box lim t)
6633 (if (member (match-string 2) '("[ ]" "[-]"))
6634 (setq c-off (1+ c-off))
6635 (setq c-on (1+ c-on))))
6636 ; (delete-region b1 e1)
6637 (goto-char b1)
6638 (insert (if f1
6639 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
6640 (format "[%d/%d]" c-on (+ c-on c-off))))
6641 (and (looking-at "\\[.*?\\]")
6642 (replace-match ""))))
6643 (when (interactive-p)
6644 (message "Checkbox satistics updated %s (%d places)"
6645 (if all "in entire file" "in current outline entry") cstat)))))
6647 (defun org-get-checkbox-statistics-face ()
6648 "Select the face for checkbox statistics.
6649 The face will be `org-done' when all relevant boxes are checked. Otherwise
6650 it will be `org-todo'."
6651 (if (match-end 1)
6652 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
6653 (if (and (> (match-end 2) (match-beginning 2))
6654 (equal (match-string 2) (match-string 3)))
6655 'org-done
6656 'org-todo)))
6658 (defun org-get-indentation (&optional line)
6659 "Get the indentation of the current line, interpreting tabs.
6660 When LINE is given, assume it represents a line and compute its indentation."
6661 (if line
6662 (if (string-match "^ *" (org-remove-tabs line))
6663 (match-end 0))
6664 (save-excursion
6665 (beginning-of-line 1)
6666 (skip-chars-forward " \t")
6667 (current-column))))
6669 (defun org-remove-tabs (s &optional width)
6670 "Replace tabulators in S with spaces.
6671 Assumes that s is a single line, starting in column 0."
6672 (setq width (or width tab-width))
6673 (while (string-match "\t" s)
6674 (setq s (replace-match
6675 (make-string
6676 (- (* width (/ (+ (match-beginning 0) width) width))
6677 (match-beginning 0)) ?\ )
6678 t t s)))
6681 (defun org-fix-indentation (line ind)
6682 "Fix indentation in LINE.
6683 IND is a cons cell with target and minimum indentation.
6684 If the current indenation in LINE is smaller than the minimum,
6685 leave it alone. If it is larger than ind, set it to the target."
6686 (let* ((l (org-remove-tabs line))
6687 (i (org-get-indentation l))
6688 (i1 (car ind)) (i2 (cdr ind)))
6689 (if (>= i i2) (setq l (substring line i2)))
6690 (if (> i1 0)
6691 (concat (make-string i1 ?\ ) l)
6692 l)))
6694 (defcustom org-empty-line-terminates-plain-lists nil
6695 "Non-nil means, an empty line ends all plain list levels.
6696 When nil, empty lines are part of the preceeding item."
6697 :group 'org-plain-lists
6698 :type 'boolean)
6700 (defun org-beginning-of-item ()
6701 "Go to the beginning of the current hand-formatted item.
6702 If the cursor is not in an item, throw an error."
6703 (interactive)
6704 (let ((pos (point))
6705 (limit (save-excursion
6706 (condition-case nil
6707 (progn
6708 (org-back-to-heading)
6709 (beginning-of-line 2) (point))
6710 (error (point-min)))))
6711 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6712 ind ind1)
6713 (if (org-at-item-p)
6714 (beginning-of-line 1)
6715 (beginning-of-line 1)
6716 (skip-chars-forward " \t")
6717 (setq ind (current-column))
6718 (if (catch 'exit
6719 (while t
6720 (beginning-of-line 0)
6721 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
6723 (if (looking-at "[ \t]*$")
6724 (setq ind1 ind-empty)
6725 (skip-chars-forward " \t")
6726 (setq ind1 (current-column)))
6727 (if (< ind1 ind)
6728 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
6730 (goto-char pos)
6731 (error "Not in an item")))))
6733 (defun org-end-of-item ()
6734 "Go to the end of the current hand-formatted item.
6735 If the cursor is not in an item, throw an error."
6736 (interactive)
6737 (let* ((pos (point))
6738 ind1
6739 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
6740 (limit (save-excursion (outline-next-heading) (point)))
6741 (ind (save-excursion
6742 (org-beginning-of-item)
6743 (skip-chars-forward " \t")
6744 (current-column)))
6745 (end (catch 'exit
6746 (while t
6747 (beginning-of-line 2)
6748 (if (eobp) (throw 'exit (point)))
6749 (if (>= (point) limit) (throw 'exit (point-at-bol)))
6750 (if (looking-at "[ \t]*$")
6751 (setq ind1 ind-empty)
6752 (skip-chars-forward " \t")
6753 (setq ind1 (current-column)))
6754 (if (<= ind1 ind)
6755 (throw 'exit (point-at-bol)))))))
6756 (if end
6757 (goto-char end)
6758 (goto-char pos)
6759 (error "Not in an item"))))
6761 (defun org-next-item ()
6762 "Move to the beginning of the next item in the current plain list.
6763 Error if not at a plain list, or if this is the last item in the list."
6764 (interactive)
6765 (let (ind ind1 (pos (point)))
6766 (org-beginning-of-item)
6767 (setq ind (org-get-indentation))
6768 (org-end-of-item)
6769 (setq ind1 (org-get-indentation))
6770 (unless (and (org-at-item-p) (= ind ind1))
6771 (goto-char pos)
6772 (error "On last item"))))
6774 (defun org-previous-item ()
6775 "Move to the beginning of the previous item in the current plain list.
6776 Error if not at a plain list, or if this is the first item in the list."
6777 (interactive)
6778 (let (beg ind ind1 (pos (point)))
6779 (org-beginning-of-item)
6780 (setq beg (point))
6781 (setq ind (org-get-indentation))
6782 (goto-char beg)
6783 (catch 'exit
6784 (while t
6785 (beginning-of-line 0)
6786 (if (looking-at "[ \t]*$")
6788 (if (<= (setq ind1 (org-get-indentation)) ind)
6789 (throw 'exit t)))))
6790 (condition-case nil
6791 (if (or (not (org-at-item-p))
6792 (< ind1 (1- ind)))
6793 (error "")
6794 (org-beginning-of-item))
6795 (error (goto-char pos)
6796 (error "On first item")))))
6798 (defun org-move-item-down ()
6799 "Move the plain list item at point down, i.e. swap with following item.
6800 Subitems (items with larger indentation) are considered part of the item,
6801 so this really moves item trees."
6802 (interactive)
6803 (let (beg end ind ind1 (pos (point)) txt)
6804 (org-beginning-of-item)
6805 (setq beg (point))
6806 (setq ind (org-get-indentation))
6807 (org-end-of-item)
6808 (setq end (point))
6809 (setq ind1 (org-get-indentation))
6810 (if (and (org-at-item-p) (= ind ind1))
6811 (progn
6812 (org-end-of-item)
6813 (setq txt (buffer-substring beg end))
6814 (save-excursion
6815 (delete-region beg end))
6816 (setq pos (point))
6817 (insert txt)
6818 (goto-char pos)
6819 (org-maybe-renumber-ordered-list))
6820 (goto-char pos)
6821 (error "Cannot move this item further down"))))
6823 (defun org-move-item-up (arg)
6824 "Move the plain list item at point up, i.e. swap with previous item.
6825 Subitems (items with larger indentation) are considered part of the item,
6826 so this really moves item trees."
6827 (interactive "p")
6828 (let (beg end ind ind1 (pos (point)) txt)
6829 (org-beginning-of-item)
6830 (setq beg (point))
6831 (setq ind (org-get-indentation))
6832 (org-end-of-item)
6833 (setq end (point))
6834 (goto-char beg)
6835 (catch 'exit
6836 (while t
6837 (beginning-of-line 0)
6838 (if (looking-at "[ \t]*$")
6839 (if org-empty-line-terminates-plain-lists
6840 (progn
6841 (goto-char pos)
6842 (error "Cannot move this item further up"))
6843 nil)
6844 (if (<= (setq ind1 (org-get-indentation)) ind)
6845 (throw 'exit t)))))
6846 (condition-case nil
6847 (org-beginning-of-item)
6848 (error (goto-char beg)
6849 (error "Cannot move this item further up")))
6850 (setq ind1 (org-get-indentation))
6851 (if (and (org-at-item-p) (= ind ind1))
6852 (progn
6853 (setq txt (buffer-substring beg end))
6854 (save-excursion
6855 (delete-region beg end))
6856 (setq pos (point))
6857 (insert txt)
6858 (goto-char pos)
6859 (org-maybe-renumber-ordered-list))
6860 (goto-char pos)
6861 (error "Cannot move this item further up"))))
6863 (defun org-maybe-renumber-ordered-list ()
6864 "Renumber the ordered list at point if setup allows it.
6865 This tests the user option `org-auto-renumber-ordered-lists' before
6866 doing the renumbering."
6867 (interactive)
6868 (when (and org-auto-renumber-ordered-lists
6869 (org-at-item-p))
6870 (if (match-beginning 3)
6871 (org-renumber-ordered-list 1)
6872 (org-fix-bullet-type))))
6874 (defun org-maybe-renumber-ordered-list-safe ()
6875 (condition-case nil
6876 (save-excursion
6877 (org-maybe-renumber-ordered-list))
6878 (error nil)))
6880 (defun org-cycle-list-bullet (&optional which)
6881 "Cycle through the different itemize/enumerate bullets.
6882 This cycle the entire list level through the sequence:
6884 `-' -> `+' -> `*' -> `1.' -> `1)'
6886 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
6887 0 meand `-', 1 means `+' etc."
6888 (interactive "P")
6889 (org-preserve-lc
6890 (org-beginning-of-item-list)
6891 (org-at-item-p)
6892 (beginning-of-line 1)
6893 (let ((current (match-string 0))
6894 (prevp (eq which 'previous))
6895 new)
6896 (setq new (cond
6897 ((and (numberp which)
6898 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6899 ((string-match "-" current) (if prevp "1)" "+"))
6900 ((string-match "\\+" current)
6901 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6902 ((string-match "\\*" current) (if prevp "+" "1."))
6903 ((string-match "\\." current) (if prevp "*" "1)"))
6904 ((string-match ")" current) (if prevp "1." "-"))
6905 (t (error "This should not happen"))))
6906 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6907 (org-fix-bullet-type)
6908 (org-maybe-renumber-ordered-list))))
6910 (defun org-get-string-indentation (s)
6911 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6912 (let ((n -1) (i 0) (w tab-width) c)
6913 (catch 'exit
6914 (while (< (setq n (1+ n)) (length s))
6915 (setq c (aref s n))
6916 (cond ((= c ?\ ) (setq i (1+ i)))
6917 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6918 (t (throw 'exit t)))))
6921 (defun org-renumber-ordered-list (arg)
6922 "Renumber an ordered plain list.
6923 Cursor needs to be in the first line of an item, the line that starts
6924 with something like \"1.\" or \"2)\"."
6925 (interactive "p")
6926 (unless (and (org-at-item-p)
6927 (match-beginning 3))
6928 (error "This is not an ordered list"))
6929 (let ((line (org-current-line))
6930 (col (current-column))
6931 (ind (org-get-string-indentation
6932 (buffer-substring (point-at-bol) (match-beginning 3))))
6933 ;; (term (substring (match-string 3) -1))
6934 ind1 (n (1- arg))
6935 fmt)
6936 ;; find where this list begins
6937 (org-beginning-of-item-list)
6938 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6939 (setq fmt (concat "%d" (match-string 1)))
6940 (beginning-of-line 0)
6941 ;; walk forward and replace these numbers
6942 (catch 'exit
6943 (while t
6944 (catch 'next
6945 (beginning-of-line 2)
6946 (if (eobp) (throw 'exit nil))
6947 (if (looking-at "[ \t]*$") (throw 'next nil))
6948 (skip-chars-forward " \t") (setq ind1 (current-column))
6949 (if (> ind1 ind) (throw 'next t))
6950 (if (< ind1 ind) (throw 'exit t))
6951 (if (not (org-at-item-p)) (throw 'exit nil))
6952 (delete-region (match-beginning 2) (match-end 2))
6953 (goto-char (match-beginning 2))
6954 (insert (format fmt (setq n (1+ n)))))))
6955 (goto-line line)
6956 (move-to-column col)))
6958 (defun org-fix-bullet-type ()
6959 "Make sure all items in this list have the same bullet as the firsst item."
6960 (interactive)
6961 (unless (org-at-item-p) (error "This is not a list"))
6962 (let ((line (org-current-line))
6963 (col (current-column))
6964 (ind (current-indentation))
6965 ind1 bullet)
6966 ;; find where this list begins
6967 (org-beginning-of-item-list)
6968 (beginning-of-line 1)
6969 ;; find out what the bullet type is
6970 (looking-at "[ \t]*\\(\\S-+\\)")
6971 (setq bullet (match-string 1))
6972 ;; walk forward and replace these numbers
6973 (beginning-of-line 0)
6974 (catch 'exit
6975 (while t
6976 (catch 'next
6977 (beginning-of-line 2)
6978 (if (eobp) (throw 'exit nil))
6979 (if (looking-at "[ \t]*$") (throw 'next nil))
6980 (skip-chars-forward " \t") (setq ind1 (current-column))
6981 (if (> ind1 ind) (throw 'next t))
6982 (if (< ind1 ind) (throw 'exit t))
6983 (if (not (org-at-item-p)) (throw 'exit nil))
6984 (skip-chars-forward " \t")
6985 (looking-at "\\S-+")
6986 (replace-match bullet))))
6987 (goto-line line)
6988 (move-to-column col)
6989 (if (string-match "[0-9]" bullet)
6990 (org-renumber-ordered-list 1))))
6992 (defun org-beginning-of-item-list ()
6993 "Go to the beginning of the current item list.
6994 I.e. to the first item in this list."
6995 (interactive)
6996 (org-beginning-of-item)
6997 (let ((pos (point-at-bol))
6998 (ind (org-get-indentation))
6999 ind1)
7000 ;; find where this list begins
7001 (catch 'exit
7002 (while t
7003 (catch 'next
7004 (beginning-of-line 0)
7005 (if (looking-at "[ \t]*$")
7006 (throw (if (bobp) 'exit 'next) t))
7007 (skip-chars-forward " \t") (setq ind1 (current-column))
7008 (if (or (< ind1 ind)
7009 (and (= ind1 ind)
7010 (not (org-at-item-p)))
7011 (bobp))
7012 (throw 'exit t)
7013 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7014 (goto-char pos)))
7017 (defun org-end-of-item-list ()
7018 "Go to the end of the current item list.
7019 I.e. to the text after the last item."
7020 (interactive)
7021 (org-beginning-of-item)
7022 (let ((pos (point-at-bol))
7023 (ind (org-get-indentation))
7024 ind1)
7025 ;; find where this list begins
7026 (catch 'exit
7027 (while t
7028 (catch 'next
7029 (beginning-of-line 2)
7030 (if (looking-at "[ \t]*$")
7031 (throw (if (eobp) 'exit 'next) t))
7032 (skip-chars-forward " \t") (setq ind1 (current-column))
7033 (if (or (< ind1 ind)
7034 (and (= ind1 ind)
7035 (not (org-at-item-p)))
7036 (eobp))
7037 (progn
7038 (setq pos (point-at-bol))
7039 (throw 'exit t))))))
7040 (goto-char pos)))
7043 (defvar org-last-indent-begin-marker (make-marker))
7044 (defvar org-last-indent-end-marker (make-marker))
7046 (defun org-outdent-item (arg)
7047 "Outdent a local list item."
7048 (interactive "p")
7049 (org-indent-item (- arg)))
7051 (defun org-indent-item (arg)
7052 "Indent a local list item."
7053 (interactive "p")
7054 (unless (org-at-item-p)
7055 (error "Not on an item"))
7056 (save-excursion
7057 (let (beg end ind ind1 tmp delta ind-down ind-up)
7058 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7059 (setq beg org-last-indent-begin-marker
7060 end org-last-indent-end-marker)
7061 (org-beginning-of-item)
7062 (setq beg (move-marker org-last-indent-begin-marker (point)))
7063 (org-end-of-item)
7064 (setq end (move-marker org-last-indent-end-marker (point))))
7065 (goto-char beg)
7066 (setq tmp (org-item-indent-positions)
7067 ind (car tmp)
7068 ind-down (nth 2 tmp)
7069 ind-up (nth 1 tmp)
7070 delta (if (> arg 0)
7071 (if ind-down (- ind-down ind) 2)
7072 (if ind-up (- ind-up ind) -2)))
7073 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7074 (while (< (point) end)
7075 (beginning-of-line 1)
7076 (skip-chars-forward " \t") (setq ind1 (current-column))
7077 (delete-region (point-at-bol) (point))
7078 (or (eolp) (indent-to-column (+ ind1 delta)))
7079 (beginning-of-line 2))))
7080 (org-fix-bullet-type)
7081 (org-maybe-renumber-ordered-list-safe)
7082 (save-excursion
7083 (beginning-of-line 0)
7084 (condition-case nil (org-beginning-of-item) (error nil))
7085 (org-maybe-renumber-ordered-list-safe)))
7087 (defun org-item-indent-positions ()
7088 "Return indentation for plain list items.
7089 This returns a list with three values: The current indentation, the
7090 parent indentation and the indentation a child should habe.
7091 Assumes cursor in item line."
7092 (let* ((bolpos (point-at-bol))
7093 (ind (org-get-indentation))
7094 ind-down ind-up pos)
7095 (save-excursion
7096 (org-beginning-of-item-list)
7097 (skip-chars-backward "\n\r \t")
7098 (when (org-in-item-p)
7099 (org-beginning-of-item)
7100 (setq ind-up (org-get-indentation))))
7101 (setq pos (point))
7102 (save-excursion
7103 (cond
7104 ((and (condition-case nil (progn (org-previous-item) t)
7105 (error nil))
7106 (or (forward-char 1) t)
7107 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7108 (setq ind-down (org-get-indentation)))
7109 ((and (goto-char pos)
7110 (org-at-item-p))
7111 (goto-char (match-end 0))
7112 (skip-chars-forward " \t")
7113 (setq ind-down (current-column)))))
7114 (list ind ind-up ind-down)))
7116 ;;; The orgstruct minor mode
7118 ;; Define a minor mode which can be used in other modes in order to
7119 ;; integrate the org-mode structure editing commands.
7121 ;; This is really a hack, because the org-mode structure commands use
7122 ;; keys which normally belong to the major mode. Here is how it
7123 ;; works: The minor mode defines all the keys necessary to operate the
7124 ;; structure commands, but wraps the commands into a function which
7125 ;; tests if the cursor is currently at a headline or a plain list
7126 ;; item. If that is the case, the structure command is used,
7127 ;; temporarily setting many Org-mode variables like regular
7128 ;; expressions for filling etc. However, when any of those keys is
7129 ;; used at a different location, function uses `key-binding' to look
7130 ;; up if the key has an associated command in another currently active
7131 ;; keymap (minor modes, major mode, global), and executes that
7132 ;; command. There might be problems if any of the keys is otherwise
7133 ;; used as a prefix key.
7135 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7136 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7137 ;; addresses this by checking explicitly for both bindings.
7139 (defvar orgstruct-mode-map (make-sparse-keymap)
7140 "Keymap for the minor `orgstruct-mode'.")
7142 (defvar org-local-vars nil
7143 "List of local variables, for use by `orgstruct-mode'")
7145 ;;;###autoload
7146 (define-minor-mode orgstruct-mode
7147 "Toggle the minor more `orgstruct-mode'.
7148 This mode is for using Org-mode structure commands in other modes.
7149 The following key behave as if Org-mode was active, if the cursor
7150 is on a headline, or on a plain list item (both in the definition
7151 of Org-mode).
7153 M-up Move entry/item up
7154 M-down Move entry/item down
7155 M-left Promote
7156 M-right Demote
7157 M-S-up Move entry/item up
7158 M-S-down Move entry/item down
7159 M-S-left Promote subtree
7160 M-S-right Demote subtree
7161 M-q Fill paragraph and items like in Org-mode
7162 C-c ^ Sort entries
7163 C-c - Cycle list bullet
7164 TAB Cycle item visibility
7165 M-RET Insert new heading/item
7166 S-M-RET Insert new TODO heading / Chekbox item
7167 C-c C-c Set tags / toggle checkbox"
7168 nil " OrgStruct" nil
7169 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7171 ;;;###autoload
7172 (defun turn-on-orgstruct ()
7173 "Unconditionally turn on `orgstruct-mode'."
7174 (orgstruct-mode 1))
7176 ;;;###autoload
7177 (defun turn-on-orgstruct++ ()
7178 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7179 In addition to setting orgstruct-mode, this also exports all indentation and
7180 autofilling variables from org-mode into the buffer. Note that turning
7181 off orgstruct-mode will *not* remove these additonal settings."
7182 (orgstruct-mode 1)
7183 (let (var val)
7184 (mapc
7185 (lambda (x)
7186 (when (string-match
7187 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7188 (symbol-name (car x)))
7189 (setq var (car x) val (nth 1 x))
7190 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7191 org-local-vars)))
7193 (defun orgstruct-error ()
7194 "Error when there is no default binding for a structure key."
7195 (interactive)
7196 (error "This key is has no function outside structure elements"))
7198 (defun orgstruct-setup ()
7199 "Setup orgstruct keymaps."
7200 (let ((nfunc 0)
7201 (bindings
7202 (list
7203 '([(meta up)] org-metaup)
7204 '([(meta down)] org-metadown)
7205 '([(meta left)] org-metaleft)
7206 '([(meta right)] org-metaright)
7207 '([(meta shift up)] org-shiftmetaup)
7208 '([(meta shift down)] org-shiftmetadown)
7209 '([(meta shift left)] org-shiftmetaleft)
7210 '([(meta shift right)] org-shiftmetaright)
7211 '([(shift up)] org-shiftup)
7212 '([(shift down)] org-shiftdown)
7213 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7214 '("\M-q" fill-paragraph)
7215 '("\C-c^" org-sort)
7216 '("\C-c-" org-cycle-list-bullet)))
7217 elt key fun cmd)
7218 (while (setq elt (pop bindings))
7219 (setq nfunc (1+ nfunc))
7220 (setq key (org-key (car elt))
7221 fun (nth 1 elt)
7222 cmd (orgstruct-make-binding fun nfunc key))
7223 (org-defkey orgstruct-mode-map key cmd))
7225 ;; Special treatment needed for TAB and RET
7226 (org-defkey orgstruct-mode-map [(tab)]
7227 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7228 (org-defkey orgstruct-mode-map "\C-i"
7229 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7231 (org-defkey orgstruct-mode-map "\M-\C-m"
7232 (orgstruct-make-binding 'org-insert-heading 105
7233 "\M-\C-m" [(meta return)]))
7234 (org-defkey orgstruct-mode-map [(meta return)]
7235 (orgstruct-make-binding 'org-insert-heading 106
7236 [(meta return)] "\M-\C-m"))
7238 (org-defkey orgstruct-mode-map [(shift meta return)]
7239 (orgstruct-make-binding 'org-insert-todo-heading 107
7240 [(meta return)] "\M-\C-m"))
7242 (unless org-local-vars
7243 (setq org-local-vars (org-get-local-variables)))
7247 (defun orgstruct-make-binding (fun n &rest keys)
7248 "Create a function for binding in the structure minor mode.
7249 FUN is the command to call inside a table. N is used to create a unique
7250 command name. KEYS are keys that should be checked in for a command
7251 to execute outside of tables."
7252 (eval
7253 (list 'defun
7254 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7255 '(arg)
7256 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7257 "Outside of structure, run the binding of `"
7258 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7259 "'.")
7260 '(interactive "p")
7261 (list 'if
7262 '(org-context-p 'headline 'item)
7263 (list 'org-run-like-in-org-mode (list 'quote fun))
7264 (list 'let '(orgstruct-mode)
7265 (list 'call-interactively
7266 (append '(or)
7267 (mapcar (lambda (k)
7268 (list 'key-binding k))
7269 keys)
7270 '('orgstruct-error))))))))
7272 (defun org-context-p (&rest contexts)
7273 "Check if local context is and of CONTEXTS.
7274 Possible values in the list of contexts are `table', `headline', and `item'."
7275 (let ((pos (point)))
7276 (goto-char (point-at-bol))
7277 (prog1 (or (and (memq 'table contexts)
7278 (looking-at "[ \t]*|"))
7279 (and (memq 'headline contexts)
7280 (looking-at "\\*+"))
7281 (and (memq 'item contexts)
7282 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7283 (goto-char pos))))
7285 (defun org-get-local-variables ()
7286 "Return a list of all local variables in an org-mode buffer."
7287 (let (varlist)
7288 (with-current-buffer (get-buffer-create "*Org tmp*")
7289 (erase-buffer)
7290 (org-mode)
7291 (setq varlist (buffer-local-variables)))
7292 (kill-buffer "*Org tmp*")
7293 (delq nil
7294 (mapcar
7295 (lambda (x)
7296 (setq x
7297 (if (symbolp x)
7298 (list x)
7299 (list (car x) (list 'quote (cdr x)))))
7300 (if (string-match
7301 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7302 (symbol-name (car x)))
7303 x nil))
7304 varlist))))
7306 ;;;###autoload
7307 (defun org-run-like-in-org-mode (cmd)
7308 (unless org-local-vars
7309 (setq org-local-vars (org-get-local-variables)))
7310 (eval (list 'let org-local-vars
7311 (list 'call-interactively (list 'quote cmd)))))
7313 ;;;; Archiving
7315 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7317 (defun org-archive-subtree (&optional find-done)
7318 "Move the current subtree to the archive.
7319 The archive can be a certain top-level heading in the current file, or in
7320 a different file. The tree will be moved to that location, the subtree
7321 heading be marked DONE, and the current time will be added.
7323 When called with prefix argument FIND-DONE, find whole trees without any
7324 open TODO items and archive them (after getting confirmation from the user).
7325 If the cursor is not at a headline when this comand is called, try all level
7326 1 trees. If the cursor is on a headline, only try the direct children of
7327 this heading."
7328 (interactive "P")
7329 (if find-done
7330 (org-archive-all-done)
7331 ;; Save all relevant TODO keyword-relatex variables
7333 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
7334 (tr-org-todo-keywords-1 org-todo-keywords-1)
7335 (tr-org-todo-kwd-alist org-todo-kwd-alist)
7336 (tr-org-done-keywords org-done-keywords)
7337 (tr-org-todo-regexp org-todo-regexp)
7338 (tr-org-todo-line-regexp org-todo-line-regexp)
7339 (tr-org-odd-levels-only org-odd-levels-only)
7340 (this-buffer (current-buffer))
7341 (org-archive-location org-archive-location)
7342 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
7343 ;; start of variables that will be used for saving context
7344 ;; The compiler complains about them - keep them anyway!
7345 (file (abbreviate-file-name (buffer-file-name)))
7346 (time (format-time-string
7347 (substring (cdr org-time-stamp-formats) 1 -1)
7348 (current-time)))
7349 afile heading buffer level newfile-p
7350 category todo priority
7351 ;; start of variables that will be used for savind context
7352 ltags itags prop)
7354 ;; Try to find a local archive location
7355 (save-excursion
7356 (save-restriction
7357 (widen)
7358 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
7359 (if (and prop (string-match "\\S-" prop))
7360 (setq org-archive-location prop)
7361 (if (or (re-search-backward re nil t)
7362 (re-search-forward re nil t))
7363 (setq org-archive-location (match-string 1))))))
7365 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
7366 (progn
7367 (setq afile (format (match-string 1 org-archive-location)
7368 (file-name-nondirectory buffer-file-name))
7369 heading (match-string 2 org-archive-location)))
7370 (error "Invalid `org-archive-location'"))
7371 (if (> (length afile) 0)
7372 (setq newfile-p (not (file-exists-p afile))
7373 buffer (find-file-noselect afile))
7374 (setq buffer (current-buffer)))
7375 (unless buffer
7376 (error "Cannot access file \"%s\"" afile))
7377 (if (and (> (length heading) 0)
7378 (string-match "^\\*+" heading))
7379 (setq level (match-end 0))
7380 (setq heading nil level 0))
7381 (save-excursion
7382 (org-back-to-heading t)
7383 ;; Get context information that will be lost by moving the tree
7384 (org-refresh-category-properties)
7385 (setq category (org-get-category)
7386 todo (and (looking-at org-todo-line-regexp)
7387 (match-string 2))
7388 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
7389 ltags (org-get-tags)
7390 itags (org-delete-all ltags (org-get-tags-at)))
7391 (setq ltags (mapconcat 'identity ltags " ")
7392 itags (mapconcat 'identity itags " "))
7393 ;; We first only copy, in case something goes wrong
7394 ;; we need to protect this-command, to avoid kill-region sets it,
7395 ;; which would lead to duplication of subtrees
7396 (let (this-command) (org-copy-subtree))
7397 (set-buffer buffer)
7398 ;; Enforce org-mode for the archive buffer
7399 (if (not (org-mode-p))
7400 ;; Force the mode for future visits.
7401 (let ((org-insert-mode-line-in-empty-file t)
7402 (org-inhibit-startup t))
7403 (call-interactively 'org-mode)))
7404 (when newfile-p
7405 (goto-char (point-max))
7406 (insert (format "\nArchived entries from file %s\n\n"
7407 (buffer-file-name this-buffer))))
7408 ;; Force the TODO keywords of the original buffer
7409 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
7410 (org-todo-keywords-1 tr-org-todo-keywords-1)
7411 (org-todo-kwd-alist tr-org-todo-kwd-alist)
7412 (org-done-keywords tr-org-done-keywords)
7413 (org-todo-regexp tr-org-todo-regexp)
7414 (org-todo-line-regexp tr-org-todo-line-regexp)
7415 (org-odd-levels-only
7416 (if (local-variable-p 'org-odd-levels-only (current-buffer))
7417 org-odd-levels-only
7418 tr-org-odd-levels-only)))
7419 (goto-char (point-min))
7420 (if heading
7421 (progn
7422 (if (re-search-forward
7423 (concat "^" (regexp-quote heading)
7424 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
7425 nil t)
7426 (goto-char (match-end 0))
7427 ;; Heading not found, just insert it at the end
7428 (goto-char (point-max))
7429 (or (bolp) (insert "\n"))
7430 (insert "\n" heading "\n")
7431 (end-of-line 0))
7432 ;; Make the subtree visible
7433 (show-subtree)
7434 (org-end-of-subtree t)
7435 (skip-chars-backward " \t\r\n")
7436 (and (looking-at "[ \t\r\n]*")
7437 (replace-match "\n\n")))
7438 ;; No specific heading, just go to end of file.
7439 (goto-char (point-max)) (insert "\n"))
7440 ;; Paste
7441 (org-paste-subtree (org-get-legal-level level 1))
7443 ;; Mark the entry as done
7444 (when (and org-archive-mark-done
7445 (looking-at org-todo-line-regexp)
7446 (or (not (match-end 2))
7447 (not (member (match-string 2) org-done-keywords))))
7448 (let (org-log-done)
7449 (org-todo
7450 (car (or (member org-archive-mark-done org-done-keywords)
7451 org-done-keywords)))))
7453 ;; Add the context info
7454 (when org-archive-save-context-info
7455 (let ((l org-archive-save-context-info) e n v)
7456 (while (setq e (pop l))
7457 (when (and (setq v (symbol-value e))
7458 (stringp v) (string-match "\\S-" v))
7459 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
7460 (org-entry-put (point) n v)))))
7462 ;; Save the buffer, if it is not the same buffer.
7463 (if (not (eq this-buffer buffer)) (save-buffer))))
7464 ;; Here we are back in the original buffer. Everything seems to have
7465 ;; worked. So now cut the tree and finish up.
7466 (let (this-command) (org-cut-subtree))
7467 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
7468 (message "Subtree archived %s"
7469 (if (eq this-buffer buffer)
7470 (concat "under heading: " heading)
7471 (concat "in file: " (abbreviate-file-name afile)))))))
7473 (defun org-refresh-category-properties ()
7474 "Refresh category text properties in teh buffer."
7475 (let ((def-cat (cond
7476 ((null org-category)
7477 (if buffer-file-name
7478 (file-name-sans-extension
7479 (file-name-nondirectory buffer-file-name))
7480 "???"))
7481 ((symbolp org-category) (symbol-name org-category))
7482 (t org-category)))
7483 beg end cat pos optionp)
7484 (org-unmodified
7485 (save-excursion
7486 (save-restriction
7487 (widen)
7488 (goto-char (point-min))
7489 (put-text-property (point) (point-max) 'org-category def-cat)
7490 (while (re-search-forward
7491 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7492 (setq pos (match-end 0)
7493 optionp (equal (char-after (match-beginning 0)) ?#)
7494 cat (org-trim (match-string 2)))
7495 (if optionp
7496 (setq beg (point-at-bol) end (point-max))
7497 (org-back-to-heading t)
7498 (setq beg (point) end (org-end-of-subtree t t)))
7499 (put-text-property beg end 'org-category cat)
7500 (goto-char pos)))))))
7502 (defun org-archive-all-done (&optional tag)
7503 "Archive sublevels of the current tree without open TODO items.
7504 If the cursor is not on a headline, try all level 1 trees. If
7505 it is on a headline, try all direct children.
7506 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
7507 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
7508 (rea (concat ".*:" org-archive-tag ":"))
7509 (begm (make-marker))
7510 (endm (make-marker))
7511 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
7512 "Move subtree to archive (no open TODO items)? "))
7513 beg end (cntarch 0))
7514 (if (org-on-heading-p)
7515 (progn
7516 (setq re1 (concat "^" (regexp-quote
7517 (make-string
7518 (1+ (- (match-end 0) (match-beginning 0)))
7519 ?*))
7520 " "))
7521 (move-marker begm (point))
7522 (move-marker endm (org-end-of-subtree t)))
7523 (setq re1 "^* ")
7524 (move-marker begm (point-min))
7525 (move-marker endm (point-max)))
7526 (save-excursion
7527 (goto-char begm)
7528 (while (re-search-forward re1 endm t)
7529 (setq beg (match-beginning 0)
7530 end (save-excursion (org-end-of-subtree t) (point)))
7531 (goto-char beg)
7532 (if (re-search-forward re end t)
7533 (goto-char end)
7534 (goto-char beg)
7535 (if (and (or (not tag) (not (looking-at rea)))
7536 (y-or-n-p question))
7537 (progn
7538 (if tag
7539 (org-toggle-tag org-archive-tag 'on)
7540 (org-archive-subtree))
7541 (setq cntarch (1+ cntarch)))
7542 (goto-char end)))))
7543 (message "%d trees archived" cntarch)))
7545 (defun org-cycle-hide-drawers (state)
7546 "Re-hide all drawers after a visibility state change."
7547 (when (and (org-mode-p)
7548 (not (memq state '(overview folded))))
7549 (save-excursion
7550 (let* ((globalp (memq state '(contents all)))
7551 (beg (if globalp (point-min) (point)))
7552 (end (if globalp (point-max) (org-end-of-subtree t))))
7553 (goto-char beg)
7554 (while (re-search-forward org-drawer-regexp end t)
7555 (org-flag-drawer t))))))
7557 (defun org-flag-drawer (flag)
7558 (save-excursion
7559 (beginning-of-line 1)
7560 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
7561 (let ((b (match-end 0)))
7562 (if (re-search-forward
7563 "^[ \t]*:END:"
7564 (save-excursion (outline-next-heading) (point)) t)
7565 (outline-flag-region b (point-at-eol) flag)
7566 (error ":END: line missing"))))))
7568 (defun org-cycle-hide-archived-subtrees (state)
7569 "Re-hide all archived subtrees after a visibility state change."
7570 (when (and (not org-cycle-open-archived-trees)
7571 (not (memq state '(overview folded))))
7572 (save-excursion
7573 (let* ((globalp (memq state '(contents all)))
7574 (beg (if globalp (point-min) (point)))
7575 (end (if globalp (point-max) (org-end-of-subtree t))))
7576 (org-hide-archived-subtrees beg end)
7577 (goto-char beg)
7578 (if (looking-at (concat ".*:" org-archive-tag ":"))
7579 (message (substitute-command-keys
7580 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
7582 (defun org-force-cycle-archived ()
7583 "Cycle subtree even if it is archived."
7584 (interactive)
7585 (setq this-command 'org-cycle)
7586 (let ((org-cycle-open-archived-trees t))
7587 (call-interactively 'org-cycle)))
7589 (defun org-hide-archived-subtrees (beg end)
7590 "Re-hide all archived subtrees after a visibility state change."
7591 (save-excursion
7592 (let* ((re (concat ":" org-archive-tag ":")))
7593 (goto-char beg)
7594 (while (re-search-forward re end t)
7595 (and (org-on-heading-p) (hide-subtree))
7596 (org-end-of-subtree t)))))
7598 (defun org-toggle-tag (tag &optional onoff)
7599 "Toggle the tag TAG for the current line.
7600 If ONOFF is `on' or `off', don't toggle but set to this state."
7601 (unless (org-on-heading-p t) (error "Not on headling"))
7602 (let (res current)
7603 (save-excursion
7604 (beginning-of-line)
7605 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
7606 (point-at-eol) t)
7607 (progn
7608 (setq current (match-string 1))
7609 (replace-match ""))
7610 (setq current ""))
7611 (setq current (nreverse (org-split-string current ":")))
7612 (cond
7613 ((eq onoff 'on)
7614 (setq res t)
7615 (or (member tag current) (push tag current)))
7616 ((eq onoff 'off)
7617 (or (not (member tag current)) (setq current (delete tag current))))
7618 (t (if (member tag current)
7619 (setq current (delete tag current))
7620 (setq res t)
7621 (push tag current))))
7622 (end-of-line 1)
7623 (if current
7624 (progn
7625 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
7626 (org-set-tags nil t))
7627 (delete-horizontal-space))
7628 (run-hooks 'org-after-tags-change-hook))
7629 res))
7631 (defun org-toggle-archive-tag (&optional arg)
7632 "Toggle the archive tag for the current headline.
7633 With prefix ARG, check all children of current headline and offer tagging
7634 the children that do not contain any open TODO items."
7635 (interactive "P")
7636 (if arg
7637 (org-archive-all-done 'tag)
7638 (let (set)
7639 (save-excursion
7640 (org-back-to-heading t)
7641 (setq set (org-toggle-tag org-archive-tag))
7642 (when set (hide-subtree)))
7643 (and set (beginning-of-line 1))
7644 (message "Subtree %s" (if set "archived" "unarchived")))))
7647 ;;;; Tables
7649 ;;; The table editor
7651 ;; Watch out: Here we are talking about two different kind of tables.
7652 ;; Most of the code is for the tables created with the Org-mode table editor.
7653 ;; Sometimes, we talk about tables created and edited with the table.el
7654 ;; Emacs package. We call the former org-type tables, and the latter
7655 ;; table.el-type tables.
7657 (defun org-before-change-function (beg end)
7658 "Every change indicates that a table might need an update."
7659 (setq org-table-may-need-update t))
7661 (defconst org-table-line-regexp "^[ \t]*|"
7662 "Detects an org-type table line.")
7663 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7664 "Detects an org-type table line.")
7665 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7666 "Detects a table line marked for automatic recalculation.")
7667 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7668 "Detects a table line marked for automatic recalculation.")
7669 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7670 "Detects a table line marked for automatic recalculation.")
7671 (defconst org-table-hline-regexp "^[ \t]*|-"
7672 "Detects an org-type table hline.")
7673 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7674 "Detects a table-type table hline.")
7675 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7676 "Detects an org-type or table-type table.")
7677 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7678 "Searching from within a table (any type) this finds the first line
7679 outside the table.")
7680 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7681 "Searching from within a table (any type) this finds the first line
7682 outside the table.")
7684 (defvar org-table-last-highlighted-reference nil)
7685 (defvar org-table-formula-history nil)
7687 (defvar org-table-column-names nil
7688 "Alist with column names, derived from the `!' line.")
7689 (defvar org-table-column-name-regexp nil
7690 "Regular expression matching the current column names.")
7691 (defvar org-table-local-parameters nil
7692 "Alist with parameter names, derived from the `$' line.")
7693 (defvar org-table-named-field-locations nil
7694 "Alist with locations of named fields.")
7696 (defvar org-table-current-line-types nil
7697 "Table row types, non-nil only for the duration of a comand.")
7698 (defvar org-table-current-begin-line nil
7699 "Table begin line, non-nil only for the duration of a comand.")
7700 (defvar org-table-current-begin-pos nil
7701 "Table begin position, non-nil only for the duration of a comand.")
7702 (defvar org-table-dlines nil
7703 "Vector of data line line numbers in the current table.")
7704 (defvar org-table-hlines nil
7705 "Vector of hline line numbers in the current table.")
7707 (defconst org-table-range-regexp
7708 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
7709 ;; 1 2 3 4 5
7710 "Regular expression for matching ranges in formulas.")
7712 (defconst org-table-range-regexp2
7713 (concat
7714 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
7715 "\\.\\."
7716 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
7717 "Match a range for reference display.")
7719 (defconst org-table-translate-regexp
7720 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
7721 "Match a reference that needs translation, for reference display.")
7723 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
7725 (defun org-table-create-with-table.el ()
7726 "Use the table.el package to insert a new table.
7727 If there is already a table at point, convert between Org-mode tables
7728 and table.el tables."
7729 (interactive)
7730 (require 'table)
7731 (cond
7732 ((org-at-table.el-p)
7733 (if (y-or-n-p "Convert table to Org-mode table? ")
7734 (org-table-convert)))
7735 ((org-at-table-p)
7736 (if (y-or-n-p "Convert table to table.el table? ")
7737 (org-table-convert)))
7738 (t (call-interactively 'table-insert))))
7740 (defun org-table-create-or-convert-from-region (arg)
7741 "Convert region to table, or create an empty table.
7742 If there is an active region, convert it to a table, using the function
7743 `org-table-convert-region'. See the documentation of that function
7744 to learn how the prefix argument is interpreted to determine the field
7745 separator.
7746 If there is no such region, create an empty table with `org-table-create'."
7747 (interactive "P")
7748 (if (org-region-active-p)
7749 (org-table-convert-region (region-beginning) (region-end) arg)
7750 (org-table-create arg)))
7752 (defun org-table-create (&optional size)
7753 "Query for a size and insert a table skeleton.
7754 SIZE is a string Columns x Rows like for example \"3x2\"."
7755 (interactive "P")
7756 (unless size
7757 (setq size (read-string
7758 (concat "Table size Columns x Rows [e.g. "
7759 org-table-default-size "]: ")
7760 "" nil org-table-default-size)))
7762 (let* ((pos (point))
7763 (indent (make-string (current-column) ?\ ))
7764 (split (org-split-string size " *x *"))
7765 (rows (string-to-number (nth 1 split)))
7766 (columns (string-to-number (car split)))
7767 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7768 "\n")))
7769 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7770 (point-at-bol) (point)))
7771 (beginning-of-line 1)
7772 (newline))
7773 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7774 (dotimes (i rows) (insert line))
7775 (goto-char pos)
7776 (if (> rows 1)
7777 ;; Insert a hline after the first row.
7778 (progn
7779 (end-of-line 1)
7780 (insert "\n|-")
7781 (goto-char pos)))
7782 (org-table-align)))
7784 (defun org-table-convert-region (beg0 end0 &optional separator)
7785 "Convert region to a table.
7786 The region goes from BEG0 to END0, but these borders will be moved
7787 slightly, to make sure a beginning of line in the first line is included.
7789 SEPARATOR specifies the field separator in the lines. It can have the
7790 following values:
7792 '(4) Use the comma as a field separator
7793 '(16) Use a TAB as field separator
7794 integer When a number, use that many spaces as field separator
7795 nil When nil, the command tries to be smart and figure out the
7796 separator in the following way:
7797 - when each line contains a TAB, assume TAB-separated material
7798 - when each line contains a comme, assume CSV material
7799 - else, assume one or more SPACE charcters as separator."
7800 (interactive "rP")
7801 (let* ((beg (min beg0 end0))
7802 (end (max beg0 end0))
7804 (goto-char beg)
7805 (beginning-of-line 1)
7806 (setq beg (move-marker (make-marker) (point)))
7807 (goto-char end)
7808 (if (bolp) (backward-char 1) (end-of-line 1))
7809 (setq end (move-marker (make-marker) (point)))
7810 ;; Get the right field separator
7811 (unless separator
7812 (goto-char beg)
7813 (setq separator
7814 (cond
7815 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
7816 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
7817 (t 1))))
7818 (setq re (cond
7819 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
7820 ((equal separator '(16)) "^\\|\t")
7821 ((integerp separator)
7822 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
7823 (t (error "This should not happen"))))
7824 (goto-char beg)
7825 (while (re-search-forward re end t)
7826 (replace-match "| " t t))
7827 (goto-char beg)
7828 (insert " ")
7829 (org-table-align)))
7831 (defun org-table-import (file arg)
7832 "Import FILE as a table.
7833 The file is assumed to be tab-separated. Such files can be produced by most
7834 spreadsheet and database applications. If no tabs (at least one per line)
7835 are found, lines will be split on whitespace into fields."
7836 (interactive "f\nP")
7837 (or (bolp) (newline))
7838 (let ((beg (point))
7839 (pm (point-max)))
7840 (insert-file-contents file)
7841 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7843 (defun org-table-export ()
7844 "Export table as a tab-separated file.
7845 Such a file can be imported into a spreadsheet program like Excel."
7846 (interactive)
7847 (let* ((beg (org-table-begin))
7848 (end (org-table-end))
7849 (table (buffer-substring beg end))
7850 (file (read-file-name "Export table to: "))
7851 buf)
7852 (unless (or (not (file-exists-p file))
7853 (y-or-n-p (format "Overwrite file %s? " file)))
7854 (error "Abort"))
7855 (with-current-buffer (find-file-noselect file)
7856 (setq buf (current-buffer))
7857 (erase-buffer)
7858 (fundamental-mode)
7859 (insert table)
7860 (goto-char (point-min))
7861 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7862 (replace-match "" t t)
7863 (end-of-line 1))
7864 (goto-char (point-min))
7865 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7866 (replace-match "" t t)
7867 (goto-char (min (1+ (point)) (point-max))))
7868 (goto-char (point-min))
7869 (while (re-search-forward "^-[-+]*$" nil t)
7870 (replace-match "")
7871 (if (looking-at "\n")
7872 (delete-char 1)))
7873 (goto-char (point-min))
7874 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7875 (replace-match "\t" t t))
7876 (save-buffer))
7877 (kill-buffer buf)))
7879 (defvar org-table-aligned-begin-marker (make-marker)
7880 "Marker at the beginning of the table last aligned.
7881 Used to check if cursor still is in that table, to minimize realignment.")
7882 (defvar org-table-aligned-end-marker (make-marker)
7883 "Marker at the end of the table last aligned.
7884 Used to check if cursor still is in that table, to minimize realignment.")
7885 (defvar org-table-last-alignment nil
7886 "List of flags for flushright alignment, from the last re-alignment.
7887 This is being used to correctly align a single field after TAB or RET.")
7888 (defvar org-table-last-column-widths nil
7889 "List of max width of fields in each column.
7890 This is being used to correctly align a single field after TAB or RET.")
7891 (defvar org-table-overlay-coordinates nil
7892 "Overlay coordinates after each align of a table.")
7893 (make-variable-buffer-local 'org-table-overlay-coordinates)
7895 (defvar org-last-recalc-line nil)
7896 (defconst org-narrow-column-arrow "=>"
7897 "Used as display property in narrowed table columns.")
7899 (defun org-table-align ()
7900 "Align the table at point by aligning all vertical bars."
7901 (interactive)
7902 (let* (
7903 ;; Limits of table
7904 (beg (org-table-begin))
7905 (end (org-table-end))
7906 ;; Current cursor position
7907 (linepos (org-current-line))
7908 (colpos (org-table-current-column))
7909 (winstart (window-start))
7910 (winstartline (org-current-line (min winstart (1- (point-max)))))
7911 lines (new "") lengths l typenums ty fields maxfields i
7912 column
7913 (indent "") cnt frac
7914 rfmt hfmt
7915 (spaces '(1 . 1))
7916 (sp1 (car spaces))
7917 (sp2 (cdr spaces))
7918 (rfmt1 (concat
7919 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7920 (hfmt1 (concat
7921 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7922 emptystrings links dates emph narrow fmax f1 len c e)
7923 (untabify beg end)
7924 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
7925 ;; Check if we have links or dates
7926 (goto-char beg)
7927 (setq links (re-search-forward org-bracket-link-regexp end t))
7928 (goto-char beg)
7929 (setq emph (and org-hide-emphasis-markers
7930 (re-search-forward org-emph-re end t)))
7931 (goto-char beg)
7932 (setq dates (and org-display-custom-times
7933 (re-search-forward org-ts-regexp-both end t)))
7934 ;; Make sure the link properties are right
7935 (when links (goto-char beg) (while (org-activate-bracket-links end)))
7936 ;; Make sure the date properties are right
7937 (when dates (goto-char beg) (while (org-activate-dates end)))
7938 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
7940 ;; Check if we are narrowing any columns
7941 (goto-char beg)
7942 (setq narrow (and org-format-transports-properties-p
7943 (re-search-forward "<[0-9]+>" end t)))
7944 ;; Get the rows
7945 (setq lines (org-split-string
7946 (buffer-substring beg end) "\n"))
7947 ;; Store the indentation of the first line
7948 (if (string-match "^ *" (car lines))
7949 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7950 ;; Mark the hlines by setting the corresponding element to nil
7951 ;; At the same time, we remove trailing space.
7952 (setq lines (mapcar (lambda (l)
7953 (if (string-match "^ *|-" l)
7955 (if (string-match "[ \t]+$" l)
7956 (substring l 0 (match-beginning 0))
7957 l)))
7958 lines))
7959 ;; Get the data fields by splitting the lines.
7960 (setq fields (mapcar
7961 (lambda (l)
7962 (org-split-string l " *| *"))
7963 (delq nil (copy-sequence lines))))
7964 ;; How many fields in the longest line?
7965 (condition-case nil
7966 (setq maxfields (apply 'max (mapcar 'length fields)))
7967 (error
7968 (kill-region beg end)
7969 (org-table-create org-table-default-size)
7970 (error "Empty table - created default table")))
7971 ;; A list of empty strings to fill any short rows on output
7972 (setq emptystrings (make-list maxfields ""))
7973 ;; Check for special formatting.
7974 (setq i -1)
7975 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7976 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7977 ;; Check if there is an explicit width specified
7978 (when narrow
7979 (setq c column fmax nil)
7980 (while c
7981 (setq e (pop c))
7982 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
7983 (setq fmax (string-to-number (match-string 1 e)) c nil)))
7984 ;; Find fields that are wider than fmax, and shorten them
7985 (when fmax
7986 (loop for xx in column do
7987 (when (and (stringp xx)
7988 (> (org-string-width xx) fmax))
7989 (org-add-props xx nil
7990 'help-echo
7991 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
7992 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
7993 (unless (> f1 1)
7994 (error "Cannot narrow field starting with wide link \"%s\""
7995 (match-string 0 xx)))
7996 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
7997 (add-text-properties (- f1 2) f1
7998 (list 'display org-narrow-column-arrow)
7999 xx)))))
8000 ;; Get the maximum width for each column
8001 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8002 ;; Get the fraction of numbers, to decide about alignment of the column
8003 (setq cnt 0 frac 0.0)
8004 (loop for x in column do
8005 (if (equal x "")
8007 (setq frac ( / (+ (* frac cnt)
8008 (if (string-match org-table-number-regexp x) 1 0))
8009 (setq cnt (1+ cnt))))))
8010 (push (>= frac org-table-number-fraction) typenums))
8011 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8013 ;; Store the alignment of this table, for later editing of single fields
8014 (setq org-table-last-alignment typenums
8015 org-table-last-column-widths lengths)
8017 ;; With invisible characters, `format' does not get the field width right
8018 ;; So we need to make these fields wide by hand.
8019 (when (or links emph)
8020 (loop for i from 0 upto (1- maxfields) do
8021 (setq len (nth i lengths))
8022 (loop for j from 0 upto (1- (length fields)) do
8023 (setq c (nthcdr i (car (nthcdr j fields))))
8024 (if (and (stringp (car c))
8025 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8026 ; (string-match org-bracket-link-regexp (car c))
8027 (< (org-string-width (car c)) len))
8028 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8030 ;; Compute the formats needed for output of the table
8031 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8032 (while (setq l (pop lengths))
8033 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8034 (setq rfmt (concat rfmt (format rfmt1 ty l))
8035 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8036 (setq rfmt (concat rfmt "\n")
8037 hfmt (concat (substring hfmt 0 -1) "|\n"))
8039 (setq new (mapconcat
8040 (lambda (l)
8041 (if l (apply 'format rfmt
8042 (append (pop fields) emptystrings))
8043 hfmt))
8044 lines ""))
8045 ;; Replace the old one
8046 (delete-region beg end)
8047 (move-marker end nil)
8048 (move-marker org-table-aligned-begin-marker (point))
8049 (insert new)
8050 (move-marker org-table-aligned-end-marker (point))
8051 (when (and orgtbl-mode (not (org-mode-p)))
8052 (goto-char org-table-aligned-begin-marker)
8053 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8054 ;; Try to move to the old location
8055 (goto-line winstartline)
8056 (setq winstart (point-at-bol))
8057 (goto-line linepos)
8058 (set-window-start (selected-window) winstart 'noforce)
8059 (org-table-goto-column colpos)
8060 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8061 (setq org-table-may-need-update nil)
8064 (defun org-string-width (s)
8065 "Compute width of string, ignoring invisible characters.
8066 This ignores character with invisibility property `org-link', and also
8067 characters with property `org-cwidth', because these will become invisible
8068 upon the next fontification round."
8069 (let (b l)
8070 (when (or (eq t buffer-invisibility-spec)
8071 (assq 'org-link buffer-invisibility-spec))
8072 (while (setq b (text-property-any 0 (length s)
8073 'invisible 'org-link s))
8074 (setq s (concat (substring s 0 b)
8075 (substring s (or (next-single-property-change
8076 b 'invisible s) (length s)))))))
8077 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8078 (setq s (concat (substring s 0 b)
8079 (substring s (or (next-single-property-change
8080 b 'org-cwidth s) (length s))))))
8081 (setq l (string-width s) b -1)
8082 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8083 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8086 (defun org-table-begin (&optional table-type)
8087 "Find the beginning of the table and return its position.
8088 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8089 (save-excursion
8090 (if (not (re-search-backward
8091 (if table-type org-table-any-border-regexp
8092 org-table-border-regexp)
8093 nil t))
8094 (progn (goto-char (point-min)) (point))
8095 (goto-char (match-beginning 0))
8096 (beginning-of-line 2)
8097 (point))))
8099 (defun org-table-end (&optional table-type)
8100 "Find the end of the table and return its position.
8101 With argument TABLE-TYPE, go to the end of a table.el-type table."
8102 (save-excursion
8103 (if (not (re-search-forward
8104 (if table-type org-table-any-border-regexp
8105 org-table-border-regexp)
8106 nil t))
8107 (goto-char (point-max))
8108 (goto-char (match-beginning 0)))
8109 (point-marker)))
8111 (defun org-table-justify-field-maybe (&optional new)
8112 "Justify the current field, text to left, number to right.
8113 Optional argument NEW may specify text to replace the current field content."
8114 (cond
8115 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8116 ((org-at-table-hline-p))
8117 ((and (not new)
8118 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8119 (current-buffer)))
8120 (< (point) org-table-aligned-begin-marker)
8121 (>= (point) org-table-aligned-end-marker)))
8122 ;; This is not the same table, force a full re-align
8123 (setq org-table-may-need-update t))
8124 (t ;; realign the current field, based on previous full realign
8125 (let* ((pos (point)) s
8126 (col (org-table-current-column))
8127 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8128 l f n o e)
8129 (when (> col 0)
8130 (skip-chars-backward "^|\n")
8131 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8132 (progn
8133 (setq s (match-string 1)
8134 o (match-string 0)
8135 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8136 e (not (= (match-beginning 2) (match-end 2))))
8137 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8138 l (if e "|" (setq org-table-may-need-update t) ""))
8139 n (format f s))
8140 (if new
8141 (if (<= (length new) l) ;; FIXME: length -> str-width?
8142 (setq n (format f new))
8143 (setq n (concat new "|") org-table-may-need-update t)))
8144 (or (equal n o)
8145 (let (org-table-may-need-update)
8146 (replace-match n t t))))
8147 (setq org-table-may-need-update t))
8148 (goto-char pos))))))
8150 (defun org-table-next-field ()
8151 "Go to the next field in the current table, creating new lines as needed.
8152 Before doing so, re-align the table if necessary."
8153 (interactive)
8154 (org-table-maybe-eval-formula)
8155 (org-table-maybe-recalculate-line)
8156 (if (and org-table-automatic-realign
8157 org-table-may-need-update)
8158 (org-table-align))
8159 (let ((end (org-table-end)))
8160 (if (org-at-table-hline-p)
8161 (end-of-line 1))
8162 (condition-case nil
8163 (progn
8164 (re-search-forward "|" end)
8165 (if (looking-at "[ \t]*$")
8166 (re-search-forward "|" end))
8167 (if (and (looking-at "-")
8168 org-table-tab-jumps-over-hlines
8169 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8170 (goto-char (match-beginning 1)))
8171 (if (looking-at "-")
8172 (progn
8173 (beginning-of-line 0)
8174 (org-table-insert-row 'below))
8175 (if (looking-at " ") (forward-char 1))))
8176 (error
8177 (org-table-insert-row 'below)))))
8179 (defun org-table-previous-field ()
8180 "Go to the previous field in the table.
8181 Before doing so, re-align the table if necessary."
8182 (interactive)
8183 (org-table-justify-field-maybe)
8184 (org-table-maybe-recalculate-line)
8185 (if (and org-table-automatic-realign
8186 org-table-may-need-update)
8187 (org-table-align))
8188 (if (org-at-table-hline-p)
8189 (end-of-line 1))
8190 (re-search-backward "|" (org-table-begin))
8191 (re-search-backward "|" (org-table-begin))
8192 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8193 (re-search-backward "|" (org-table-begin)))
8194 (if (looking-at "| ?")
8195 (goto-char (match-end 0))))
8197 (defun org-table-next-row ()
8198 "Go to the next row (same column) in the current table.
8199 Before doing so, re-align the table if necessary."
8200 (interactive)
8201 (org-table-maybe-eval-formula)
8202 (org-table-maybe-recalculate-line)
8203 (if (or (looking-at "[ \t]*$")
8204 (save-excursion (skip-chars-backward " \t") (bolp)))
8205 (newline)
8206 (if (and org-table-automatic-realign
8207 org-table-may-need-update)
8208 (org-table-align))
8209 (let ((col (org-table-current-column)))
8210 (beginning-of-line 2)
8211 (if (or (not (org-at-table-p))
8212 (org-at-table-hline-p))
8213 (progn
8214 (beginning-of-line 0)
8215 (org-table-insert-row 'below)))
8216 (org-table-goto-column col)
8217 (skip-chars-backward "^|\n\r")
8218 (if (looking-at " ") (forward-char 1)))))
8220 (defun org-table-copy-down (n)
8221 "Copy a field down in the current column.
8222 If the field at the cursor is empty, copy into it the content of the nearest
8223 non-empty field above. With argument N, use the Nth non-empty field.
8224 If the current field is not empty, it is copied down to the next row, and
8225 the cursor is moved with it. Therefore, repeating this command causes the
8226 column to be filled row-by-row.
8227 If the variable `org-table-copy-increment' is non-nil and the field is an
8228 integer or a timestamp, it will be incremented while copying. In the case of
8229 a timestamp, if the cursor is on the year, change the year. If it is on the
8230 month or the day, change that. Point will stay on the current date field
8231 in order to easily repeat the interval."
8232 (interactive "p")
8233 (let* ((colpos (org-table-current-column))
8234 (col (current-column))
8235 (field (org-table-get-field))
8236 (non-empty (string-match "[^ \t]" field))
8237 (beg (org-table-begin))
8238 txt)
8239 (org-table-check-inside-data-field)
8240 (if non-empty
8241 (progn
8242 (setq txt (org-trim field))
8243 (org-table-next-row)
8244 (org-table-blank-field))
8245 (save-excursion
8246 (setq txt
8247 (catch 'exit
8248 (while (progn (beginning-of-line 1)
8249 (re-search-backward org-table-dataline-regexp
8250 beg t))
8251 (org-table-goto-column colpos t)
8252 (if (and (looking-at
8253 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8254 (= (setq n (1- n)) 0))
8255 (throw 'exit (match-string 1))))))))
8256 (if txt
8257 (progn
8258 (if (and org-table-copy-increment
8259 (string-match "^[0-9]+$" txt))
8260 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8261 (insert txt)
8262 (move-to-column col)
8263 (if (and org-table-copy-increment (org-at-timestamp-p t))
8264 (org-timestamp-up 1)
8265 (org-table-maybe-recalculate-line))
8266 (org-table-align)
8267 (move-to-column col))
8268 (error "No non-empty field found"))))
8270 (defun org-table-check-inside-data-field ()
8271 "Is point inside a table data field?
8272 I.e. not on a hline or before the first or after the last column?
8273 This actually throws an error, so it aborts the current command."
8274 (if (or (not (org-at-table-p))
8275 (= (org-table-current-column) 0)
8276 (org-at-table-hline-p)
8277 (looking-at "[ \t]*$"))
8278 (error "Not in table data field")))
8280 (defvar org-table-clip nil
8281 "Clipboard for table regions.")
8283 (defun org-table-blank-field ()
8284 "Blank the current table field or active region."
8285 (interactive)
8286 (org-table-check-inside-data-field)
8287 (if (and (interactive-p) (org-region-active-p))
8288 (let (org-table-clip)
8289 (org-table-cut-region (region-beginning) (region-end)))
8290 (skip-chars-backward "^|")
8291 (backward-char 1)
8292 (if (looking-at "|[^|\n]+")
8293 (let* ((pos (match-beginning 0))
8294 (match (match-string 0))
8295 (len (org-string-width match)))
8296 (replace-match (concat "|" (make-string (1- len) ?\ )))
8297 (goto-char (+ 2 pos))
8298 (substring match 1)))))
8300 (defun org-table-get-field (&optional n replace)
8301 "Return the value of the field in column N of current row.
8302 N defaults to current field.
8303 If REPLACE is a string, replace field with this value. The return value
8304 is always the old value."
8305 (and n (org-table-goto-column n))
8306 (skip-chars-backward "^|\n")
8307 (backward-char 1)
8308 (if (looking-at "|[^|\r\n]*")
8309 (let* ((pos (match-beginning 0))
8310 (val (buffer-substring (1+ pos) (match-end 0))))
8311 (if replace
8312 (replace-match (concat "|" replace) t t))
8313 (goto-char (min (point-at-eol) (+ 2 pos)))
8314 val)
8315 (forward-char 1) ""))
8317 (defun org-table-field-info (arg)
8318 "Show info about the current field, and highlight any reference at point."
8319 (interactive "P")
8320 (org-table-get-specials)
8321 (save-excursion
8322 (let* ((pos (point))
8323 (col (org-table-current-column))
8324 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8325 (name (car (rassoc (list (org-current-line) col)
8326 org-table-named-field-locations)))
8327 (eql (org-table-get-stored-formulas))
8328 (dline (org-table-current-dline))
8329 (ref (format "@%d$%d" dline col))
8330 (ref1 (org-table-convert-refs-to-an ref))
8331 (fequation (or (assoc name eql) (assoc ref eql)))
8332 (cequation (assoc (int-to-string col) eql))
8333 (eqn (or fequation cequation)))
8334 (goto-char pos)
8335 (condition-case nil
8336 (org-table-show-reference 'local)
8337 (error nil))
8338 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
8339 dline col
8340 (if cname (concat " or $" cname) "")
8341 dline col ref1
8342 (if name (concat " or $" name) "")
8343 ;; FIXME: formula info not correct if special table line
8344 (if eqn
8345 (concat ", formula: "
8346 (org-table-formula-to-user
8347 (concat
8348 (if (string-match "^[$@]"(car eqn)) "" "$")
8349 (car eqn) "=" (cdr eqn))))
8350 "")))))
8352 (defun org-table-current-column ()
8353 "Find out which column we are in.
8354 When called interactively, column is also displayed in echo area."
8355 (interactive)
8356 (if (interactive-p) (org-table-check-inside-data-field))
8357 (save-excursion
8358 (let ((cnt 0) (pos (point)))
8359 (beginning-of-line 1)
8360 (while (search-forward "|" pos t)
8361 (setq cnt (1+ cnt)))
8362 (if (interactive-p) (message "This is table column %d" cnt))
8363 cnt)))
8365 (defun org-table-current-dline ()
8366 "Find out what table data line we are in.
8367 Only datalins count for this."
8368 (interactive)
8369 (if (interactive-p) (org-table-check-inside-data-field))
8370 (save-excursion
8371 (let ((cnt 0) (pos (point)))
8372 (goto-char (org-table-begin))
8373 (while (<= (point) pos)
8374 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
8375 (beginning-of-line 2))
8376 (if (interactive-p) (message "This is table line %d" cnt))
8377 cnt)))
8379 (defun org-table-goto-column (n &optional on-delim force)
8380 "Move the cursor to the Nth column in the current table line.
8381 With optional argument ON-DELIM, stop with point before the left delimiter
8382 of the field.
8383 If there are less than N fields, just go to after the last delimiter.
8384 However, when FORCE is non-nil, create new columns if necessary."
8385 (interactive "p")
8386 (let ((pos (point-at-eol)))
8387 (beginning-of-line 1)
8388 (when (> n 0)
8389 (while (and (> (setq n (1- n)) -1)
8390 (or (search-forward "|" pos t)
8391 (and force
8392 (progn (end-of-line 1)
8393 (skip-chars-backward "^|")
8394 (insert " | "))))))
8395 ; (backward-char 2) t)))))
8396 (when (and force (not (looking-at ".*|")))
8397 (save-excursion (end-of-line 1) (insert " | ")))
8398 (if on-delim
8399 (backward-char 1)
8400 (if (looking-at " ") (forward-char 1))))))
8402 (defun org-at-table-p (&optional table-type)
8403 "Return t if the cursor is inside an org-type table.
8404 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8405 (if org-enable-table-editor
8406 (save-excursion
8407 (beginning-of-line 1)
8408 (looking-at (if table-type org-table-any-line-regexp
8409 org-table-line-regexp)))
8410 nil))
8412 (defun org-at-table.el-p ()
8413 "Return t if and only if we are at a table.el table."
8414 (and (org-at-table-p 'any)
8415 (save-excursion
8416 (goto-char (org-table-begin 'any))
8417 (looking-at org-table1-hline-regexp))))
8419 (defun org-table-recognize-table.el ()
8420 "If there is a table.el table nearby, recognize it and move into it."
8421 (if org-table-tab-recognizes-table.el
8422 (if (org-at-table.el-p)
8423 (progn
8424 (beginning-of-line 1)
8425 (if (looking-at org-table-dataline-regexp)
8427 (if (looking-at org-table1-hline-regexp)
8428 (progn
8429 (beginning-of-line 2)
8430 (if (looking-at org-table-any-border-regexp)
8431 (beginning-of-line -1)))))
8432 (if (re-search-forward "|" (org-table-end t) t)
8433 (progn
8434 (require 'table)
8435 (if (table--at-cell-p (point))
8437 (message "recognizing table.el table...")
8438 (table-recognize-table)
8439 (message "recognizing table.el table...done")))
8440 (error "This should not happen..."))
8442 nil)
8443 nil))
8445 (defun org-at-table-hline-p ()
8446 "Return t if the cursor is inside a hline in a table."
8447 (if org-enable-table-editor
8448 (save-excursion
8449 (beginning-of-line 1)
8450 (looking-at org-table-hline-regexp))
8451 nil))
8453 (defun org-table-insert-column ()
8454 "Insert a new column into the table."
8455 (interactive)
8456 (if (not (org-at-table-p))
8457 (error "Not at a table"))
8458 (org-table-find-dataline)
8459 (let* ((col (max 1 (org-table-current-column)))
8460 (beg (org-table-begin))
8461 (end (org-table-end))
8462 ;; Current cursor position
8463 (linepos (org-current-line))
8464 (colpos col))
8465 (goto-char beg)
8466 (while (< (point) end)
8467 (if (org-at-table-hline-p)
8469 (org-table-goto-column col t)
8470 (insert "| "))
8471 (beginning-of-line 2))
8472 (move-marker end nil)
8473 (goto-line linepos)
8474 (org-table-goto-column colpos)
8475 (org-table-align)
8476 (org-table-fix-formulas "$" nil (1- col) 1)))
8478 (defun org-table-find-dataline ()
8479 "Find a dataline in the current table, which is needed for column commands."
8480 (if (and (org-at-table-p)
8481 (not (org-at-table-hline-p)))
8483 (let ((col (current-column))
8484 (end (org-table-end)))
8485 (move-to-column col)
8486 (while (and (< (point) end)
8487 (or (not (= (current-column) col))
8488 (org-at-table-hline-p)))
8489 (beginning-of-line 2)
8490 (move-to-column col))
8491 (if (and (org-at-table-p)
8492 (not (org-at-table-hline-p)))
8494 (error
8495 "Please position cursor in a data line for column operations")))))
8497 (defun org-table-delete-column ()
8498 "Delete a column from the table."
8499 (interactive)
8500 (if (not (org-at-table-p))
8501 (error "Not at a table"))
8502 (org-table-find-dataline)
8503 (org-table-check-inside-data-field)
8504 (let* ((col (org-table-current-column))
8505 (beg (org-table-begin))
8506 (end (org-table-end))
8507 ;; Current cursor position
8508 (linepos (org-current-line))
8509 (colpos col))
8510 (goto-char beg)
8511 (while (< (point) end)
8512 (if (org-at-table-hline-p)
8514 (org-table-goto-column col t)
8515 (and (looking-at "|[^|\n]+|")
8516 (replace-match "|")))
8517 (beginning-of-line 2))
8518 (move-marker end nil)
8519 (goto-line linepos)
8520 (org-table-goto-column colpos)
8521 (org-table-align)
8522 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
8523 col -1 col)))
8525 (defun org-table-move-column-right ()
8526 "Move column to the right."
8527 (interactive)
8528 (org-table-move-column nil))
8529 (defun org-table-move-column-left ()
8530 "Move column to the left."
8531 (interactive)
8532 (org-table-move-column 'left))
8534 (defun org-table-move-column (&optional left)
8535 "Move the current column to the right. With arg LEFT, move to the left."
8536 (interactive "P")
8537 (if (not (org-at-table-p))
8538 (error "Not at a table"))
8539 (org-table-find-dataline)
8540 (org-table-check-inside-data-field)
8541 (let* ((col (org-table-current-column))
8542 (col1 (if left (1- col) col))
8543 (beg (org-table-begin))
8544 (end (org-table-end))
8545 ;; Current cursor position
8546 (linepos (org-current-line))
8547 (colpos (if left (1- col) (1+ col))))
8548 (if (and left (= col 1))
8549 (error "Cannot move column further left"))
8550 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8551 (error "Cannot move column further right"))
8552 (goto-char beg)
8553 (while (< (point) end)
8554 (if (org-at-table-hline-p)
8556 (org-table-goto-column col1 t)
8557 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8558 (replace-match "|\\2|\\1|")))
8559 (beginning-of-line 2))
8560 (move-marker end nil)
8561 (goto-line linepos)
8562 (org-table-goto-column colpos)
8563 (org-table-align)
8564 (org-table-fix-formulas
8565 "$" (list (cons (number-to-string col) (number-to-string colpos))
8566 (cons (number-to-string colpos) (number-to-string col))))))
8568 (defun org-table-move-row-down ()
8569 "Move table row down."
8570 (interactive)
8571 (org-table-move-row nil))
8572 (defun org-table-move-row-up ()
8573 "Move table row up."
8574 (interactive)
8575 (org-table-move-row 'up))
8577 (defun org-table-move-row (&optional up)
8578 "Move the current table line down. With arg UP, move it up."
8579 (interactive "P")
8580 (let* ((col (current-column))
8581 (pos (point))
8582 (hline1p (save-excursion (beginning-of-line 1)
8583 (looking-at org-table-hline-regexp)))
8584 (dline1 (org-table-current-dline))
8585 (dline2 (+ dline1 (if up -1 1)))
8586 (tonew (if up 0 2))
8587 txt hline2p)
8588 (beginning-of-line tonew)
8589 (unless (org-at-table-p)
8590 (goto-char pos)
8591 (error "Cannot move row further"))
8592 (setq hline2p (looking-at org-table-hline-regexp))
8593 (goto-char pos)
8594 (beginning-of-line 1)
8595 (setq pos (point))
8596 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8597 (delete-region (point) (1+ (point-at-eol)))
8598 (beginning-of-line tonew)
8599 (insert txt)
8600 (beginning-of-line 0)
8601 (move-to-column col)
8602 (unless (or hline1p hline2p)
8603 (org-table-fix-formulas
8604 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
8605 (cons (number-to-string dline2) (number-to-string dline1)))))))
8607 (defun org-table-insert-row (&optional arg)
8608 "Insert a new row above the current line into the table.
8609 With prefix ARG, insert below the current line."
8610 (interactive "P")
8611 (if (not (org-at-table-p))
8612 (error "Not at a table"))
8613 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
8614 (new (org-table-clean-line line)))
8615 ;; Fix the first field if necessary
8616 (if (string-match "^[ \t]*| *[#$] *|" line)
8617 (setq new (replace-match (match-string 0 line) t t new)))
8618 (beginning-of-line (if arg 2 1))
8619 (let (org-table-may-need-update) (insert-before-markers new "\n"))
8620 (beginning-of-line 0)
8621 (re-search-forward "| ?" (point-at-eol) t)
8622 (and (or org-table-may-need-update org-table-overlay-coordinates)
8623 (org-table-align))
8624 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
8626 (defun org-table-insert-hline (&optional above)
8627 "Insert a horizontal-line below the current line into the table.
8628 With prefix ABOVE, insert above the current line."
8629 (interactive "P")
8630 (if (not (org-at-table-p))
8631 (error "Not at a table"))
8632 (let ((line (org-table-clean-line
8633 (buffer-substring (point-at-bol) (point-at-eol))))
8634 (col (current-column)))
8635 (while (string-match "|\\( +\\)|" line)
8636 (setq line (replace-match
8637 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
8638 ?-) "|") t t line)))
8639 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
8640 (beginning-of-line (if above 1 2))
8641 (insert line "\n")
8642 (beginning-of-line (if above 1 -1))
8643 (move-to-column col)
8644 (and org-table-overlay-coordinates (org-table-align))))
8646 (defun org-table-hline-and-move (&optional same-column)
8647 "Insert a hline and move to the row below that line."
8648 (interactive "P")
8649 (let ((col (org-table-current-column)))
8650 (org-table-maybe-eval-formula)
8651 (org-table-maybe-recalculate-line)
8652 (org-table-insert-hline)
8653 (end-of-line 2)
8654 (if (looking-at "\n[ \t]*|-")
8655 (progn (insert "\n|") (org-table-align))
8656 (org-table-next-field))
8657 (if same-column (org-table-goto-column col))))
8659 (defun org-table-clean-line (s)
8660 "Convert a table line S into a string with only \"|\" and space.
8661 In particular, this does handle wide and invisible characters."
8662 (if (string-match "^[ \t]*|-" s)
8663 ;; It's a hline, just map the characters
8664 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
8665 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
8666 (setq s (replace-match
8667 (concat "|" (make-string (org-string-width (match-string 1 s))
8668 ?\ ) "|")
8669 t t s)))
8672 (defun org-table-kill-row ()
8673 "Delete the current row or horizontal line from the table."
8674 (interactive)
8675 (if (not (org-at-table-p))
8676 (error "Not at a table"))
8677 (let ((col (current-column))
8678 (dline (org-table-current-dline)))
8679 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8680 (if (not (org-at-table-p)) (beginning-of-line 0))
8681 (move-to-column col)
8682 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
8683 dline -1 dline)))
8685 (defun org-table-sort-lines (with-case &optional sorting-type)
8686 "Sort table lines according to the column at point.
8688 The position of point indicates the column to be used for
8689 sorting, and the range of lines is the range between the nearest
8690 horizontal separator lines, or the entire table of no such lines
8691 exist. If point is before the first column, you will be prompted
8692 for the sorting column. If there is an active region, the mark
8693 specifies the first line and the sorting column, while point
8694 should be in the last line to be included into the sorting.
8696 The command then prompts for the sorting type which can be
8697 alphabetically, numerically, or by time (as given in a time stamp
8698 in the field). Sorting in reverse order is also possible.
8700 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
8702 If SORTING-TYPE is specified when this function is called from a Lisp
8703 program, no prompting will take place. SORTING-TYPE must be a character,
8704 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
8705 should be done in reverse order."
8706 (interactive "P")
8707 (let* ((thisline (org-current-line))
8708 (thiscol (org-table-current-column))
8709 beg end bcol ecol tend tbeg column lns pos)
8710 (when (equal thiscol 0)
8711 (if (interactive-p)
8712 (setq thiscol
8713 (string-to-number
8714 (read-string "Use column N for sorting: ")))
8715 (setq thiscol 1))
8716 (org-table-goto-column thiscol))
8717 (org-table-check-inside-data-field)
8718 (if (org-region-active-p)
8719 (progn
8720 (setq beg (region-beginning) end (region-end))
8721 (goto-char beg)
8722 (setq column (org-table-current-column)
8723 beg (point-at-bol))
8724 (goto-char end)
8725 (setq end (point-at-bol 2)))
8726 (setq column (org-table-current-column)
8727 pos (point)
8728 tbeg (org-table-begin)
8729 tend (org-table-end))
8730 (if (re-search-backward org-table-hline-regexp tbeg t)
8731 (setq beg (point-at-bol 2))
8732 (goto-char tbeg)
8733 (setq beg (point-at-bol 1)))
8734 (goto-char pos)
8735 (if (re-search-forward org-table-hline-regexp tend t)
8736 (setq end (point-at-bol 1))
8737 (goto-char tend)
8738 (setq end (point-at-bol))))
8739 (setq beg (move-marker (make-marker) beg)
8740 end (move-marker (make-marker) end))
8741 (untabify beg end)
8742 (goto-char beg)
8743 (org-table-goto-column column)
8744 (skip-chars-backward "^|")
8745 (setq bcol (current-column))
8746 (org-table-goto-column (1+ column))
8747 (skip-chars-backward "^|")
8748 (setq ecol (1- (current-column)))
8749 (org-table-goto-column column)
8750 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8751 (org-split-string (buffer-substring beg end) "\n")))
8752 (setq lns (org-do-sort lns "Table" with-case sorting-type))
8753 (delete-region beg end)
8754 (move-marker beg nil)
8755 (move-marker end nil)
8756 (insert (mapconcat 'cdr lns "\n") "\n")
8757 (goto-line thisline)
8758 (org-table-goto-column thiscol)
8759 (message "%d lines sorted, based on column %d" (length lns) column)))
8761 (defun org-table-cut-region (beg end)
8762 "Copy region in table to the clipboard and blank all relevant fields."
8763 (interactive "r")
8764 (org-table-copy-region beg end 'cut))
8766 (defun org-table-copy-region (beg end &optional cut)
8767 "Copy rectangular region in table to clipboard.
8768 A special clipboard is used which can only be accessed
8769 with `org-table-paste-rectangle'."
8770 (interactive "rP")
8771 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8772 region cols
8773 (rpl (if cut " " nil)))
8774 (goto-char beg)
8775 (org-table-check-inside-data-field)
8776 (setq l01 (org-current-line)
8777 c01 (org-table-current-column))
8778 (goto-char end)
8779 (org-table-check-inside-data-field)
8780 (setq l02 (org-current-line)
8781 c02 (org-table-current-column))
8782 (setq l1 (min l01 l02) l2 (max l01 l02)
8783 c1 (min c01 c02) c2 (max c01 c02))
8784 (catch 'exit
8785 (while t
8786 (catch 'nextline
8787 (if (> l1 l2) (throw 'exit t))
8788 (goto-line l1)
8789 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8790 (setq cols nil ic1 c1 ic2 c2)
8791 (while (< ic1 (1+ ic2))
8792 (push (org-table-get-field ic1 rpl) cols)
8793 (setq ic1 (1+ ic1)))
8794 (push (nreverse cols) region)
8795 (setq l1 (1+ l1)))))
8796 (setq org-table-clip (nreverse region))
8797 (if cut (org-table-align))
8798 org-table-clip))
8800 (defun org-table-paste-rectangle ()
8801 "Paste a rectangular region into a table.
8802 The upper right corner ends up in the current field. All involved fields
8803 will be overwritten. If the rectangle does not fit into the present table,
8804 the table is enlarged as needed. The process ignores horizontal separator
8805 lines."
8806 (interactive)
8807 (unless (and org-table-clip (listp org-table-clip))
8808 (error "First cut/copy a region to paste!"))
8809 (org-table-check-inside-data-field)
8810 (let* ((clip org-table-clip)
8811 (line (org-current-line))
8812 (col (org-table-current-column))
8813 (org-enable-table-editor t)
8814 (org-table-automatic-realign nil)
8815 c cols field)
8816 (while (setq cols (pop clip))
8817 (while (org-at-table-hline-p) (beginning-of-line 2))
8818 (if (not (org-at-table-p))
8819 (progn (end-of-line 0) (org-table-next-field)))
8820 (setq c col)
8821 (while (setq field (pop cols))
8822 (org-table-goto-column c nil 'force)
8823 (org-table-get-field nil field)
8824 (setq c (1+ c)))
8825 (beginning-of-line 2))
8826 (goto-line line)
8827 (org-table-goto-column col)
8828 (org-table-align)))
8830 (defun org-table-convert ()
8831 "Convert from `org-mode' table to table.el and back.
8832 Obviously, this only works within limits. When an Org-mode table is
8833 converted to table.el, all horizontal separator lines get lost, because
8834 table.el uses these as cell boundaries and has no notion of horizontal lines.
8835 A table.el table can be converted to an Org-mode table only if it does not
8836 do row or column spanning. Multiline cells will become multiple cells.
8837 Beware, Org-mode does not test if the table can be successfully converted - it
8838 blindly applies a recipe that works for simple tables."
8839 (interactive)
8840 (require 'table)
8841 (if (org-at-table.el-p)
8842 ;; convert to Org-mode table
8843 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8844 (end (move-marker (make-marker) (org-table-end t))))
8845 (table-unrecognize-region beg end)
8846 (goto-char beg)
8847 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8848 (replace-match ""))
8849 (goto-char beg))
8850 (if (org-at-table-p)
8851 ;; convert to table.el table
8852 (let ((beg (move-marker (make-marker) (org-table-begin)))
8853 (end (move-marker (make-marker) (org-table-end))))
8854 ;; first, get rid of all horizontal lines
8855 (goto-char beg)
8856 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8857 (replace-match ""))
8858 ;; insert a hline before first
8859 (goto-char beg)
8860 (org-table-insert-hline 'above)
8861 (beginning-of-line -1)
8862 ;; insert a hline after each line
8863 (while (progn (beginning-of-line 3) (< (point) end))
8864 (org-table-insert-hline))
8865 (goto-char beg)
8866 (setq end (move-marker end (org-table-end)))
8867 ;; replace "+" at beginning and ending of hlines
8868 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8869 (replace-match "\\1+-"))
8870 (goto-char beg)
8871 (while (re-search-forward "-|[ \t]*$" end t)
8872 (replace-match "-+"))
8873 (goto-char beg)))))
8875 (defun org-table-wrap-region (arg)
8876 "Wrap several fields in a column like a paragraph.
8877 This is useful if you'd like to spread the contents of a field over several
8878 lines, in order to keep the table compact.
8880 If there is an active region, and both point and mark are in the same column,
8881 the text in the column is wrapped to minimum width for the given number of
8882 lines. Generally, this makes the table more compact. A prefix ARG may be
8883 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8884 formats the selected text to two lines. If the region was longer than two
8885 lines, the remaining lines remain empty. A negative prefix argument reduces
8886 the current number of lines by that amount. The wrapped text is pasted back
8887 into the table. If you formatted it to more lines than it was before, fields
8888 further down in the table get overwritten - so you might need to make space in
8889 the table first.
8891 If there is no region, the current field is split at the cursor position and
8892 the text fragment to the right of the cursor is prepended to the field one
8893 line down.
8895 If there is no region, but you specify a prefix ARG, the current field gets
8896 blank, and the content is appended to the field above."
8897 (interactive "P")
8898 (org-table-check-inside-data-field)
8899 (if (org-region-active-p)
8900 ;; There is a region: fill as a paragraph
8901 (let* ((beg (region-beginning))
8902 (cline (save-excursion (goto-char beg) (org-current-line)))
8903 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
8904 nlines)
8905 (org-table-cut-region (region-beginning) (region-end))
8906 (if (> (length (car org-table-clip)) 1)
8907 (error "Region must be limited to single column"))
8908 (setq nlines (if arg
8909 (if (< arg 1)
8910 (+ (length org-table-clip) arg)
8911 arg)
8912 (length org-table-clip)))
8913 (setq org-table-clip
8914 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8915 nil nlines)))
8916 (goto-line cline)
8917 (org-table-goto-column ccol)
8918 (org-table-paste-rectangle))
8919 ;; No region, split the current field at point
8920 (if arg
8921 ;; combine with field above
8922 (let ((s (org-table-blank-field))
8923 (col (org-table-current-column)))
8924 (beginning-of-line 0)
8925 (while (org-at-table-hline-p) (beginning-of-line 0))
8926 (org-table-goto-column col)
8927 (skip-chars-forward "^|")
8928 (skip-chars-backward " ")
8929 (insert " " (org-trim s))
8930 (org-table-align))
8931 ;; split field
8932 (when (looking-at "\\([^|]+\\)+|")
8933 (let ((s (match-string 1)))
8934 (replace-match " |")
8935 (goto-char (match-beginning 0))
8936 (org-table-next-row)
8937 (insert (org-trim s) " ")
8938 (org-table-align))))))
8940 (defvar org-field-marker nil)
8942 (defun org-table-edit-field (arg)
8943 "Edit table field in a different window.
8944 This is mainly useful for fields that contain hidden parts.
8945 When called with a \\[universal-argument] prefix, just make the full field visible so that
8946 it can be edited in place."
8947 (interactive "P")
8948 (if arg
8949 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
8950 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
8951 (remove-text-properties b e '(org-cwidth t invisible t
8952 display t intangible t))
8953 (if (and (boundp 'font-lock-mode) font-lock-mode)
8954 (font-lock-fontify-block)))
8955 (let ((pos (move-marker (make-marker) (point)))
8956 (field (org-table-get-field))
8957 (cw (current-window-configuration))
8959 (org-switch-to-buffer-other-window "*Org tmp*")
8960 (erase-buffer)
8961 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
8962 (let ((org-inhibit-startup t)) (org-mode))
8963 (goto-char (setq p (point-max)))
8964 (insert (org-trim field))
8965 (remove-text-properties p (point-max)
8966 '(invisible t org-cwidth t display t
8967 intangible t))
8968 (goto-char p)
8969 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
8970 (org-set-local 'org-window-configuration cw)
8971 (org-set-local 'org-field-marker pos)
8972 (message "Edit and finish with C-c C-c"))))
8974 (defun org-table-finish-edit-field ()
8975 "Finish editing a table data field.
8976 Remove all newline characters, insert the result into the table, realign
8977 the table and kill the editing buffer."
8978 (let ((pos org-field-marker)
8979 (cw org-window-configuration)
8980 (cb (current-buffer))
8981 text)
8982 (goto-char (point-min))
8983 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
8984 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
8985 (replace-match " "))
8986 (setq text (org-trim (buffer-string)))
8987 (set-window-configuration cw)
8988 (kill-buffer cb)
8989 (select-window (get-buffer-window (marker-buffer pos)))
8990 (goto-char pos)
8991 (move-marker pos nil)
8992 (org-table-check-inside-data-field)
8993 (org-table-get-field nil text)
8994 (org-table-align)
8995 (message "New field value inserted")))
8997 (defun org-trim (s)
8998 "Remove whitespace at beginning and end of string."
8999 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9000 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9003 (defun org-wrap (string &optional width lines)
9004 "Wrap string to either a number of lines, or a width in characters.
9005 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9006 that costs. If there is a word longer than WIDTH, the text is actually
9007 wrapped to the length of that word.
9008 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9009 many lines, whatever width that takes.
9010 The return value is a list of lines, without newlines at the end."
9011 (let* ((words (org-split-string string "[ \t\n]+"))
9012 (maxword (apply 'max (mapcar 'org-string-width words)))
9013 w ll)
9014 (cond (width
9015 (org-do-wrap words (max maxword width)))
9016 (lines
9017 (setq w maxword)
9018 (setq ll (org-do-wrap words maxword))
9019 (if (<= (length ll) lines)
9021 (setq ll words)
9022 (while (> (length ll) lines)
9023 (setq w (1+ w))
9024 (setq ll (org-do-wrap words w)))
9025 ll))
9026 (t (error "Cannot wrap this")))))
9029 (defun org-do-wrap (words width)
9030 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9031 (let (lines line)
9032 (while words
9033 (setq line (pop words))
9034 (while (and words (< (+ (length line) (length (car words))) width))
9035 (setq line (concat line " " (pop words))))
9036 (setq lines (push line lines)))
9037 (nreverse lines)))
9039 (defun org-split-string (string &optional separators)
9040 "Splits STRING into substrings at SEPARATORS.
9041 No empty strings are returned if there are matches at the beginning
9042 and end of string."
9043 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9044 (start 0)
9045 notfirst
9046 (list nil))
9047 (while (and (string-match rexp string
9048 (if (and notfirst
9049 (= start (match-beginning 0))
9050 (< start (length string)))
9051 (1+ start) start))
9052 (< (match-beginning 0) (length string)))
9053 (setq notfirst t)
9054 (or (eq (match-beginning 0) 0)
9055 (and (eq (match-beginning 0) (match-end 0))
9056 (eq (match-beginning 0) start))
9057 (setq list
9058 (cons (substring string start (match-beginning 0))
9059 list)))
9060 (setq start (match-end 0)))
9061 (or (eq start (length string))
9062 (setq list
9063 (cons (substring string start)
9064 list)))
9065 (nreverse list)))
9067 (defun org-table-map-tables (function)
9068 "Apply FUNCTION to the start of all tables in the buffer."
9069 (save-excursion
9070 (save-restriction
9071 (widen)
9072 (goto-char (point-min))
9073 (while (re-search-forward org-table-any-line-regexp nil t)
9074 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9075 (beginning-of-line 1)
9076 (if (looking-at org-table-line-regexp)
9077 (save-excursion (funcall function)))
9078 (re-search-forward org-table-any-border-regexp nil 1))))
9079 (message "Mapping tables: done"))
9081 (defvar org-timecnt) ; dynamically scoped parameter
9083 (defun org-table-sum (&optional beg end nlast)
9084 "Sum numbers in region of current table column.
9085 The result will be displayed in the echo area, and will be available
9086 as kill to be inserted with \\[yank].
9088 If there is an active region, it is interpreted as a rectangle and all
9089 numbers in that rectangle will be summed. If there is no active
9090 region and point is located in a table column, sum all numbers in that
9091 column.
9093 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9094 numbers are assumed to be times as well (in decimal hours) and the
9095 numbers are added as such.
9097 If NLAST is a number, only the NLAST fields will actually be summed."
9098 (interactive)
9099 (save-excursion
9100 (let (col (org-timecnt 0) diff h m s org-table-clip)
9101 (cond
9102 ((and beg end)) ; beg and end given explicitly
9103 ((org-region-active-p)
9104 (setq beg (region-beginning) end (region-end)))
9106 (setq col (org-table-current-column))
9107 (goto-char (org-table-begin))
9108 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9109 (error "No table data"))
9110 (org-table-goto-column col)
9111 (setq beg (point))
9112 (goto-char (org-table-end))
9113 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9114 (error "No table data"))
9115 (org-table-goto-column col)
9116 (setq end (point))))
9117 (let* ((items (apply 'append (org-table-copy-region beg end)))
9118 (items1 (cond ((not nlast) items)
9119 ((>= nlast (length items)) items)
9120 (t (setq items (reverse items))
9121 (setcdr (nthcdr (1- nlast) items) nil)
9122 (nreverse items))))
9123 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9124 items1)))
9125 (res (apply '+ numbers))
9126 (sres (if (= org-timecnt 0)
9127 (format "%g" res)
9128 (setq diff (* 3600 res)
9129 h (floor (/ diff 3600)) diff (mod diff 3600)
9130 m (floor (/ diff 60)) diff (mod diff 60)
9131 s diff)
9132 (format "%d:%02d:%02d" h m s))))
9133 (kill-new sres)
9134 (if (interactive-p)
9135 (message "%s"
9136 (substitute-command-keys
9137 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9138 (length numbers) sres))))
9139 sres))))
9141 (defun org-table-get-number-for-summing (s)
9142 (let (n)
9143 (if (string-match "^ *|? *" s)
9144 (setq s (replace-match "" nil nil s)))
9145 (if (string-match " *|? *$" s)
9146 (setq s (replace-match "" nil nil s)))
9147 (setq n (string-to-number s))
9148 (cond
9149 ((and (string-match "0" s)
9150 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9151 ((string-match "\\`[ \t]+\\'" s) nil)
9152 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9153 (let ((h (string-to-number (or (match-string 1 s) "0")))
9154 (m (string-to-number (or (match-string 2 s) "0")))
9155 (s (string-to-number (or (match-string 4 s) "0"))))
9156 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9157 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9158 ((equal n 0) nil)
9159 (t n))))
9161 (defun org-table-current-field-formula (&optional key noerror)
9162 "Return the formula active for the current field.
9163 Assumes that specials are in place.
9164 If KEY is given, return the key to this formula.
9165 Otherwise return the formula preceeded with \"=\" or \":=\"."
9166 (let* ((name (car (rassoc (list (org-current-line)
9167 (org-table-current-column))
9168 org-table-named-field-locations)))
9169 (col (org-table-current-column))
9170 (scol (int-to-string col))
9171 (ref (format "@%d$%d" (org-table-current-dline) col))
9172 (stored-list (org-table-get-stored-formulas noerror))
9173 (ass (or (assoc name stored-list)
9174 (assoc ref stored-list)
9175 (assoc scol stored-list))))
9176 (if key
9177 (car ass)
9178 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9179 (cdr ass))))))
9181 (defun org-table-get-formula (&optional equation named)
9182 "Read a formula from the minibuffer, offer stored formula as default.
9183 When NAMED is non-nil, look for a named equation."
9184 (let* ((stored-list (org-table-get-stored-formulas))
9185 (name (car (rassoc (list (org-current-line)
9186 (org-table-current-column))
9187 org-table-named-field-locations)))
9188 (ref (format "@%d$%d" (org-table-current-dline)
9189 (org-table-current-column)))
9190 (refass (assoc ref stored-list))
9191 (scol (if named
9192 (if name name ref)
9193 (int-to-string (org-table-current-column))))
9194 (dummy (and (or name refass) (not named)
9195 (not (y-or-n-p "Replace field formula with column formula? " ))
9196 (error "Abort")))
9197 (name (or name ref))
9198 (org-table-may-need-update nil)
9199 (stored (cdr (assoc scol stored-list)))
9200 (eq (cond
9201 ((and stored equation (string-match "^ *=? *$" equation))
9202 stored)
9203 ((stringp equation)
9204 equation)
9205 (t (org-table-formula-from-user
9206 (read-string
9207 (org-table-formula-to-user
9208 (format "%s formula %s%s="
9209 (if named "Field" "Column")
9210 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9211 scol))
9212 (if stored (org-table-formula-to-user stored) "")
9213 'org-table-formula-history
9214 )))))
9215 mustsave)
9216 (when (not (string-match "\\S-" eq))
9217 ;; remove formula
9218 (setq stored-list (delq (assoc scol stored-list) stored-list))
9219 (org-table-store-formulas stored-list)
9220 (error "Formula removed"))
9221 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9222 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9223 (if (and name (not named))
9224 ;; We set the column equation, delete the named one.
9225 (setq stored-list (delq (assoc name stored-list) stored-list)
9226 mustsave t))
9227 (if stored
9228 (setcdr (assoc scol stored-list) eq)
9229 (setq stored-list (cons (cons scol eq) stored-list)))
9230 (if (or mustsave (not (equal stored eq)))
9231 (org-table-store-formulas stored-list))
9232 eq))
9234 (defun org-table-store-formulas (alist)
9235 "Store the list of formulas below the current table."
9236 (setq alist (sort alist 'org-table-formula-less-p))
9237 (save-excursion
9238 (goto-char (org-table-end))
9239 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9240 (progn
9241 ;; don't overwrite TBLFM, we might use text properties to store stuff
9242 (goto-char (match-beginning 2))
9243 (delete-region (match-beginning 2) (match-end 0)))
9244 (insert "#+TBLFM:"))
9245 (insert " "
9246 (mapconcat (lambda (x)
9247 (concat
9248 (if (equal (string-to-char (car x)) ?@) "" "$")
9249 (car x) "=" (cdr x)))
9250 alist "::")
9251 "\n")))
9253 (defsubst org-table-formula-make-cmp-string (a)
9254 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9255 (concat
9256 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9257 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9258 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9260 (defun org-table-formula-less-p (a b)
9261 "Compare two formulas for sorting."
9262 (let ((as (org-table-formula-make-cmp-string (car a)))
9263 (bs (org-table-formula-make-cmp-string (car b))))
9264 (and as bs (string< as bs))))
9266 (defun org-table-get-stored-formulas (&optional noerror)
9267 "Return an alist with the stored formulas directly after current table."
9268 (interactive)
9269 (let (scol eq eq-alist strings string seen)
9270 (save-excursion
9271 (goto-char (org-table-end))
9272 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9273 (setq strings (org-split-string (match-string 2) " *:: *"))
9274 (while (setq string (pop strings))
9275 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9276 (setq scol (if (match-end 2)
9277 (match-string 2 string)
9278 (match-string 1 string))
9279 eq (match-string 3 string)
9280 eq-alist (cons (cons scol eq) eq-alist))
9281 (if (member scol seen)
9282 (if noerror
9283 (progn
9284 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9285 (ding)
9286 (sit-for 2))
9287 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9288 (push scol seen))))))
9289 (nreverse eq-alist)))
9291 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9292 "Modify the equations after the table structure has been edited.
9293 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9294 For all numbers larger than LIMIT, shift them by DELTA."
9295 (save-excursion
9296 (goto-char (org-table-end))
9297 (when (looking-at "#\\+TBLFM:")
9298 (let ((re (concat key "\\([0-9]+\\)"))
9299 (re2
9300 (when remove
9301 (if (equal key "$")
9302 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9303 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9304 s n a)
9305 (when remove
9306 (while (re-search-forward re2 (point-at-eol) t)
9307 (replace-match "")))
9308 (while (re-search-forward re (point-at-eol) t)
9309 (setq s (match-string 1) n (string-to-number s))
9310 (cond
9311 ((setq a (assoc s replace))
9312 (replace-match (concat key (cdr a)) t t))
9313 ((and limit (> n limit))
9314 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
9316 (defun org-table-get-specials ()
9317 "Get the column names and local parameters for this table."
9318 (save-excursion
9319 (let ((beg (org-table-begin)) (end (org-table-end))
9320 names name fields fields1 field cnt
9321 c v l line col types dlines hlines)
9322 (setq org-table-column-names nil
9323 org-table-local-parameters nil
9324 org-table-named-field-locations nil
9325 org-table-current-begin-line nil
9326 org-table-current-begin-pos nil
9327 org-table-current-line-types nil)
9328 (goto-char beg)
9329 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9330 (setq names (org-split-string (match-string 1) " *| *")
9331 cnt 1)
9332 (while (setq name (pop names))
9333 (setq cnt (1+ cnt))
9334 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9335 (push (cons name (int-to-string cnt)) org-table-column-names))))
9336 (setq org-table-column-names (nreverse org-table-column-names))
9337 (setq org-table-column-name-regexp
9338 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9339 (goto-char beg)
9340 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9341 (setq fields (org-split-string (match-string 1) " *| *"))
9342 (while (setq field (pop fields))
9343 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9344 (push (cons (match-string 1 field) (match-string 2 field))
9345 org-table-local-parameters))))
9346 (goto-char beg)
9347 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9348 (setq c (match-string 1)
9349 fields (org-split-string (match-string 2) " *| *"))
9350 (save-excursion
9351 (beginning-of-line (if (equal c "_") 2 0))
9352 (setq line (org-current-line) col 1)
9353 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9354 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9355 (while (and fields1 (setq field (pop fields)))
9356 (setq v (pop fields1) col (1+ col))
9357 (when (and (stringp field) (stringp v)
9358 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9359 (push (cons field v) org-table-local-parameters)
9360 (push (list field line col) org-table-named-field-locations))))
9361 ;; Analyse the line types
9362 (goto-char beg)
9363 (setq org-table-current-begin-line (org-current-line)
9364 org-table-current-begin-pos (point)
9365 l org-table-current-begin-line)
9366 (while (looking-at "[ \t]*|\\(-\\)?")
9367 (push (if (match-end 1) 'hline 'dline) types)
9368 (if (match-end 1) (push l hlines) (push l dlines))
9369 (beginning-of-line 2)
9370 (setq l (1+ l)))
9371 (setq org-table-current-line-types (apply 'vector (nreverse types))
9372 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
9373 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
9375 (defun org-table-maybe-eval-formula ()
9376 "Check if the current field starts with \"=\" or \":=\".
9377 If yes, store the formula and apply it."
9378 ;; We already know we are in a table. Get field will only return a formula
9379 ;; when appropriate. It might return a separator line, but no problem.
9380 (when org-table-formula-evaluate-inline
9381 (let* ((field (org-trim (or (org-table-get-field) "")))
9382 named eq)
9383 (when (string-match "^:?=\\(.*\\)" field)
9384 (setq named (equal (string-to-char field) ?:)
9385 eq (match-string 1 field))
9386 (if (or (fboundp 'calc-eval)
9387 (equal (substring eq 0 (min 2 (length eq))) "'("))
9388 (org-table-eval-formula (if named '(4) nil)
9389 (org-table-formula-from-user eq))
9390 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
9392 (defvar org-recalc-commands nil
9393 "List of commands triggering the recalculation of a line.
9394 Will be filled automatically during use.")
9396 (defvar org-recalc-marks
9397 '((" " . "Unmarked: no special line, no automatic recalculation")
9398 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9399 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9400 ("!" . "Column name definition line. Reference in formula as $name.")
9401 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9402 ("_" . "Names for values in row below this one.")
9403 ("^" . "Names for values in row above this one.")))
9405 (defun org-table-rotate-recalc-marks (&optional newchar)
9406 "Rotate the recalculation mark in the first column.
9407 If in any row, the first field is not consistent with a mark,
9408 insert a new column for the markers.
9409 When there is an active region, change all the lines in the region,
9410 after prompting for the marking character.
9411 After each change, a message will be displayed indicating the meaning
9412 of the new mark."
9413 (interactive)
9414 (unless (org-at-table-p) (error "Not at a table"))
9415 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9416 (beg (org-table-begin))
9417 (end (org-table-end))
9418 (l (org-current-line))
9419 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9420 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9421 (have-col
9422 (save-excursion
9423 (goto-char beg)
9424 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9425 (col (org-table-current-column))
9426 (forcenew (car (assoc newchar org-recalc-marks)))
9427 epos new)
9428 (when l1
9429 (message "Change region to what mark? Type # * ! $ or SPC: ")
9430 (setq newchar (char-to-string (read-char-exclusive))
9431 forcenew (car (assoc newchar org-recalc-marks))))
9432 (if (and newchar (not forcenew))
9433 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9434 newchar))
9435 (if l1 (goto-line l1))
9436 (save-excursion
9437 (beginning-of-line 1)
9438 (unless (looking-at org-table-dataline-regexp)
9439 (error "Not at a table data line")))
9440 (unless have-col
9441 (org-table-goto-column 1)
9442 (org-table-insert-column)
9443 (org-table-goto-column (1+ col)))
9444 (setq epos (point-at-eol))
9445 (save-excursion
9446 (beginning-of-line 1)
9447 (org-table-get-field
9448 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9449 (concat " "
9450 (setq new (or forcenew
9451 (cadr (member (match-string 1) marks))))
9452 " ")
9453 " # ")))
9454 (if (and l1 l2)
9455 (progn
9456 (goto-line l1)
9457 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9458 (and (looking-at org-table-dataline-regexp)
9459 (org-table-get-field 1 (concat " " new " "))))
9460 (goto-line l1)))
9461 (if (not (= epos (point-at-eol))) (org-table-align))
9462 (goto-line l)
9463 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9465 (defun org-table-maybe-recalculate-line ()
9466 "Recompute the current line if marked for it, and if we haven't just done it."
9467 (interactive)
9468 (and org-table-allow-automatic-line-recalculation
9469 (not (and (memq last-command org-recalc-commands)
9470 (equal org-last-recalc-line (org-current-line))))
9471 (save-excursion (beginning-of-line 1)
9472 (looking-at org-table-auto-recalculate-regexp))
9473 (org-table-recalculate) t))
9475 (defvar org-table-formula-debug nil
9476 "Non-nil means, debug table formulas.
9477 When nil, simply write \"#ERROR\" in corrupted fields.")
9478 (make-variable-buffer-local 'org-table-formula-debug)
9480 (defvar modes)
9481 (defsubst org-set-calc-mode (var &optional value)
9482 (if (stringp var)
9483 (setq var (assoc var '(("D" calc-angle-mode deg)
9484 ("R" calc-angle-mode rad)
9485 ("F" calc-prefer-frac t)
9486 ("S" calc-symbolic-mode t)))
9487 value (nth 2 var) var (nth 1 var)))
9488 (if (memq var modes)
9489 (setcar (cdr (memq var modes)) value)
9490 (cons var (cons value modes)))
9491 modes)
9493 (defun org-table-eval-formula (&optional arg equation
9494 suppress-align suppress-const
9495 suppress-store suppress-analysis)
9496 "Replace the table field value at the cursor by the result of a calculation.
9498 This function makes use of Dave Gillespie's Calc package, in my view the
9499 most exciting program ever written for GNU Emacs. So you need to have Calc
9500 installed in order to use this function.
9502 In a table, this command replaces the value in the current field with the
9503 result of a formula. It also installs the formula as the \"current\" column
9504 formula, by storing it in a special line below the table. When called
9505 with a `C-u' prefix, the current field must ba a named field, and the
9506 formula is installed as valid in only this specific field.
9508 When called with two `C-u' prefixes, insert the active equation
9509 for the field back into the current field, so that it can be
9510 edited there. This is useful in order to use \\[org-table-show-reference]
9511 to check the referenced fields.
9513 When called, the command first prompts for a formula, which is read in
9514 the minibuffer. Previously entered formulas are available through the
9515 history list, and the last used formula is offered as a default.
9516 These stored formulas are adapted correctly when moving, inserting, or
9517 deleting columns with the corresponding commands.
9519 The formula can be any algebraic expression understood by the Calc package.
9520 For details, see the Org-mode manual.
9522 This function can also be called from Lisp programs and offers
9523 additional arguments: EQUATION can be the formula to apply. If this
9524 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9525 used to speed-up recursive calls by by-passing unnecessary aligns.
9526 SUPPRESS-CONST suppresses the interpretation of constants in the
9527 formula, assuming that this has been done already outside the function.
9528 SUPPRESS-STORE means the formula should not be stored, either because
9529 it is already stored, or because it is a modified equation that should
9530 not overwrite the stored one."
9531 (interactive "P")
9532 (org-table-check-inside-data-field)
9533 (or suppress-analysis (org-table-get-specials))
9534 (if (equal arg '(16))
9535 (let ((eq (org-table-current-field-formula)))
9536 (or eq (error "No equation active for current field"))
9537 (org-table-get-field nil eq)
9538 (org-table-align)
9539 (setq org-table-may-need-update t))
9540 (let* (fields
9541 (ndown (if (integerp arg) arg 1))
9542 (org-table-automatic-realign nil)
9543 (case-fold-search nil)
9544 (down (> ndown 1))
9545 (formula (if (and equation suppress-store)
9546 equation
9547 (org-table-get-formula equation (equal arg '(4)))))
9548 (n0 (org-table-current-column))
9549 (modes (copy-sequence org-calc-default-modes))
9550 (numbers nil) ; was a variable, now fixed default
9551 (keep-empty nil)
9552 n form form0 bw fmt x ev orig c lispp literal)
9553 ;; Parse the format string. Since we have a lot of modes, this is
9554 ;; a lot of work. However, I think calc still uses most of the time.
9555 (if (string-match ";" formula)
9556 (let ((tmp (org-split-string formula ";")))
9557 (setq formula (car tmp)
9558 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9559 (nth 1 tmp)))
9560 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
9561 (setq c (string-to-char (match-string 1 fmt))
9562 n (string-to-number (match-string 2 fmt)))
9563 (if (= c ?p)
9564 (setq modes (org-set-calc-mode 'calc-internal-prec n))
9565 (setq modes (org-set-calc-mode
9566 'calc-float-format
9567 (list (cdr (assoc c '((?n . float) (?f . fix)
9568 (?s . sci) (?e . eng))))
9569 n))))
9570 (setq fmt (replace-match "" t t fmt)))
9571 (if (string-match "[NT]" fmt)
9572 (setq numbers (equal (match-string 0 fmt) "N")
9573 fmt (replace-match "" t t fmt)))
9574 (if (string-match "L" fmt)
9575 (setq literal t
9576 fmt (replace-match "" t t fmt)))
9577 (if (string-match "E" fmt)
9578 (setq keep-empty t
9579 fmt (replace-match "" t t fmt)))
9580 (while (string-match "[DRFS]" fmt)
9581 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9582 (setq fmt (replace-match "" t t fmt)))
9583 (unless (string-match "\\S-" fmt)
9584 (setq fmt nil))))
9585 (if (and (not suppress-const) org-table-formula-use-constants)
9586 (setq formula (org-table-formula-substitute-names formula)))
9587 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9588 (while (> ndown 0)
9589 (setq fields (org-split-string
9590 (org-no-properties
9591 (buffer-substring (point-at-bol) (point-at-eol)))
9592 " *| *"))
9593 (if (eq numbers t)
9594 (setq fields (mapcar
9595 (lambda (x) (number-to-string (string-to-number x)))
9596 fields)))
9597 (setq ndown (1- ndown))
9598 (setq form (copy-sequence formula)
9599 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
9600 (if (and lispp literal) (setq lispp 'literal))
9601 ;; Check for old vertical references
9602 (setq form (org-rewrite-old-row-references form))
9603 ;; Insert complex ranges
9604 (while (string-match org-table-range-regexp form)
9605 (setq form
9606 (replace-match
9607 (save-match-data
9608 (org-table-make-reference
9609 (org-table-get-range (match-string 0 form) nil n0)
9610 keep-empty numbers lispp))
9611 t t form)))
9612 ;; Insert simple ranges
9613 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
9614 (setq form
9615 (replace-match
9616 (save-match-data
9617 (org-table-make-reference
9618 (org-sublist
9619 fields (string-to-number (match-string 1 form))
9620 (string-to-number (match-string 2 form)))
9621 keep-empty numbers lispp))
9622 t t form)))
9623 (setq form0 form)
9624 ;; Insert the references to fields in same row
9625 (while (string-match "\\$\\([0-9]+\\)" form)
9626 (setq n (string-to-number (match-string 1 form))
9627 x (nth (1- (if (= n 0) n0 n)) fields))
9628 (unless x (error "Invalid field specifier \"%s\""
9629 (match-string 0 form)))
9630 (setq form (replace-match
9631 (save-match-data
9632 (org-table-make-reference x nil numbers lispp))
9633 t t form)))
9635 (if lispp
9636 (setq ev (condition-case nil
9637 (eval (eval (read form)))
9638 (error "#ERROR"))
9639 ev (if (numberp ev) (number-to-string ev) ev))
9640 (or (fboundp 'calc-eval)
9641 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
9642 (setq ev (calc-eval (cons form modes)
9643 (if numbers 'num))))
9645 (when org-table-formula-debug
9646 (with-output-to-temp-buffer "*Substitution History*"
9647 (princ (format "Substitution history of formula
9648 Orig: %s
9649 $xyz-> %s
9650 @r$c-> %s
9651 $1-> %s\n" orig formula form0 form))
9652 (if (listp ev)
9653 (princ (format " %s^\nError: %s"
9654 (make-string (car ev) ?\-) (nth 1 ev)))
9655 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9656 ev (or fmt "NONE")
9657 (if fmt (format fmt (string-to-number ev)) ev)))))
9658 (setq bw (get-buffer-window "*Substitution History*"))
9659 (shrink-window-if-larger-than-buffer bw)
9660 (unless (and (interactive-p) (not ndown))
9661 (unless (let (inhibit-redisplay)
9662 (y-or-n-p "Debugging Formula. Continue to next? "))
9663 (org-table-align)
9664 (error "Abort"))
9665 (delete-window bw)
9666 (message "")))
9667 (if (listp ev) (setq fmt nil ev "#ERROR"))
9668 (org-table-justify-field-maybe
9669 (if fmt (format fmt (string-to-number ev)) ev))
9670 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9671 (call-interactively 'org-return)
9672 (setq ndown 0)))
9673 (and down (org-table-maybe-recalculate-line))
9674 (or suppress-align (and org-table-may-need-update
9675 (org-table-align))))))
9677 (defun org-table-put-field-property (prop value)
9678 (save-excursion
9679 (put-text-property (progn (skip-chars-backward "^|") (point))
9680 (progn (skip-chars-forward "^|") (point))
9681 prop value)))
9683 (defun org-table-get-range (desc &optional tbeg col highlight)
9684 "Get a calc vector from a column, accorting to descriptor DESC.
9685 Optional arguments TBEG and COL can give the beginning of the table and
9686 the current column, to avoid unnecessary parsing.
9687 HIGHLIGHT means, just highlight the range."
9688 (if (not (equal (string-to-char desc) ?@))
9689 (setq desc (concat "@" desc)))
9690 (save-excursion
9691 (or tbeg (setq tbeg (org-table-begin)))
9692 (or col (setq col (org-table-current-column)))
9693 (let ((thisline (org-current-line))
9694 beg end c1 c2 r1 r2 rangep tmp)
9695 (unless (string-match org-table-range-regexp desc)
9696 (error "Invalid table range specifier `%s'" desc))
9697 (setq rangep (match-end 3)
9698 r1 (and (match-end 1) (match-string 1 desc))
9699 r2 (and (match-end 4) (match-string 4 desc))
9700 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
9701 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
9703 (and c1 (setq c1 (+ (string-to-number c1)
9704 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
9705 (and c2 (setq c2 (+ (string-to-number c2)
9706 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
9707 (if (equal r1 "") (setq r1 nil))
9708 (if (equal r2 "") (setq r2 nil))
9709 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
9710 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
9711 ; (setq r2 (or r2 r1) c2 (or c2 c1))
9712 (if (not r1) (setq r1 thisline))
9713 (if (not r2) (setq r2 thisline))
9714 (if (not c1) (setq c1 col))
9715 (if (not c2) (setq c2 col))
9716 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
9717 ;; just one field
9718 (progn
9719 (goto-line r1)
9720 (while (not (looking-at org-table-dataline-regexp))
9721 (beginning-of-line 2))
9722 (prog1 (org-trim (org-table-get-field c1))
9723 (if highlight (org-table-highlight-rectangle (point) (point)))))
9724 ;; A range, return a vector
9725 ;; First sort the numbers to get a regular ractangle
9726 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
9727 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
9728 (goto-line r1)
9729 (while (not (looking-at org-table-dataline-regexp))
9730 (beginning-of-line 2))
9731 (org-table-goto-column c1)
9732 (setq beg (point))
9733 (goto-line r2)
9734 (while (not (looking-at org-table-dataline-regexp))
9735 (beginning-of-line 0))
9736 (org-table-goto-column c2)
9737 (setq end (point))
9738 (if highlight
9739 (org-table-highlight-rectangle
9740 beg (progn (skip-chars-forward "^|\n") (point))))
9741 ;; return string representation of calc vector
9742 (mapcar 'org-trim
9743 (apply 'append (org-table-copy-region beg end)))))))
9745 (defun org-table-get-descriptor-line (desc &optional cline bline table)
9746 "Analyze descriptor DESC and retrieve the corresponding line number.
9747 The cursor is currently in line CLINE, the table begins in line BLINE,
9748 and TABLE is a vector with line types."
9749 (if (string-match "^[0-9]+$" desc)
9750 (aref org-table-dlines (string-to-number desc))
9751 (setq cline (or cline (org-current-line))
9752 bline (or bline org-table-current-begin-line)
9753 table (or table org-table-current-line-types))
9754 (if (or
9755 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
9756 ;; 1 2 3 4 5 6
9757 (and (not (match-end 3)) (not (match-end 6)))
9758 (and (match-end 3) (match-end 6) (not (match-end 5))))
9759 (error "invalid row descriptor `%s'" desc))
9760 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
9761 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
9762 (odir (and (match-end 5) (match-string 5 desc)))
9763 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
9764 (i (- cline bline))
9765 (rel (and (match-end 6)
9766 (or (and (match-end 1) (not (match-end 3)))
9767 (match-end 5)))))
9768 (if (and hn (not hdir))
9769 (progn
9770 (setq i 0 hdir "+")
9771 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
9772 (if (and (not hn) on (not odir))
9773 (error "should never happen");;(aref org-table-dlines on)
9774 (if (and hn (> hn 0))
9775 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
9776 (if on
9777 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
9778 (+ bline i)))))
9780 (defun org-find-row-type (table i type backwards relative n)
9781 (let ((l (length table)))
9782 (while (> n 0)
9783 (while (and (setq i (+ i (if backwards -1 1)))
9784 (>= i 0) (< i l)
9785 (not (eq (aref table i) type))
9786 (if (and relative (eq (aref table i) 'hline))
9787 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
9788 t)))
9789 (setq n (1- n)))
9790 (if (or (< i 0) (>= i l))
9791 (error "Row descriptior leads outside table")
9792 i)))
9794 (defun org-rewrite-old-row-references (s)
9795 (if (string-match "&[-+0-9I]" s)
9796 (error "Formula contains old &row reference, please rewrite using @-syntax")
9799 (defun org-table-make-reference (elements keep-empty numbers lispp)
9800 "Convert list ELEMENTS to something appropriate to insert into formula.
9801 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
9802 NUMBERS indicates that everything should be converted to numbers.
9803 LISPP means to return something appropriate for a Lisp list."
9804 (if (stringp elements) ; just a single val
9805 (if lispp
9806 (if (eq lispp 'literal)
9807 elements
9808 (prin1-to-string (if numbers (string-to-number elements) elements)))
9809 (if (equal elements "") (setq elements "0"))
9810 (if numbers (number-to-string (string-to-number elements)) elements))
9811 (unless keep-empty
9812 (setq elements
9813 (delq nil
9814 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
9815 elements))))
9816 (setq elements (or elements '("0")))
9817 (if lispp
9818 (mapconcat
9819 (lambda (x)
9820 (if (eq lispp 'literal)
9822 (prin1-to-string (if numbers (string-to-number x) x))))
9823 elements " ")
9824 (concat "[" (mapconcat
9825 (lambda (x)
9826 (if numbers (number-to-string (string-to-number x)) x))
9827 elements
9828 ",") "]"))))
9830 (defun org-table-recalculate (&optional all noalign)
9831 "Recalculate the current table line by applying all stored formulas.
9832 With prefix arg ALL, do this for all lines in the table."
9833 (interactive "P")
9834 (or (memq this-command org-recalc-commands)
9835 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9836 (unless (org-at-table-p) (error "Not at a table"))
9837 (if (equal all '(16))
9838 (org-table-iterate)
9839 (org-table-get-specials)
9840 (let* ((eqlist (sort (org-table-get-stored-formulas)
9841 (lambda (a b) (string< (car a) (car b)))))
9842 (inhibit-redisplay (not debug-on-error))
9843 (line-re org-table-dataline-regexp)
9844 (thisline (org-current-line))
9845 (thiscol (org-table-current-column))
9846 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
9847 ;; Insert constants in all formulas
9848 (setq eqlist
9849 (mapcar (lambda (x)
9850 (setcdr x (org-table-formula-substitute-names (cdr x)))
9852 eqlist))
9853 ;; Split the equation list
9854 (while (setq eq (pop eqlist))
9855 (if (<= (string-to-char (car eq)) ?9)
9856 (push eq eqlnum)
9857 (push eq eqlname)))
9858 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9859 (if all
9860 (progn
9861 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9862 (goto-char (setq beg (org-table-begin)))
9863 (if (re-search-forward org-table-calculate-mark-regexp end t)
9864 ;; This is a table with marked lines, compute selected lines
9865 (setq line-re org-table-recalculate-regexp)
9866 ;; Move forward to the first non-header line
9867 (if (and (re-search-forward org-table-dataline-regexp end t)
9868 (re-search-forward org-table-hline-regexp end t)
9869 (re-search-forward org-table-dataline-regexp end t))
9870 (setq beg (match-beginning 0))
9871 nil))) ;; just leave beg where it is
9872 (setq beg (point-at-bol)
9873 end (move-marker (make-marker) (1+ (point-at-eol)))))
9874 (goto-char beg)
9875 (and all (message "Re-applying formulas to full table..."))
9877 ;; First find the named fields, and mark them untouchanble
9878 (remove-text-properties beg end '(org-untouchable t))
9879 (while (setq eq (pop eqlname))
9880 (setq name (car eq)
9881 a (assoc name org-table-named-field-locations))
9882 (and (not a)
9883 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
9884 (setq a (list name
9885 (aref org-table-dlines
9886 (string-to-number (match-string 1 name)))
9887 (string-to-number (match-string 2 name)))))
9888 (when (and a (or all (equal (nth 1 a) thisline)))
9889 (message "Re-applying formula to field: %s" name)
9890 (goto-line (nth 1 a))
9891 (org-table-goto-column (nth 2 a))
9892 (push (append a (list (cdr eq))) eqlname1)
9893 (org-table-put-field-property :org-untouchable t)))
9895 ;; Now evauluate the column formulas, but skip fields covered by
9896 ;; field formulas
9897 (goto-char beg)
9898 (while (re-search-forward line-re end t)
9899 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
9900 ;; Unprotected line, recalculate
9901 (and all (message "Re-applying formulas to full table...(line %d)"
9902 (setq cnt (1+ cnt))))
9903 (setq org-last-recalc-line (org-current-line))
9904 (setq eql eqlnum)
9905 (while (setq entry (pop eql))
9906 (goto-line org-last-recalc-line)
9907 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9908 (unless (get-text-property (point) :org-untouchable)
9909 (org-table-eval-formula nil (cdr entry)
9910 'noalign 'nocst 'nostore 'noanalysis)))))
9912 ;; Now evaluate the field formulas
9913 (while (setq eq (pop eqlname1))
9914 (message "Re-applying formula to field: %s" (car eq))
9915 (goto-line (nth 1 eq))
9916 (org-table-goto-column (nth 2 eq))
9917 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
9918 'nostore 'noanalysis))
9920 (goto-line thisline)
9921 (org-table-goto-column thiscol)
9922 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
9923 (or noalign (and org-table-may-need-update (org-table-align))
9924 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9926 ;; back to initial position
9927 (message "Re-applying formulas...done")
9928 (goto-line thisline)
9929 (org-table-goto-column thiscol)
9930 (or noalign (and org-table-may-need-update (org-table-align))
9931 (and all (message "Re-applying formulas...done"))))))
9933 (defun org-table-iterate (&optional arg)
9934 "Recalculate the table until it does not change anymore."
9935 (interactive "P")
9936 (let ((imax (if arg (prefix-numeric-value arg) 10))
9937 (i 0)
9938 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
9939 thistbl)
9940 (catch 'exit
9941 (while (< i imax)
9942 (setq i (1+ i))
9943 (org-table-recalculate 'all)
9944 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
9945 (if (not (string= lasttbl thistbl))
9946 (setq lasttbl thistbl)
9947 (if (> i 1)
9948 (message "Convergence after %d iterations" i)
9949 (message "Table was already stable"))
9950 (throw 'exit t)))
9951 (error "No convergence after %d iterations" i))))
9953 (defun org-table-formula-substitute-names (f)
9954 "Replace $const with values in string F."
9955 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
9956 ;; First, check for column names
9957 (while (setq start (string-match org-table-column-name-regexp f start))
9958 (setq start (1+ start))
9959 (setq a (assoc (match-string 1 f) org-table-column-names))
9960 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9961 ;; Parameters and constants
9962 (setq start 0)
9963 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
9964 (setq start (1+ start))
9965 (if (setq a (save-match-data
9966 (org-table-get-constant (match-string 1 f))))
9967 (setq f (replace-match
9968 (concat (if pp "(") a (if pp ")")) t t f))))
9969 (if org-table-formula-debug
9970 (put-text-property 0 (length f) :orig-formula f1 f))
9973 (defun org-table-get-constant (const)
9974 "Find the value for a parameter or constant in a formula.
9975 Parameters get priority."
9976 (or (cdr (assoc const org-table-local-parameters))
9977 (cdr (assoc const org-table-formula-constants-local))
9978 (cdr (assoc const org-table-formula-constants))
9979 (and (fboundp 'constants-get) (constants-get const))
9980 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
9981 (org-entry-get nil (substring const 5) 'inherit))
9982 "#UNDEFINED_NAME"))
9984 (defvar org-table-fedit-map
9985 (let ((map (make-sparse-keymap)))
9986 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
9987 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
9988 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
9989 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
9990 (org-defkey map "\C-c?" 'org-table-show-reference)
9991 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
9992 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
9993 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
9994 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
9995 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
9996 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
9997 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
9998 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
9999 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10000 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10001 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10002 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10003 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10004 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10005 map))
10007 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10008 '("Edit-Formulas"
10009 ["Finish and Install" org-table-fedit-finish t]
10010 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10011 ["Abort" org-table-fedit-abort t]
10012 "--"
10013 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10014 ["Complete Lisp Symbol" lisp-complete-symbol t]
10015 "--"
10016 "Shift Reference at Point"
10017 ["Up" org-table-fedit-ref-up t]
10018 ["Down" org-table-fedit-ref-down t]
10019 ["Left" org-table-fedit-ref-left t]
10020 ["Right" org-table-fedit-ref-right t]
10022 "Change Test Row for Column Formulas"
10023 ["Up" org-table-fedit-line-up t]
10024 ["Down" org-table-fedit-line-down t]
10025 "--"
10026 ["Scroll Table Window" org-table-fedit-scroll t]
10027 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10028 ["Show Table Grid" org-table-fedit-toggle-coordinates
10029 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10030 org-table-overlay-coordinates)]
10031 "--"
10032 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10033 :style toggle :selected org-table-buffer-is-an]))
10035 (defvar org-pos)
10037 (defun org-table-edit-formulas ()
10038 "Edit the formulas of the current table in a separate buffer."
10039 (interactive)
10040 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10041 (beginning-of-line 0))
10042 (unless (org-at-table-p) (error "Not at a table"))
10043 (org-table-get-specials)
10044 (let ((key (org-table-current-field-formula 'key 'noerror))
10045 (eql (sort (org-table-get-stored-formulas 'noerror)
10046 'org-table-formula-less-p))
10047 (pos (move-marker (make-marker) (point)))
10048 (startline 1)
10049 (wc (current-window-configuration))
10050 (titles '((column . "# Column Formulas\n")
10051 (field . "# Field Formulas\n")
10052 (named . "# Named Field Formulas\n")))
10053 entry s type title)
10054 (org-switch-to-buffer-other-window "*Edit Formulas*")
10055 (erase-buffer)
10056 ;; Keep global-font-lock-mode from turning on font-lock-mode
10057 (let ((font-lock-global-modes '(not fundamental-mode)))
10058 (fundamental-mode))
10059 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10060 (org-set-local 'org-pos pos)
10061 (org-set-local 'org-window-configuration wc)
10062 (use-local-map org-table-fedit-map)
10063 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10064 (easy-menu-add org-table-fedit-menu)
10065 (setq startline (org-current-line))
10066 (while (setq entry (pop eql))
10067 (setq type (cond
10068 ((equal (string-to-char (car entry)) ?@) 'field)
10069 ((string-match "^[0-9]" (car entry)) 'column)
10070 (t 'named)))
10071 (when (setq title (assq type titles))
10072 (or (bobp) (insert "\n"))
10073 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10074 (setq titles (delq title titles)))
10075 (if (equal key (car entry)) (setq startline (org-current-line)))
10076 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10077 (car entry) " = " (cdr entry) "\n"))
10078 (remove-text-properties 0 (length s) '(face nil) s)
10079 (insert s))
10080 (if (eq org-table-use-standard-references t)
10081 (org-table-fedit-toggle-ref-type))
10082 (goto-line startline)
10083 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10085 (defun org-table-fedit-post-command ()
10086 (when (not (memq this-command '(lisp-complete-symbol)))
10087 (let ((win (selected-window)))
10088 (save-excursion
10089 (condition-case nil
10090 (org-table-show-reference)
10091 (error nil))
10092 (select-window win)))))
10094 (defun org-table-formula-to-user (s)
10095 "Convert a formula from internal to user representation."
10096 (if (eq org-table-use-standard-references t)
10097 (org-table-convert-refs-to-an s)
10100 (defun org-table-formula-from-user (s)
10101 "Convert a formula from user to internal representation."
10102 (if org-table-use-standard-references
10103 (org-table-convert-refs-to-rc s)
10106 (defun org-table-convert-refs-to-rc (s)
10107 "Convert spreadsheet references from AB7 to @7$28.
10108 Works for single references, but also for entire formulas and even the
10109 full TBLFM line."
10110 (let ((start 0))
10111 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10112 (cond
10113 ((match-end 3)
10114 ;; format match, just advance
10115 (setq start (match-end 0)))
10116 ((and (> (match-beginning 0) 0)
10117 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10118 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10119 ;; 3.e5 or something like this.
10120 (setq start (match-end 0)))
10122 (setq start (match-beginning 0)
10123 s (replace-match
10124 (if (equal (match-string 2 s) "&")
10125 (format "$%d" (org-letters-to-number (match-string 1 s)))
10126 (format "@%d$%d"
10127 (string-to-number (match-string 2 s))
10128 (org-letters-to-number (match-string 1 s))))
10129 t t s)))))
10132 (defun org-table-convert-refs-to-an (s)
10133 "Convert spreadsheet references from to @7$28 to AB7.
10134 Works for single references, but also for entire formulas and even the
10135 full TBLFM line."
10136 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10137 (setq s (replace-match
10138 (format "%s%d"
10139 (org-number-to-letters
10140 (string-to-number (match-string 2 s)))
10141 (string-to-number (match-string 1 s)))
10142 t t s)))
10143 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10144 (setq s (replace-match (concat "\\1"
10145 (org-number-to-letters
10146 (string-to-number (match-string 2 s))) "&")
10147 t nil s)))
10150 (defun org-letters-to-number (s)
10151 "Convert a base 26 number represented by letters into an integer.
10152 For example: AB -> 28."
10153 (let ((n 0))
10154 (setq s (upcase s))
10155 (while (> (length s) 0)
10156 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10157 s (substring s 1)))
10160 (defun org-number-to-letters (n)
10161 "Convert an integer into a base 26 number represented by letters.
10162 For example: 28 -> AB."
10163 (let ((s ""))
10164 (while (> n 0)
10165 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10166 n (/ (1- n) 26)))
10169 (defun org-table-fedit-convert-buffer (function)
10170 "Convert all references in this buffer, using FUNTION."
10171 (let ((line (org-current-line)))
10172 (goto-char (point-min))
10173 (while (not (eobp))
10174 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10175 (delete-region (point) (point-at-eol))
10176 (or (eobp) (forward-char 1)))
10177 (goto-line line)))
10179 (defun org-table-fedit-toggle-ref-type ()
10180 "Convert all references in the buffer from B3 to @3$2 and back."
10181 (interactive)
10182 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10183 (org-table-fedit-convert-buffer
10184 (if org-table-buffer-is-an
10185 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10186 (message "Reference type switched to %s"
10187 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10189 (defun org-table-fedit-ref-up ()
10190 "Shift the reference at point one row/hline up."
10191 (interactive)
10192 (org-table-fedit-shift-reference 'up))
10193 (defun org-table-fedit-ref-down ()
10194 "Shift the reference at point one row/hline down."
10195 (interactive)
10196 (org-table-fedit-shift-reference 'down))
10197 (defun org-table-fedit-ref-left ()
10198 "Shift the reference at point one field to the left."
10199 (interactive)
10200 (org-table-fedit-shift-reference 'left))
10201 (defun org-table-fedit-ref-right ()
10202 "Shift the reference at point one field to the right."
10203 (interactive)
10204 (org-table-fedit-shift-reference 'right))
10206 (defun org-table-fedit-shift-reference (dir)
10207 (cond
10208 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10209 (if (memq dir '(left right))
10210 (org-rematch-and-replace 1 (eq dir 'left))
10211 (error "Cannot shift reference in this direction")))
10212 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10213 ;; A B3-like reference
10214 (if (memq dir '(up down))
10215 (org-rematch-and-replace 2 (eq dir 'up))
10216 (org-rematch-and-replace 1 (eq dir 'left))))
10217 ((org-at-regexp-p
10218 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10219 ;; An internal reference
10220 (if (memq dir '(up down))
10221 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10222 (org-rematch-and-replace 5 (eq dir 'left))))))
10224 (defun org-rematch-and-replace (n &optional decr hline)
10225 "Re-match the group N, and replace it with the shifted refrence."
10226 (or (match-end n) (error "Cannot shift reference in this direction"))
10227 (goto-char (match-beginning n))
10228 (and (looking-at (regexp-quote (match-string n)))
10229 (replace-match (org-shift-refpart (match-string 0) decr hline)
10230 t t)))
10232 (defun org-shift-refpart (ref &optional decr hline)
10233 "Shift a refrence part REF.
10234 If DECR is set, decrease the references row/column, else increase.
10235 If HLINE is set, this may be a hline reference, it certainly is not
10236 a translation reference."
10237 (save-match-data
10238 (let* ((sign (string-match "^[-+]" ref)) n)
10240 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10241 (cond
10242 ((and hline (string-match "^I+" ref))
10243 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10244 (setq n (+ n (if decr -1 1)))
10245 (if (= n 0) (setq n (+ n (if decr -1 1))))
10246 (if sign
10247 (setq sign (if (< n 0) "-" "+") n (abs n))
10248 (setq n (max 1 n)))
10249 (concat sign (make-string n ?I)))
10251 ((string-match "^[0-9]+" ref)
10252 (setq n (string-to-number (concat sign ref)))
10253 (setq n (+ n (if decr -1 1)))
10254 (if sign
10255 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10256 (number-to-string (max 1 n))))
10258 ((string-match "^[a-zA-Z]+" ref)
10259 (org-number-to-letters
10260 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10262 (t (error "Cannot shift reference"))))))
10264 (defun org-table-fedit-toggle-coordinates ()
10265 "Toggle the display of coordinates in the refrenced table."
10266 (interactive)
10267 (let ((pos (marker-position org-pos)))
10268 (with-current-buffer (marker-buffer org-pos)
10269 (save-excursion
10270 (goto-char pos)
10271 (org-table-toggle-coordinate-overlays)))))
10273 (defun org-table-fedit-finish (&optional arg)
10274 "Parse the buffer for formula definitions and install them.
10275 With prefix ARG, apply the new formulas to the table."
10276 (interactive "P")
10277 (org-table-remove-rectangle-highlight)
10278 (if org-table-use-standard-references
10279 (progn
10280 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10281 (setq org-table-buffer-is-an nil)))
10282 (let ((pos org-pos) eql var form)
10283 (goto-char (point-min))
10284 (while (re-search-forward
10285 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10286 nil t)
10287 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10288 form (match-string 3))
10289 (setq form (org-trim form))
10290 (when (not (equal form ""))
10291 (while (string-match "[ \t]*\n[ \t]*" form)
10292 (setq form (replace-match " " t t form)))
10293 (when (assoc var eql)
10294 (error "Double formulas for %s" var))
10295 (push (cons var form) eql)))
10296 (setq org-pos nil)
10297 (set-window-configuration org-window-configuration)
10298 (select-window (get-buffer-window (marker-buffer pos)))
10299 (goto-char pos)
10300 (unless (org-at-table-p)
10301 (error "Lost table position - cannot install formulae"))
10302 (org-table-store-formulas eql)
10303 (move-marker pos nil)
10304 (kill-buffer "*Edit Formulas*")
10305 (if arg
10306 (org-table-recalculate 'all)
10307 (message "New formulas installed - press C-u C-c C-c to apply."))))
10309 (defun org-table-fedit-abort ()
10310 "Abort editing formulas, without installing the changes."
10311 (interactive)
10312 (org-table-remove-rectangle-highlight)
10313 (let ((pos org-pos))
10314 (set-window-configuration org-window-configuration)
10315 (select-window (get-buffer-window (marker-buffer pos)))
10316 (goto-char pos)
10317 (move-marker pos nil)
10318 (message "Formula editing aborted without installing changes")))
10320 (defun org-table-fedit-lisp-indent ()
10321 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
10322 (interactive)
10323 (let ((pos (point)) beg end ind)
10324 (beginning-of-line 1)
10325 (cond
10326 ((looking-at "[ \t]")
10327 (goto-char pos)
10328 (call-interactively 'lisp-indent-line))
10329 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
10330 ((not (fboundp 'pp-buffer))
10331 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
10332 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
10333 (goto-char (- (match-end 0) 2))
10334 (setq beg (point))
10335 (setq ind (make-string (current-column) ?\ ))
10336 (condition-case nil (forward-sexp 1)
10337 (error
10338 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
10339 (setq end (point))
10340 (save-restriction
10341 (narrow-to-region beg end)
10342 (if (eq last-command this-command)
10343 (progn
10344 (goto-char (point-min))
10345 (setq this-command nil)
10346 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
10347 (replace-match " ")))
10348 (pp-buffer)
10349 (untabify (point-min) (point-max))
10350 (goto-char (1+ (point-min)))
10351 (while (re-search-forward "^." nil t)
10352 (beginning-of-line 1)
10353 (insert ind))
10354 (goto-char (point-max))
10355 (backward-delete-char 1)))
10356 (goto-char beg))
10357 (t nil))))
10359 (defvar org-show-positions nil)
10361 (defun org-table-show-reference (&optional local)
10362 "Show the location/value of the $ expression at point."
10363 (interactive)
10364 (org-table-remove-rectangle-highlight)
10365 (catch 'exit
10366 (let ((pos (if local (point) org-pos))
10367 (face2 'highlight)
10368 (org-inhibit-highlight-removal t)
10369 (win (selected-window))
10370 (org-show-positions nil)
10371 var name e what match dest)
10372 (if local (org-table-get-specials))
10373 (setq what (cond
10374 ((or (org-at-regexp-p org-table-range-regexp2)
10375 (org-at-regexp-p org-table-translate-regexp)
10376 (org-at-regexp-p org-table-range-regexp))
10377 (setq match
10378 (save-match-data
10379 (org-table-convert-refs-to-rc (match-string 0))))
10380 'range)
10381 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
10382 ((org-at-regexp-p "\\$[0-9]+") 'column)
10383 ((not local) nil)
10384 (t (error "No reference at point")))
10385 match (and what (or match (match-string 0))))
10386 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
10387 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
10388 'secondary-selection))
10389 (org-add-hook 'before-change-functions
10390 'org-table-remove-rectangle-highlight)
10391 (if (eq what 'name) (setq var (substring match 1)))
10392 (when (eq what 'range)
10393 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
10394 (setq match (org-table-formula-substitute-names match)))
10395 (unless local
10396 (save-excursion
10397 (end-of-line 1)
10398 (re-search-backward "^\\S-" nil t)
10399 (beginning-of-line 1)
10400 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
10401 (setq dest
10402 (save-match-data
10403 (org-table-convert-refs-to-rc (match-string 1))))
10404 (org-table-add-rectangle-overlay
10405 (match-beginning 1) (match-end 1) face2))))
10406 (if (and (markerp pos) (marker-buffer pos))
10407 (if (get-buffer-window (marker-buffer pos))
10408 (select-window (get-buffer-window (marker-buffer pos)))
10409 (org-switch-to-buffer-other-window (get-buffer-window
10410 (marker-buffer pos)))))
10411 (goto-char pos)
10412 (org-table-force-dataline)
10413 (when dest
10414 (setq name (substring dest 1))
10415 (cond
10416 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
10417 (setq e (assoc name org-table-named-field-locations))
10418 (goto-line (nth 1 e))
10419 (org-table-goto-column (nth 2 e)))
10420 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
10421 (let ((l (string-to-number (match-string 1 dest)))
10422 (c (string-to-number (match-string 2 dest))))
10423 (goto-line (aref org-table-dlines l))
10424 (org-table-goto-column c)))
10425 (t (org-table-goto-column (string-to-number name))))
10426 (move-marker pos (point))
10427 (org-table-highlight-rectangle nil nil face2))
10428 (cond
10429 ((equal dest match))
10430 ((not match))
10431 ((eq what 'range)
10432 (condition-case nil
10433 (save-excursion
10434 (org-table-get-range match nil nil 'highlight))
10435 (error nil)))
10436 ((setq e (assoc var org-table-named-field-locations))
10437 (goto-line (nth 1 e))
10438 (org-table-goto-column (nth 2 e))
10439 (org-table-highlight-rectangle (point) (point))
10440 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10441 ((setq e (assoc var org-table-column-names))
10442 (org-table-goto-column (string-to-number (cdr e)))
10443 (org-table-highlight-rectangle (point) (point))
10444 (goto-char (org-table-begin))
10445 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10446 (org-table-end) t)
10447 (progn
10448 (goto-char (match-beginning 1))
10449 (org-table-highlight-rectangle)
10450 (message "Named column (column %s)" (cdr e)))
10451 (error "Column name not found")))
10452 ((eq what 'column)
10453 ;; column number
10454 (org-table-goto-column (string-to-number (substring match 1)))
10455 (org-table-highlight-rectangle (point) (point))
10456 (message "Column %s" (substring match 1)))
10457 ((setq e (assoc var org-table-local-parameters))
10458 (goto-char (org-table-begin))
10459 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10460 (progn
10461 (goto-char (match-beginning 1))
10462 (org-table-highlight-rectangle)
10463 (message "Local parameter."))
10464 (error "Parameter not found")))
10466 (cond
10467 ((not var) (error "No reference at point"))
10468 ((setq e (assoc var org-table-formula-constants-local))
10469 (message "Local Constant: $%s=%s in #+CONSTANTS line."
10470 var (cdr e)))
10471 ((setq e (assoc var org-table-formula-constants))
10472 (message "Constant: $%s=%s in `org-table-formula-constants'."
10473 var (cdr e)))
10474 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10475 (message "Constant: $%s=%s, from `constants.el'%s."
10476 var e (format " (%s units)" constants-unit-system)))
10477 (t (error "Undefined name $%s" var)))))
10478 (goto-char pos)
10479 (when (and org-show-positions
10480 (not (memq this-command '(org-table-fedit-scroll
10481 org-table-fedit-scroll-down))))
10482 (push pos org-show-positions)
10483 (push org-table-current-begin-pos org-show-positions)
10484 (let ((min (apply 'min org-show-positions))
10485 (max (apply 'max org-show-positions)))
10486 (goto-char min) (recenter 0)
10487 (goto-char max)
10488 (or (pos-visible-in-window-p max) (recenter -1))))
10489 (select-window win))))
10491 (defun org-table-force-dataline ()
10492 "Make sure the cursor is in a dataline in a table."
10493 (unless (save-excursion
10494 (beginning-of-line 1)
10495 (looking-at org-table-dataline-regexp))
10496 (let* ((re org-table-dataline-regexp)
10497 (p1 (save-excursion (re-search-forward re nil 'move)))
10498 (p2 (save-excursion (re-search-backward re nil 'move))))
10499 (cond ((and p1 p2)
10500 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
10501 p1 p2)))
10502 ((or p1 p2) (goto-char (or p1 p2)))
10503 (t (error "No table dataline around here"))))))
10505 (defun org-table-fedit-line-up ()
10506 "Move cursor one line up in the window showing the table."
10507 (interactive)
10508 (org-table-fedit-move 'previous-line))
10510 (defun org-table-fedit-line-down ()
10511 "Move cursor one line down in the window showing the table."
10512 (interactive)
10513 (org-table-fedit-move 'next-line))
10515 (defun org-table-fedit-move (command)
10516 "Move the cursor in the window shoinw the table.
10517 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
10518 (let ((org-table-allow-automatic-line-recalculation nil)
10519 (pos org-pos) (win (selected-window)) p)
10520 (select-window (get-buffer-window (marker-buffer org-pos)))
10521 (setq p (point))
10522 (call-interactively command)
10523 (while (and (org-at-table-p)
10524 (org-at-table-hline-p))
10525 (call-interactively command))
10526 (or (org-at-table-p) (goto-char p))
10527 (move-marker pos (point))
10528 (select-window win)))
10530 (defun org-table-fedit-scroll (N)
10531 (interactive "p")
10532 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
10533 (scroll-other-window N)))
10535 (defun org-table-fedit-scroll-down (N)
10536 (interactive "p")
10537 (org-table-fedit-scroll (- N)))
10539 (defvar org-table-rectangle-overlays nil)
10541 (defun org-table-add-rectangle-overlay (beg end &optional face)
10542 "Add a new overlay."
10543 (let ((ov (org-make-overlay beg end)))
10544 (org-overlay-put ov 'face (or face 'secondary-selection))
10545 (push ov org-table-rectangle-overlays)))
10547 (defun org-table-highlight-rectangle (&optional beg end face)
10548 "Highlight rectangular region in a table."
10549 (setq beg (or beg (point)) end (or end (point)))
10550 (let ((b (min beg end))
10551 (e (max beg end))
10552 l1 c1 l2 c2 tmp)
10553 (and (boundp 'org-show-positions)
10554 (setq org-show-positions (cons b (cons e org-show-positions))))
10555 (goto-char (min beg end))
10556 (setq l1 (org-current-line)
10557 c1 (org-table-current-column))
10558 (goto-char (max beg end))
10559 (setq l2 (org-current-line)
10560 c2 (org-table-current-column))
10561 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
10562 (goto-line l1)
10563 (beginning-of-line 1)
10564 (loop for line from l1 to l2 do
10565 (when (looking-at org-table-dataline-regexp)
10566 (org-table-goto-column c1)
10567 (skip-chars-backward "^|\n") (setq beg (point))
10568 (org-table-goto-column c2)
10569 (skip-chars-forward "^|\n") (setq end (point))
10570 (org-table-add-rectangle-overlay beg end face))
10571 (beginning-of-line 2))
10572 (goto-char b))
10573 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
10575 (defun org-table-remove-rectangle-highlight (&rest ignore)
10576 "Remove the rectangle overlays."
10577 (unless org-inhibit-highlight-removal
10578 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
10579 (mapc 'org-delete-overlay org-table-rectangle-overlays)
10580 (setq org-table-rectangle-overlays nil)))
10582 (defvar org-table-coordinate-overlays nil
10583 "Collects the cooordinate grid overlays, so that they can be removed.")
10584 (make-variable-buffer-local 'org-table-coordinate-overlays)
10586 (defun org-table-overlay-coordinates ()
10587 "Add overlays to the table at point, to show row/column coordinates."
10588 (interactive)
10589 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10590 (setq org-table-coordinate-overlays nil)
10591 (save-excursion
10592 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
10593 (goto-char (org-table-begin))
10594 (while (org-at-table-p)
10595 (setq eol (point-at-eol))
10596 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
10597 (push ov org-table-coordinate-overlays)
10598 (setq hline (looking-at org-table-hline-regexp))
10599 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
10600 (format "%4d" (setq id (1+ id)))))
10601 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
10602 (when hline
10603 (setq ic 0)
10604 (while (re-search-forward "[+|]\\(-+\\)" eol t)
10605 (setq beg (1+ (match-beginning 0))
10606 ic (1+ ic)
10607 s1 (concat "$" (int-to-string ic))
10608 s2 (org-number-to-letters ic)
10609 str (if (eq org-table-use-standard-references t) s2 s1))
10610 (setq ov (org-make-overlay beg (+ beg (length str))))
10611 (push ov org-table-coordinate-overlays)
10612 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
10613 (beginning-of-line 2)))))
10615 (defun org-table-toggle-coordinate-overlays ()
10616 "Toggle the display of Row/Column numbers in tables."
10617 (interactive)
10618 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
10619 (message "Row/Column number display turned %s"
10620 (if org-table-overlay-coordinates "on" "off"))
10621 (if (and (org-at-table-p) org-table-overlay-coordinates)
10622 (org-table-align))
10623 (unless org-table-overlay-coordinates
10624 (mapc 'org-delete-overlay org-table-coordinate-overlays)
10625 (setq org-table-coordinate-overlays nil)))
10627 (defun org-table-toggle-formula-debugger ()
10628 "Toggle the formula debugger in tables."
10629 (interactive)
10630 (setq org-table-formula-debug (not org-table-formula-debug))
10631 (message "Formula debugging has been turned %s"
10632 (if org-table-formula-debug "on" "off")))
10634 ;;; The orgtbl minor mode
10636 ;; Define a minor mode which can be used in other modes in order to
10637 ;; integrate the org-mode table editor.
10639 ;; This is really a hack, because the org-mode table editor uses several
10640 ;; keys which normally belong to the major mode, for example the TAB and
10641 ;; RET keys. Here is how it works: The minor mode defines all the keys
10642 ;; necessary to operate the table editor, but wraps the commands into a
10643 ;; function which tests if the cursor is currently inside a table. If that
10644 ;; is the case, the table editor command is executed. However, when any of
10645 ;; those keys is used outside a table, the function uses `key-binding' to
10646 ;; look up if the key has an associated command in another currently active
10647 ;; keymap (minor modes, major mode, global), and executes that command.
10648 ;; There might be problems if any of the keys used by the table editor is
10649 ;; otherwise used as a prefix key.
10651 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10652 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10653 ;; addresses this by checking explicitly for both bindings.
10655 ;; The optimized version (see variable `orgtbl-optimized') takes over
10656 ;; all keys which are bound to `self-insert-command' in the *global map*.
10657 ;; Some modes bind other commands to simple characters, for example
10658 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10659 ;; active, this binding is ignored inside tables and replaced with a
10660 ;; modified self-insert.
10662 (defvar orgtbl-mode nil
10663 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10664 table editor in arbitrary modes.")
10665 (make-variable-buffer-local 'orgtbl-mode)
10667 (defvar orgtbl-mode-map (make-keymap)
10668 "Keymap for `orgtbl-mode'.")
10670 ;;;###autoload
10671 (defun turn-on-orgtbl ()
10672 "Unconditionally turn on `orgtbl-mode'."
10673 (orgtbl-mode 1))
10675 (defvar org-old-auto-fill-inhibit-regexp nil
10676 "Local variable used by `orgtbl-mode'")
10678 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
10679 "Matches a line belonging to an orgtbl.")
10681 (defconst orgtbl-extra-font-lock-keywords
10682 (list (list (concat "^" orgtbl-line-start-regexp ".*")
10683 0 (quote 'org-table) 'prepend))
10684 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
10686 ;;;###autoload
10687 (defun orgtbl-mode (&optional arg)
10688 "The `org-mode' table editor as a minor mode for use in other modes."
10689 (interactive)
10690 (if (org-mode-p)
10691 ;; Exit without error, in case some hook functions calls this
10692 ;; by accident in org-mode.
10693 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10694 (setq orgtbl-mode
10695 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10696 (if orgtbl-mode
10697 (progn
10698 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10699 ;; Make sure we are first in minor-mode-map-alist
10700 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10701 (and c (setq minor-mode-map-alist
10702 (cons c (delq c minor-mode-map-alist)))))
10703 (org-set-local (quote org-table-may-need-update) t)
10704 (org-add-hook 'before-change-functions 'org-before-change-function
10705 nil 'local)
10706 (org-set-local 'org-old-auto-fill-inhibit-regexp
10707 auto-fill-inhibit-regexp)
10708 (org-set-local 'auto-fill-inhibit-regexp
10709 (if auto-fill-inhibit-regexp
10710 (concat orgtbl-line-start-regexp "\\|"
10711 auto-fill-inhibit-regexp)
10712 orgtbl-line-start-regexp))
10713 (org-add-to-invisibility-spec '(org-cwidth))
10714 (when (fboundp 'font-lock-add-keywords)
10715 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
10716 (org-restart-font-lock))
10717 (easy-menu-add orgtbl-mode-menu)
10718 (run-hooks 'orgtbl-mode-hook))
10719 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10720 (org-cleanup-narrow-column-properties)
10721 (org-remove-from-invisibility-spec '(org-cwidth))
10722 (remove-hook 'before-change-functions 'org-before-change-function t)
10723 (when (fboundp 'font-lock-remove-keywords)
10724 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
10725 (org-restart-font-lock))
10726 (easy-menu-remove orgtbl-mode-menu)
10727 (force-mode-line-update 'all))))
10729 (defun org-cleanup-narrow-column-properties ()
10730 "Remove all properties related to narrow-column invisibility."
10731 (let ((s 1))
10732 (while (setq s (text-property-any s (point-max)
10733 'display org-narrow-column-arrow))
10734 (remove-text-properties s (1+ s) '(display t)))
10735 (setq s 1)
10736 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10737 (remove-text-properties s (1+ s) '(org-cwidth t)))
10738 (setq s 1)
10739 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10740 (remove-text-properties s (1+ s) '(invisible t)))))
10742 ;; Install it as a minor mode.
10743 (put 'orgtbl-mode :included t)
10744 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10745 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10747 (defun orgtbl-make-binding (fun n &rest keys)
10748 "Create a function for binding in the table minor mode.
10749 FUN is the command to call inside a table. N is used to create a unique
10750 command name. KEYS are keys that should be checked in for a command
10751 to execute outside of tables."
10752 (eval
10753 (list 'defun
10754 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10755 '(arg)
10756 (concat "In tables, run `" (symbol-name fun) "'.\n"
10757 "Outside of tables, run the binding of `"
10758 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10759 "'.")
10760 '(interactive "p")
10761 (list 'if
10762 '(org-at-table-p)
10763 (list 'call-interactively (list 'quote fun))
10764 (list 'let '(orgtbl-mode)
10765 (list 'call-interactively
10766 (append '(or)
10767 (mapcar (lambda (k)
10768 (list 'key-binding k))
10769 keys)
10770 '('orgtbl-error))))))))
10772 (defun orgtbl-error ()
10773 "Error when there is no default binding for a table key."
10774 (interactive)
10775 (error "This key is has no function outside tables"))
10777 (defun orgtbl-setup ()
10778 "Setup orgtbl keymaps."
10779 (let ((nfunc 0)
10780 (bindings
10781 (list
10782 '([(meta shift left)] org-table-delete-column)
10783 '([(meta left)] org-table-move-column-left)
10784 '([(meta right)] org-table-move-column-right)
10785 '([(meta shift right)] org-table-insert-column)
10786 '([(meta shift up)] org-table-kill-row)
10787 '([(meta shift down)] org-table-insert-row)
10788 '([(meta up)] org-table-move-row-up)
10789 '([(meta down)] org-table-move-row-down)
10790 '("\C-c\C-w" org-table-cut-region)
10791 '("\C-c\M-w" org-table-copy-region)
10792 '("\C-c\C-y" org-table-paste-rectangle)
10793 '("\C-c-" org-table-insert-hline)
10794 '("\C-c}" org-table-toggle-coordinate-overlays)
10795 '("\C-c{" org-table-toggle-formula-debugger)
10796 '("\C-m" org-table-next-row)
10797 '([(shift return)] org-table-copy-down)
10798 '("\C-c\C-q" org-table-wrap-region)
10799 '("\C-c?" org-table-field-info)
10800 '("\C-c " org-table-blank-field)
10801 '("\C-c+" org-table-sum)
10802 '("\C-c=" org-table-eval-formula)
10803 '("\C-c'" org-table-edit-formulas)
10804 '("\C-c`" org-table-edit-field)
10805 '("\C-c*" org-table-recalculate)
10806 '("\C-c|" org-table-create-or-convert-from-region)
10807 '("\C-c^" org-table-sort-lines)
10808 '([(control ?#)] org-table-rotate-recalc-marks)))
10809 elt key fun cmd)
10810 (while (setq elt (pop bindings))
10811 (setq nfunc (1+ nfunc))
10812 (setq key (org-key (car elt))
10813 fun (nth 1 elt)
10814 cmd (orgtbl-make-binding fun nfunc key))
10815 (org-defkey orgtbl-mode-map key cmd))
10817 ;; Special treatment needed for TAB and RET
10818 (org-defkey orgtbl-mode-map [(return)]
10819 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10820 (org-defkey orgtbl-mode-map "\C-m"
10821 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10823 (org-defkey orgtbl-mode-map [(tab)]
10824 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10825 (org-defkey orgtbl-mode-map "\C-i"
10826 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
10828 (org-defkey orgtbl-mode-map [(shift tab)]
10829 (orgtbl-make-binding 'org-table-previous-field 104
10830 [(shift tab)] [(tab)] "\C-i"))
10832 (org-defkey orgtbl-mode-map "\M-\C-m"
10833 (orgtbl-make-binding 'org-table-wrap-region 105
10834 "\M-\C-m" [(meta return)]))
10835 (org-defkey orgtbl-mode-map [(meta return)]
10836 (orgtbl-make-binding 'org-table-wrap-region 106
10837 [(meta return)] "\M-\C-m"))
10839 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
10840 (when orgtbl-optimized
10841 ;; If the user wants maximum table support, we need to hijack
10842 ;; some standard editing functions
10843 (org-remap orgtbl-mode-map
10844 'self-insert-command 'orgtbl-self-insert-command
10845 'delete-char 'org-delete-char
10846 'delete-backward-char 'org-delete-backward-char)
10847 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
10848 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10849 '("OrgTbl"
10850 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10851 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10852 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10853 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10854 "--"
10855 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10856 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10857 ["Copy Field from Above"
10858 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10859 "--"
10860 ("Column"
10861 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10862 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10863 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10864 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10865 ("Row"
10866 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10867 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10868 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10869 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10870 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10871 "--"
10872 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10873 ("Rectangle"
10874 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10875 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10876 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10877 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10878 "--"
10879 ("Radio tables"
10880 ["Insert table template" orgtbl-insert-radio-table
10881 (assq major-mode orgtbl-radio-table-templates)]
10882 ["Comment/uncomment table" orgtbl-toggle-comment t])
10883 "--"
10884 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10885 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10886 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10887 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10888 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10889 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
10890 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10891 ["Sum Column/Rectangle" org-table-sum
10892 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10893 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10894 ["Debug Formulas"
10895 org-table-toggle-formula-debugger :active (org-at-table-p)
10896 :keys "C-c {"
10897 :style toggle :selected org-table-formula-debug]
10898 ["Show Col/Row Numbers"
10899 org-table-toggle-coordinate-overlays :active (org-at-table-p)
10900 :keys "C-c }"
10901 :style toggle :selected org-table-overlay-coordinates]
10905 (defun orgtbl-ctrl-c-ctrl-c (arg)
10906 "If the cursor is inside a table, realign the table.
10907 It it is a table to be sent away to a receiver, do it.
10908 With prefix arg, also recompute table."
10909 (interactive "P")
10910 (let ((pos (point)) action)
10911 (save-excursion
10912 (beginning-of-line 1)
10913 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
10914 ((looking-at "[ \t]*|") pos)
10915 ((looking-at "#\\+TBLFM:") 'recalc))))
10916 (cond
10917 ((integerp action)
10918 (goto-char action)
10919 (org-table-maybe-eval-formula)
10920 (if arg
10921 (call-interactively 'org-table-recalculate)
10922 (org-table-maybe-recalculate-line))
10923 (call-interactively 'org-table-align)
10924 (orgtbl-send-table 'maybe))
10925 ((eq action 'recalc)
10926 (save-excursion
10927 (beginning-of-line 1)
10928 (skip-chars-backward " \r\n\t")
10929 (if (org-at-table-p)
10930 (org-call-with-arg 'org-table-recalculate t))))
10931 (t (let (orgtbl-mode)
10932 (call-interactively (key-binding "\C-c\C-c")))))))
10934 (defun orgtbl-tab (arg)
10935 "Justification and field motion for `orgtbl-mode'."
10936 (interactive "P")
10937 (if arg (org-table-edit-field t)
10938 (org-table-justify-field-maybe)
10939 (org-table-next-field)))
10941 (defun orgtbl-ret ()
10942 "Justification and field motion for `orgtbl-mode'."
10943 (interactive)
10944 (org-table-justify-field-maybe)
10945 (org-table-next-row))
10947 (defun orgtbl-self-insert-command (N)
10948 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10949 If the cursor is in a table looking at whitespace, the whitespace is
10950 overwritten, and the table is not marked as requiring realignment."
10951 (interactive "p")
10952 (if (and (org-at-table-p)
10954 (and org-table-auto-blank-field
10955 (member last-command
10956 '(orgtbl-hijacker-command-100
10957 orgtbl-hijacker-command-101
10958 orgtbl-hijacker-command-102
10959 orgtbl-hijacker-command-103
10960 orgtbl-hijacker-command-104
10961 orgtbl-hijacker-command-105))
10962 (org-table-blank-field))
10964 (eq N 1)
10965 (looking-at "[^|\n]* +|"))
10966 (let (org-table-may-need-update)
10967 (goto-char (1- (match-end 0)))
10968 (delete-backward-char 1)
10969 (goto-char (match-beginning 0))
10970 (self-insert-command N))
10971 (setq org-table-may-need-update t)
10972 (let (orgtbl-mode)
10973 (call-interactively (key-binding (vector last-input-event))))))
10975 (defun org-force-self-insert (N)
10976 "Needed to enforce self-insert under remapping."
10977 (interactive "p")
10978 (self-insert-command N))
10980 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
10981 "Regula expression matching exponentials as produced by calc.")
10983 (defvar org-table-clean-did-remove-column nil)
10985 (defun orgtbl-export (table target)
10986 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
10987 (lines (org-split-string table "[ \t]*\n[ \t]*"))
10988 org-table-last-alignment org-table-last-column-widths
10989 maxcol column)
10990 (if (not (fboundp func))
10991 (error "Cannot export orgtbl table to %s" target))
10992 (setq lines (org-table-clean-before-export lines))
10993 (setq table
10994 (mapcar
10995 (lambda (x)
10996 (if (string-match org-table-hline-regexp x)
10997 'hline
10998 (org-split-string (org-trim x) "\\s-*|\\s-*")))
10999 lines))
11000 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11001 table)))
11002 (loop for i from (1- maxcol) downto 0 do
11003 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11004 (setq column (delq nil column))
11005 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11006 (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))
11007 (funcall func table nil)))
11009 (defun orgtbl-send-table (&optional maybe)
11010 "Send a tranformed version of this table to the receiver position.
11011 With argument MAYBE, fail quietly if no transformation is defined for
11012 this table."
11013 (interactive)
11014 (catch 'exit
11015 (unless (org-at-table-p) (error "Not at a table"))
11016 ;; when non-interactive, we assume align has just happened.
11017 (when (interactive-p) (org-table-align))
11018 (save-excursion
11019 (goto-char (org-table-begin))
11020 (beginning-of-line 0)
11021 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11022 (if maybe
11023 (throw 'exit nil)
11024 (error "Don't know how to transform this table."))))
11025 (let* ((name (match-string 1))
11027 (transform (intern (match-string 2)))
11028 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11029 (skip (plist-get params :skip))
11030 (skipcols (plist-get params :skipcols))
11031 (txt (buffer-substring-no-properties
11032 (org-table-begin) (org-table-end)))
11033 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11034 (lines (org-table-clean-before-export lines))
11035 (i0 (if org-table-clean-did-remove-column 2 1))
11036 (table (mapcar
11037 (lambda (x)
11038 (if (string-match org-table-hline-regexp x)
11039 'hline
11040 (org-remove-by-index
11041 (org-split-string (org-trim x) "\\s-*|\\s-*")
11042 skipcols i0)))
11043 lines))
11044 (fun (if (= i0 2) 'cdr 'identity))
11045 (org-table-last-alignment
11046 (org-remove-by-index (funcall fun org-table-last-alignment)
11047 skipcols i0))
11048 (org-table-last-column-widths
11049 (org-remove-by-index (funcall fun org-table-last-column-widths)
11050 skipcols i0)))
11052 (unless (fboundp transform)
11053 (error "No such transformation function %s" transform))
11054 (setq txt (funcall transform table params))
11055 ;; Find the insertion place
11056 (save-excursion
11057 (goto-char (point-min))
11058 (unless (re-search-forward
11059 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11060 (error "Don't know where to insert translated table"))
11061 (goto-char (match-beginning 0))
11062 (beginning-of-line 2)
11063 (setq beg (point))
11064 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11065 (error "Cannot find end of insertion region"))
11066 (beginning-of-line 1)
11067 (delete-region beg (point))
11068 (goto-char beg)
11069 (insert txt "\n"))
11070 (message "Table converted and installed at receiver location"))))
11072 (defun org-remove-by-index (list indices &optional i0)
11073 "Remove the elements in LIST with indices in INDICES.
11074 First element has index 0, or I0 if given."
11075 (if (not indices)
11076 list
11077 (if (integerp indices) (setq indices (list indices)))
11078 (setq i0 (1- (or i0 0)))
11079 (delq :rm (mapcar (lambda (x)
11080 (setq i0 (1+ i0))
11081 (if (memq i0 indices) :rm x))
11082 list))))
11084 (defun orgtbl-toggle-comment ()
11085 "Comment or uncomment the orgtbl at point."
11086 (interactive)
11087 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11088 (re2 (concat "^" orgtbl-line-start-regexp))
11089 (commented (save-excursion (beginning-of-line 1)
11090 (cond ((looking-at re1) t)
11091 ((looking-at re2) nil)
11092 (t (error "Not at an org table")))))
11093 (re (if commented re1 re2))
11094 beg end)
11095 (save-excursion
11096 (beginning-of-line 1)
11097 (while (looking-at re) (beginning-of-line 0))
11098 (beginning-of-line 2)
11099 (setq beg (point))
11100 (while (looking-at re) (beginning-of-line 2))
11101 (setq end (point)))
11102 (comment-region beg end (if commented '(4) nil))))
11104 (defun orgtbl-insert-radio-table ()
11105 "Insert a radio table template appropriate for this major mode."
11106 (interactive)
11107 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11108 (txt (nth 1 e))
11109 name pos)
11110 (unless e (error "No radio table setup defined for %s" major-mode))
11111 (setq name (read-string "Table name: "))
11112 (while (string-match "%n" txt)
11113 (setq txt (replace-match name t t txt)))
11114 (or (bolp) (insert "\n"))
11115 (setq pos (point))
11116 (insert txt)
11117 (goto-char pos)))
11119 (defun org-get-param (params header i sym &optional hsym)
11120 "Get parameter value for symbol SYM.
11121 If this is a header line, actually get the value for the symbol with an
11122 additional \"h\" inserted after the colon.
11123 If the value is a protperty list, get the element for the current column.
11124 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11125 (let ((val (plist-get params sym)))
11126 (and hsym header (setq val (or (plist-get params hsym) val)))
11127 (if (consp val) (plist-get val i) val)))
11129 (defun orgtbl-to-generic (table params)
11130 "Convert the orgtbl-mode TABLE to some other format.
11131 This generic routine can be used for many standard cases.
11132 TABLE is a list, each entry either the symbol `hline' for a horizontal
11133 separator line, or a list of fields for that line.
11134 PARAMS is a property list of parameters that can influence the conversion.
11135 For the generic converter, some parameters are obligatory: You need to
11136 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11137 :splice, you must have :tstart and :tend.
11139 Valid parameters are
11141 :tstart String to start the table. Ignored when :splice is t.
11142 :tend String to end the table. Ignored when :splice is t.
11144 :splice When set to t, return only table body lines, don't wrap
11145 them into :tstart and :tend. Default is nil.
11147 :hline String to be inserted on horizontal separation lines.
11148 May be nil to ignore hlines.
11150 :lstart String to start a new table line.
11151 :lend String to end a table line
11152 :sep Separator between two fields
11153 :lfmt Format for entire line, with enough %s to capture all fields.
11154 If this is present, :lstart, :lend, and :sep are ignored.
11155 :fmt A format to be used to wrap the field, should contain
11156 %s for the original field value. For example, to wrap
11157 everything in dollars, you could use :fmt \"$%s$\".
11158 This may also be a property list with column numbers and
11159 formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11161 :hlstart :hlend :hlsep :hlfmt :hfmt
11162 Same as above, specific for the header lines in the table.
11163 All lines before the first hline are treated as header.
11164 If any of these is not present, the data line value is used.
11166 :efmt Use this format to print numbers with exponentials.
11167 The format should have %s twice for inserting mantissa
11168 and exponent, for example \"%s\\\\times10^{%s}\". This
11169 may also be a property list with column numbers and
11170 formats. :fmt will still be applied after :efmt.
11172 In addition to this, the parameters :skip and :skipcols are always handled
11173 directly by `orgtbl-send-table'. See manual."
11174 (interactive)
11175 (let* ((p params)
11176 (splicep (plist-get p :splice))
11177 (hline (plist-get p :hline))
11178 rtn line i fm efm lfmt h)
11180 ;; Do we have a header?
11181 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11182 (setq h t))
11184 ;; Put header
11185 (unless splicep
11186 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11188 ;; Now loop over all lines
11189 (while (setq line (pop table))
11190 (if (eq line 'hline)
11191 ;; A horizontal separator line
11192 (progn (if hline (push hline rtn))
11193 (setq h nil)) ; no longer in header
11194 ;; A normal line. Convert the fields, push line onto the result list
11195 (setq i 0)
11196 (setq line
11197 (mapcar
11198 (lambda (f)
11199 (setq i (1+ i)
11200 fm (org-get-param p h i :fmt :hfmt)
11201 efm (org-get-param p h i :efmt))
11202 (if (and efm (string-match orgtbl-exp-regexp f))
11203 (setq f (format
11204 efm (match-string 1 f) (match-string 2 f))))
11205 (if fm (setq f (format fm f)))
11207 line))
11208 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11209 (push (apply 'format lfmt line) rtn)
11210 (push (concat
11211 (org-get-param p h i :lstart :hlstart)
11212 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11213 (org-get-param p h i :lend :hlend))
11214 rtn))))
11216 (unless splicep
11217 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11219 (mapconcat 'identity (nreverse rtn) "\n")))
11221 (defun orgtbl-to-latex (table params)
11222 "Convert the orgtbl-mode TABLE to LaTeX.
11223 TABLE is a list, each entry either the symbol `hline' for a horizontal
11224 separator line, or a list of fields for that line.
11225 PARAMS is a property list of parameters that can influence the conversion.
11226 Supports all parameters from `orgtbl-to-generic'. Most important for
11227 LaTeX are:
11229 :splice When set to t, return only table body lines, don't wrap
11230 them into a tabular environment. Default is nil.
11232 :fmt A format to be used to wrap the field, should contain %s for the
11233 original field value. For example, to wrap everything in dollars,
11234 use :fmt \"$%s$\". This may also be a property list with column
11235 numbers and formats. for example :fmt (2 \"$%s$\" 4 \"%s%%\")
11237 :efmt Format for transforming numbers with exponentials. The format
11238 should have %s twice for inserting mantissa and exponent, for
11239 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11240 This may also be a property list with column numbers and formats.
11242 The general parameters :skip and :skipcols have already been applied when
11243 this function is called."
11244 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11245 org-table-last-alignment ""))
11246 (params2
11247 (list
11248 :tstart (concat "\\begin{tabular}{" alignment "}")
11249 :tend "\\end{tabular}"
11250 :lstart "" :lend " \\\\" :sep " & "
11251 :efmt "%s\\,(%s)" :hline "\\hline")))
11252 (orgtbl-to-generic table (org-combine-plists params2 params))))
11254 (defun orgtbl-to-html (table params)
11255 "Convert the orgtbl-mode TABLE to LaTeX.
11256 TABLE is a list, each entry either the symbol `hline' for a horizontal
11257 separator line, or a list of fields for that line.
11258 PARAMS is a property list of parameters that can influence the conversion.
11259 Currently this function recognizes the following parameters:
11261 :splice When set to t, return only table body lines, don't wrap
11262 them into a <table> environment. Default is nil.
11264 The general parameters :skip and :skipcols have already been applied when
11265 this function is called. The function does *not* use `orgtbl-to-generic',
11266 so you cannot specify parameters for it."
11267 (let* ((splicep (plist-get params :splice))
11268 html)
11269 ;; Just call the formatter we already have
11270 ;; We need to make text lines for it, so put the fields back together.
11271 (setq html (org-format-org-table-html
11272 (mapcar
11273 (lambda (x)
11274 (if (eq x 'hline)
11275 "|----+----|"
11276 (concat "| " (mapconcat 'identity x " | ") " |")))
11277 table)
11278 splicep))
11279 (if (string-match "\n+\\'" html)
11280 (setq html (replace-match "" t t html)))
11281 html))
11283 (defun orgtbl-to-texinfo (table params)
11284 "Convert the orgtbl-mode TABLE to TeXInfo.
11285 TABLE is a list, each entry either the symbol `hline' for a horizontal
11286 separator line, or a list of fields for that line.
11287 PARAMS is a property list of parameters that can influence the conversion.
11288 Supports all parameters from `orgtbl-to-generic'. Most important for
11289 TeXInfo are:
11291 :splice nil/t When set to t, return only table body lines, don't wrap
11292 them into a multitable environment. Default is nil.
11294 :fmt fmt A format to be used to wrap the field, should contain
11295 %s for the original field value. For example, to wrap
11296 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11297 This may also be a property list with column numbers and
11298 formats. for example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11300 :cf \"f1 f2..\" The column fractions for the table. Bye default these
11301 are computed automatically from the width of the columns
11302 under org-mode.
11304 The general parameters :skip and :skipcols have already been applied when
11305 this function is called."
11306 (let* ((total (float (apply '+ org-table-last-column-widths)))
11307 (colfrac (or (plist-get params :cf)
11308 (mapconcat
11309 (lambda (x) (format "%.3f" (/ (float x) total)))
11310 org-table-last-column-widths " ")))
11311 (params2
11312 (list
11313 :tstart (concat "@multitable @columnfractions " colfrac)
11314 :tend "@end multitable"
11315 :lstart "@item " :lend "" :sep " @tab "
11316 :hlstart "@headitem ")))
11317 (orgtbl-to-generic table (org-combine-plists params2 params))))
11319 ;;;; Link Stuff
11321 ;;; Link abbreviations
11323 (defun org-link-expand-abbrev (link)
11324 "Apply replacements as defined in `org-link-abbrev-alist."
11325 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
11326 (let* ((key (match-string 1 link))
11327 (as (or (assoc key org-link-abbrev-alist-local)
11328 (assoc key org-link-abbrev-alist)))
11329 (tag (and (match-end 2) (match-string 3 link)))
11330 rpl)
11331 (if (not as)
11332 link
11333 (setq rpl (cdr as))
11334 (cond
11335 ((symbolp rpl) (funcall rpl tag))
11336 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
11337 (t (concat rpl tag)))))
11338 link))
11340 ;;; Storing and inserting links
11342 (defvar org-insert-link-history nil
11343 "Minibuffer history for links inserted with `org-insert-link'.")
11345 (defvar org-stored-links nil
11346 "Contains the links stored with `org-store-link'.")
11348 (defvar org-store-link-plist nil
11349 "Plist with info about the most recently link created with `org-store-link'.")
11351 (defvar org-link-protocols nil
11352 "Link protocols added to Org-mode using `org-add-link-type'.")
11354 (defvar org-store-link-functions nil
11355 "List of functions that are called to create and store a link.
11356 Each function will be called in turn until one returns a non-nil
11357 value. Each function should check if it is responsible for creating
11358 this link (for example by looking at the major mode).
11359 If not, it must exit and return nil.
11360 If yes, it should return a non-nil value after a calling
11361 `org-store-link-props' with a list of properties and values.
11362 Special properties are:
11364 :type The link prefix. like \"http\". This must be given.
11365 :link The link, like \"http://www.astro.uva.nl/~dominik\".
11366 This is obligatory as well.
11367 :description Optional default description for the second pair
11368 of brackets in an Org-mode link. The user can still change
11369 this when inserting this link into an Org-mode buffer.
11371 In addition to these, any additional properties can be specified
11372 and then used in remember templates.")
11374 (defun org-add-link-type (type &optional follow publish)
11375 "Add TYPE to the list of `org-link-types'.
11376 Re-compute all regular expressions depending on `org-link-types'
11377 FOLLOW and PUBLISH are two functions. Both take the link path as
11378 an argument.
11379 FOLLOW should do whatever is necessary to follow the link, for example
11380 to find a file or display a mail message.
11381 PUBLISH takes the path and retuns the string that should be used when
11382 this document is published."
11383 (add-to-list 'org-link-types type t)
11384 (org-make-link-regexps)
11385 (add-to-list 'org-link-protocols
11386 (list type follow publish)))
11388 (defun org-add-agenda-custom-command (entry)
11389 "Replace or add a command in `org-agenda-custom-commands'.
11390 This is mostly for hacking and trying a new command - once the command
11391 works you probably want to add it to `org-agenda-custom-commands' for good."
11392 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
11393 (if ass
11394 (setcdr ass (cdr entry))
11395 (push entry org-agenda-custom-commands))))
11397 ;;;###autoload
11398 (defun org-store-link (arg)
11399 "\\<org-mode-map>Store an org-link to the current location.
11400 This link can later be inserted into an org-buffer with
11401 \\[org-insert-link].
11402 For some link types, a prefix arg is interpreted:
11403 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
11404 For file links, arg negates `org-context-in-file-links'."
11405 (interactive "P")
11406 (setq org-store-link-plist nil) ; reset
11407 (let (link cpltxt desc description search txt)
11408 (cond
11410 ((run-hook-with-args-until-success 'org-store-link-functions)
11411 (setq link (plist-get org-store-link-plist :link)
11412 desc (or (plist-get org-store-link-plist :description) link)))
11414 ((eq major-mode 'bbdb-mode)
11415 (let ((name (bbdb-record-name (bbdb-current-record)))
11416 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
11417 (setq cpltxt (concat "bbdb:" (or name company))
11418 link (org-make-link cpltxt))
11419 (org-store-link-props :type "bbdb" :name name :company company)))
11421 ((eq major-mode 'Info-mode)
11422 (setq link (org-make-link "info:"
11423 (file-name-nondirectory Info-current-file)
11424 ":" Info-current-node))
11425 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
11426 ":" Info-current-node))
11427 (org-store-link-props :type "info" :file Info-current-file
11428 :node Info-current-node))
11430 ((eq major-mode 'calendar-mode)
11431 (let ((cd (calendar-cursor-to-date)))
11432 (setq link
11433 (format-time-string
11434 (car org-time-stamp-formats)
11435 (apply 'encode-time
11436 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
11437 nil nil nil))))
11438 (org-store-link-props :type "calendar" :date cd)))
11440 ((or (eq major-mode 'vm-summary-mode)
11441 (eq major-mode 'vm-presentation-mode))
11442 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
11443 (vm-follow-summary-cursor)
11444 (save-excursion
11445 (vm-select-folder-buffer)
11446 (let* ((message (car vm-message-pointer))
11447 (folder buffer-file-name)
11448 (subject (vm-su-subject message))
11449 (to (vm-get-header-contents message "To"))
11450 (from (vm-get-header-contents message "From"))
11451 (message-id (vm-su-message-id message)))
11452 (org-store-link-props :type "vm" :from from :to to :subject subject
11453 :message-id message-id)
11454 (setq message-id (org-remove-angle-brackets message-id))
11455 (setq folder (abbreviate-file-name folder))
11456 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
11457 folder)
11458 (setq folder (replace-match "" t t folder)))
11459 (setq cpltxt (org-email-link-description))
11460 (setq link (org-make-link "vm:" folder "#" message-id)))))
11462 ((eq major-mode 'wl-summary-mode)
11463 (let* ((msgnum (wl-summary-message-number))
11464 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
11465 msgnum 'message-id))
11466 (wl-message-entity
11467 (if (fboundp 'elmo-message-entity)
11468 (elmo-message-entity
11469 wl-summary-buffer-elmo-folder msgnum)
11470 (elmo-msgdb-overview-get-entity
11471 msgnum (wl-summary-buffer-msgdb))))
11472 (from (wl-summary-line-from))
11473 (to (elmo-message-entity-field wl-message-entity 'to))
11474 (subject (let (wl-thr-indent-string wl-parent-message-entity)
11475 (wl-summary-line-subject))))
11476 (org-store-link-props :type "wl" :from from :to to
11477 :subject subject :message-id message-id)
11478 (setq message-id (org-remove-angle-brackets message-id))
11479 (setq cpltxt (org-email-link-description))
11480 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
11481 "#" message-id))))
11483 ((or (equal major-mode 'mh-folder-mode)
11484 (equal major-mode 'mh-show-mode))
11485 (let ((from (org-mhe-get-header "From:"))
11486 (to (org-mhe-get-header "To:"))
11487 (message-id (org-mhe-get-header "Message-Id:"))
11488 (subject (org-mhe-get-header "Subject:")))
11489 (org-store-link-props :type "mh" :from from :to to
11490 :subject subject :message-id message-id)
11491 (setq cpltxt (org-email-link-description))
11492 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
11493 (org-remove-angle-brackets message-id)))))
11495 ((eq major-mode 'rmail-mode)
11496 (save-excursion
11497 (save-restriction
11498 (rmail-narrow-to-non-pruned-header)
11499 (let ((folder buffer-file-name)
11500 (message-id (mail-fetch-field "message-id"))
11501 (from (mail-fetch-field "from"))
11502 (to (mail-fetch-field "to"))
11503 (subject (mail-fetch-field "subject")))
11504 (org-store-link-props
11505 :type "rmail" :from from :to to
11506 :subject subject :message-id message-id)
11507 (setq message-id (org-remove-angle-brackets message-id))
11508 (setq cpltxt (org-email-link-description))
11509 (setq link (org-make-link "rmail:" folder "#" message-id))))))
11511 ((eq major-mode 'gnus-group-mode)
11512 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
11513 (gnus-group-group-name)) ; version
11514 ((fboundp 'gnus-group-name)
11515 (gnus-group-name))
11516 (t "???"))))
11517 (unless group (error "Not on a group"))
11518 (org-store-link-props :type "gnus" :group group)
11519 (setq cpltxt (concat
11520 (if (org-xor arg org-usenet-links-prefer-google)
11521 "http://groups.google.com/groups?group="
11522 "gnus:")
11523 group)
11524 link (org-make-link cpltxt))))
11526 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
11527 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
11528 (let* ((group gnus-newsgroup-name)
11529 (article (gnus-summary-article-number))
11530 (header (gnus-summary-article-header article))
11531 (from (mail-header-from header))
11532 (message-id (mail-header-id header))
11533 (date (mail-header-date header))
11534 (subject (gnus-summary-subject-string)))
11535 (org-store-link-props :type "gnus" :from from :subject subject
11536 :message-id message-id :group group)
11537 (setq cpltxt (org-email-link-description))
11538 (if (org-xor arg org-usenet-links-prefer-google)
11539 (setq link
11540 (concat
11541 cpltxt "\n "
11542 (format "http://groups.google.com/groups?as_umsgid=%s"
11543 (org-fixup-message-id-for-http message-id))))
11544 (setq link (org-make-link "gnus:" group
11545 "#" (number-to-string article))))))
11547 ((eq major-mode 'w3-mode)
11548 (setq cpltxt (url-view-url t)
11549 link (org-make-link cpltxt))
11550 (org-store-link-props :type "w3" :url (url-view-url t)))
11552 ((eq major-mode 'w3m-mode)
11553 (setq cpltxt (or w3m-current-title w3m-current-url)
11554 link (org-make-link w3m-current-url))
11555 (org-store-link-props :type "w3m" :url (url-view-url t)))
11557 ((setq search (run-hook-with-args-until-success
11558 'org-create-file-search-functions))
11559 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
11560 "::" search))
11561 (setq cpltxt (or description link)))
11563 ((eq major-mode 'image-mode)
11564 (setq cpltxt (concat "file:"
11565 (abbreviate-file-name buffer-file-name))
11566 link (org-make-link cpltxt))
11567 (org-store-link-props :type "image" :file buffer-file-name))
11569 ((eq major-mode 'dired-mode)
11570 ;; link to the file in the current line
11571 (setq cpltxt (concat "file:"
11572 (abbreviate-file-name
11573 (expand-file-name
11574 (dired-get-filename nil t))))
11575 link (org-make-link cpltxt)))
11577 ((and buffer-file-name (org-mode-p))
11578 ;; Just link to current headline
11579 (setq cpltxt (concat "file:"
11580 (abbreviate-file-name buffer-file-name)))
11581 ;; Add a context search string
11582 (when (org-xor org-context-in-file-links arg)
11583 ;; Check if we are on a target
11584 (if (org-in-regexp "<<\\(.*?\\)>>")
11585 (setq cpltxt (concat cpltxt "::" (match-string 1)))
11586 (setq txt (cond
11587 ((org-on-heading-p) nil)
11588 ((org-region-active-p)
11589 (buffer-substring (region-beginning) (region-end)))
11590 (t (buffer-substring (point-at-bol) (point-at-eol)))))
11591 (when (or (null txt) (string-match "\\S-" txt))
11592 (setq cpltxt
11593 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11594 desc "NONE"))))
11595 (if (string-match "::\\'" cpltxt)
11596 (setq cpltxt (substring cpltxt 0 -2)))
11597 (setq link (org-make-link cpltxt)))
11599 ((buffer-file-name (buffer-base-buffer))
11600 ;; Just link to this file here.
11601 (setq cpltxt (concat "file:"
11602 (abbreviate-file-name
11603 (buffer-file-name (buffer-base-buffer)))))
11604 ;; Add a context string
11605 (when (org-xor org-context-in-file-links arg)
11606 (setq txt (if (org-region-active-p)
11607 (buffer-substring (region-beginning) (region-end))
11608 (buffer-substring (point-at-bol) (point-at-eol))))
11609 ;; Only use search option if there is some text.
11610 (when (string-match "\\S-" txt)
11611 (setq cpltxt
11612 (concat cpltxt "::" (org-make-org-heading-search-string txt))
11613 desc "NONE")))
11614 (setq link (org-make-link cpltxt)))
11616 ((interactive-p)
11617 (error "Cannot link to a buffer which is not visiting a file"))
11619 (t (setq link nil)))
11621 (if (consp link) (setq cpltxt (car link) link (cdr link)))
11622 (setq link (or link cpltxt)
11623 desc (or desc cpltxt))
11624 (if (equal desc "NONE") (setq desc nil))
11626 (if (and (interactive-p) link)
11627 (progn
11628 (setq org-stored-links
11629 (cons (list link desc) org-stored-links))
11630 (message "Stored: %s" (or desc link)))
11631 (and link (org-make-link-string link desc)))))
11633 (defun org-store-link-props (&rest plist)
11634 "Store link properties, extract names and addresses."
11635 (let (x adr)
11636 (when (setq x (plist-get plist :from))
11637 (setq adr (mail-extract-address-components x))
11638 (plist-put plist :fromname (car adr))
11639 (plist-put plist :fromaddress (nth 1 adr)))
11640 (when (setq x (plist-get plist :to))
11641 (setq adr (mail-extract-address-components x))
11642 (plist-put plist :toname (car adr))
11643 (plist-put plist :toaddress (nth 1 adr))))
11644 (let ((from (plist-get plist :from))
11645 (to (plist-get plist :to)))
11646 (when (and from to org-from-is-user-regexp)
11647 (plist-put plist :fromto
11648 (if (string-match org-from-is-user-regexp from)
11649 (concat "to %t")
11650 (concat "from %f")))))
11651 (setq org-store-link-plist plist))
11653 (defun org-email-link-description (&optional fmt)
11654 "Return the description part of an email link.
11655 This takes information from `org-store-link-plist' and formats it
11656 according to FMT (default from `org-email-link-description-format')."
11657 (setq fmt (or fmt org-email-link-description-format))
11658 (let* ((p org-store-link-plist)
11659 (to (plist-get p :toaddress))
11660 (from (plist-get p :fromaddress))
11661 (table
11662 (list
11663 (cons "%c" (plist-get p :fromto))
11664 (cons "%F" (plist-get p :from))
11665 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
11666 (cons "%T" (plist-get p :to))
11667 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
11668 (cons "%s" (plist-get p :subject))
11669 (cons "%m" (plist-get p :message-id)))))
11670 (when (string-match "%c" fmt)
11671 ;; Check if the user wrote this message
11672 (if (and org-from-is-user-regexp from to
11673 (save-match-data (string-match org-from-is-user-regexp from)))
11674 (setq fmt (replace-match "to %t" t t fmt))
11675 (setq fmt (replace-match "from %f" t t fmt))))
11676 (org-replace-escapes fmt table)))
11678 (defun org-make-org-heading-search-string (&optional string heading)
11679 "Make search string for STRING or current headline."
11680 (interactive)
11681 (let ((s (or string (org-get-heading))))
11682 (unless (and string (not heading))
11683 ;; We are using a headline, clean up garbage in there.
11684 (if (string-match org-todo-regexp s)
11685 (setq s (replace-match "" t t s)))
11686 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
11687 (setq s (replace-match "" t t s)))
11688 (setq s (org-trim s))
11689 (if (string-match (concat "^\\(" org-quote-string "\\|"
11690 org-comment-string "\\)") s)
11691 (setq s (replace-match "" t t s)))
11692 (while (string-match org-ts-regexp s)
11693 (setq s (replace-match "" t t s))))
11694 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
11695 (setq s (replace-match " " t t s)))
11696 (or string (setq s (concat "*" s))) ; Add * for headlines
11697 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
11699 (defun org-make-link (&rest strings)
11700 "Concatenate STRINGS."
11701 (apply 'concat strings))
11703 (defun org-make-link-string (link &optional description)
11704 "Make a link with brackets, consisting of LINK and DESCRIPTION."
11705 (unless (string-match "\\S-" link)
11706 (error "Empty link"))
11707 (when (stringp description)
11708 ;; Remove brackets from the description, they are fatal.
11709 (while (string-match "\\[\\|\\]" description)
11710 (setq description (replace-match "" t t description))))
11711 (when (equal (org-link-escape link) description)
11712 ;; No description needed, it is identical
11713 (setq description nil))
11714 (when (and (not description)
11715 (not (equal link (org-link-escape link))))
11716 (setq description link))
11717 (concat "[[" (org-link-escape link) "]"
11718 (if description (concat "[" description "]") "")
11719 "]"))
11721 (defconst org-link-escape-chars
11722 '((?\ . "%20")
11723 (?\[ . "%5B")
11724 (?\] . "%5d")
11725 (?\340 . "%E0") ; `a
11726 (?\342 . "%E2") ; ^a
11727 (?\347 . "%E7") ; ,c
11728 (?\350 . "%E8") ; `e
11729 (?\351 . "%E9") ; 'e
11730 (?\352 . "%EA") ; ^e
11731 (?\356 . "%EE") ; ^i
11732 (?\364 . "%F4") ; ^o
11733 (?\371 . "%F9") ; `u
11734 (?\373 . "%FB") ; ^u
11735 (?\; . "%3B")
11736 (?? . "%3F")
11737 (?= . "%3D")
11738 (?+ . "%2B")
11740 "Association list of escapes for some characters problematic in links.
11741 This is the list that is used for internal purposes.")
11743 (defconst org-link-escape-chars-browser
11744 '((?\ . "%20")) ; 32 for the SPC char
11746 "Association list of escapes for some characters problematic in links.
11747 This is the list that is used before handing over to the browser.")
11749 (defun org-link-escape (text &optional table)
11750 "Escape charaters in TEXT that are problematic for links."
11751 (setq table (or table org-link-escape-chars))
11752 (when text
11753 (let ((re (mapconcat (lambda (x) (regexp-quote
11754 (char-to-string (car x))))
11755 table "\\|")))
11756 (while (string-match re text)
11757 (setq text
11758 (replace-match
11759 (cdr (assoc (string-to-char (match-string 0 text))
11760 table))
11761 t t text)))
11762 text)))
11764 (defun org-link-unescape (text &optional table)
11765 "Reverse the action of `org-link-escape'."
11766 (setq table (or table org-link-escape-chars))
11767 (when text
11768 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
11769 table "\\|")))
11770 (while (string-match re text)
11771 (setq text
11772 (replace-match
11773 (char-to-string (car (rassoc (match-string 0 text) table)))
11774 t t text)))
11775 text)))
11777 (defun org-xor (a b)
11778 "Exclusive or."
11779 (if a (not b) b))
11781 (defun org-get-header (header)
11782 "Find a header field in the current buffer."
11783 (save-excursion
11784 (goto-char (point-min))
11785 (let ((case-fold-search t) s)
11786 (cond
11787 ((eq header 'from)
11788 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
11789 (setq s (match-string 1)))
11790 (while (string-match "\"" s)
11791 (setq s (replace-match "" t t s)))
11792 (if (string-match "[<(].*" s)
11793 (setq s (replace-match "" t t s))))
11794 ((eq header 'message-id)
11795 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
11796 (setq s (match-string 1))))
11797 ((eq header 'subject)
11798 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
11799 (setq s (match-string 1)))))
11800 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
11801 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
11802 s)))
11805 (defun org-fixup-message-id-for-http (s)
11806 "Replace special characters in a message id, so it can be used in an http query."
11807 (while (string-match "<" s)
11808 (setq s (replace-match "%3C" t t s)))
11809 (while (string-match ">" s)
11810 (setq s (replace-match "%3E" t t s)))
11811 (while (string-match "@" s)
11812 (setq s (replace-match "%40" t t s)))
11815 ;;;###autoload
11816 (defun org-insert-link-global ()
11817 "Insert a link like Org-mode does.
11818 This command can be called in any mode to insert a link in Org-mode syntax."
11819 (interactive)
11820 (org-run-like-in-org-mode 'org-insert-link))
11822 (defun org-insert-link (&optional complete-file)
11823 "Insert a link. At the prompt, enter the link.
11825 Completion can be used to select a link previously stored with
11826 `org-store-link'. When the empty string is entered (i.e. if you just
11827 press RET at the prompt), the link defaults to the most recently
11828 stored link. As SPC triggers completion in the minibuffer, you need to
11829 use M-SPC or C-q SPC to force the insertion of a space character.
11831 You will also be prompted for a description, and if one is given, it will
11832 be displayed in the buffer instead of the link.
11834 If there is already a link at point, this command will allow you to edit link
11835 and description parts.
11837 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
11838 selected using completion. The path to the file will be relative to
11839 the current directory if the file is in the current directory or a
11840 subdirectory. Otherwise, the link will be the absolute path as
11841 completed in the minibuffer (i.e. normally ~/path/to/file).
11843 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
11844 is in the current directory or below.
11845 With three \\[universal-argument] prefixes, negate the meaning of
11846 `org-keep-stored-link-after-insertion'."
11847 (interactive "P")
11848 (let* ((wcf (current-window-configuration))
11849 (region (if (org-region-active-p)
11850 (buffer-substring (region-beginning) (region-end))))
11851 (remove (and region (list (region-beginning) (region-end))))
11852 (desc region)
11853 tmphist ; byte-compile incorrectly complains about this
11854 link entry file)
11855 (cond
11856 ((org-in-regexp org-bracket-link-regexp 1)
11857 ;; We do have a link at point, and we are going to edit it.
11858 (setq remove (list (match-beginning 0) (match-end 0)))
11859 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
11860 (setq link (read-string "Link: "
11861 (org-link-unescape
11862 (org-match-string-no-properties 1)))))
11863 ((or (org-in-regexp org-angle-link-re)
11864 (org-in-regexp org-plain-link-re))
11865 ;; Convert to bracket link
11866 (setq remove (list (match-beginning 0) (match-end 0))
11867 link (read-string "Link: "
11868 (org-remove-angle-brackets (match-string 0)))))
11869 ((equal complete-file '(4))
11870 ;; Completing read for file names.
11871 (setq file (read-file-name "File: "))
11872 (let ((pwd (file-name-as-directory (expand-file-name ".")))
11873 (pwd1 (file-name-as-directory (abbreviate-file-name
11874 (expand-file-name ".")))))
11875 (cond
11876 ((equal complete-file '(16))
11877 (setq link (org-make-link
11878 "file:"
11879 (abbreviate-file-name (expand-file-name file)))))
11880 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
11881 (setq link (org-make-link "file:" (match-string 1 file))))
11882 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
11883 (expand-file-name file))
11884 (setq link (org-make-link
11885 "file:" (match-string 1 (expand-file-name file)))))
11886 (t (setq link (org-make-link "file:" file))))))
11888 ;; Read link, with completion for stored links.
11889 (with-output-to-temp-buffer "*Org Links*"
11890 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
11891 (when org-stored-links
11892 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
11893 (princ (mapconcat
11894 (lambda (x)
11895 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
11896 (reverse org-stored-links) "\n"))))
11897 (let ((cw (selected-window)))
11898 (select-window (get-buffer-window "*Org Links*"))
11899 (shrink-window-if-larger-than-buffer)
11900 (setq truncate-lines t)
11901 (select-window cw))
11902 ;; Fake a link history, containing the stored links.
11903 (setq tmphist (append (mapcar 'car org-stored-links)
11904 org-insert-link-history))
11905 (unwind-protect
11906 (setq link (org-completing-read
11907 "Link: "
11908 (append
11909 (mapcar (lambda (x) (list (concat (car x) ":")))
11910 (append org-link-abbrev-alist-local org-link-abbrev-alist))
11911 (mapcar (lambda (x) (list (concat x ":")))
11912 org-link-types))
11913 nil nil nil
11914 'tmphist
11915 (or (car (car org-stored-links)))))
11916 (set-window-configuration wcf)
11917 (kill-buffer "*Org Links*"))
11918 (setq entry (assoc link org-stored-links))
11919 (or entry (push link org-insert-link-history))
11920 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
11921 (not org-keep-stored-link-after-insertion))
11922 (setq org-stored-links (delq (assoc link org-stored-links)
11923 org-stored-links)))
11924 (setq desc (or desc (nth 1 entry)))))
11926 (if (string-match org-plain-link-re link)
11927 ;; URL-like link, normalize the use of angular brackets.
11928 (setq link (org-make-link (org-remove-angle-brackets link))))
11930 ;; Check if we are linking to the current file with a search option
11931 ;; If yes, simplify the link by using only the search option.
11932 (when (and buffer-file-name
11933 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
11934 (let* ((path (match-string 1 link))
11935 (case-fold-search nil)
11936 (search (match-string 2 link)))
11937 (save-match-data
11938 (if (equal (file-truename buffer-file-name) (file-truename path))
11939 ;; We are linking to this same file, with a search option
11940 (setq link search)))))
11942 ;; Check if we can/should use a relative path. If yes, simplify the link
11943 (when (string-match "\\<file:\\(.*\\)" link)
11944 (let* ((path (match-string 1 link))
11945 (origpath path)
11946 (desc-is-link (equal link desc))
11947 (case-fold-search nil))
11948 (cond
11949 ((eq org-link-file-path-type 'absolute)
11950 (setq path (abbreviate-file-name (expand-file-name path))))
11951 ((eq org-link-file-path-type 'noabbrev)
11952 (setq path (expand-file-name path)))
11953 ((eq org-link-file-path-type 'relative)
11954 (setq path (file-relative-name path)))
11956 (save-match-data
11957 (if (string-match (concat "^" (regexp-quote
11958 (file-name-as-directory
11959 (expand-file-name "."))))
11960 (expand-file-name path))
11961 ;; We are linking a file with relative path name.
11962 (setq path (substring (expand-file-name path)
11963 (match-end 0)))))))
11964 (setq link (concat "file:" path))
11965 (if (equal desc origpath)
11966 (setq desc path))))
11968 (setq desc (read-string "Description: " desc))
11969 (unless (string-match "\\S-" desc) (setq desc nil))
11970 (if remove (apply 'delete-region remove))
11971 (insert (org-make-link-string link desc))))
11973 (defun org-completing-read (&rest args)
11974 (let ((minibuffer-local-completion-map
11975 (copy-keymap minibuffer-local-completion-map)))
11976 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
11977 (apply 'completing-read args)))
11979 ;;; Opening/following a link
11980 (defvar org-link-search-failed nil)
11982 (defun org-next-link ()
11983 "Move forward to the next link.
11984 If the link is in hidden text, expose it."
11985 (interactive)
11986 (when (and org-link-search-failed (eq this-command last-command))
11987 (goto-char (point-min))
11988 (message "Link search wrapped back to beginning of buffer"))
11989 (setq org-link-search-failed nil)
11990 (let* ((pos (point))
11991 (ct (org-context))
11992 (a (assoc :link ct)))
11993 (if a (goto-char (nth 2 a)))
11994 (if (re-search-forward org-any-link-re nil t)
11995 (progn
11996 (goto-char (match-beginning 0))
11997 (if (org-invisible-p) (org-show-context)))
11998 (goto-char pos)
11999 (setq org-link-search-failed t)
12000 (error "No further link found"))))
12002 (defun org-previous-link ()
12003 "Move backward to the previous link.
12004 If the link is in hidden text, expose it."
12005 (interactive)
12006 (when (and org-link-search-failed (eq this-command last-command))
12007 (goto-char (point-max))
12008 (message "Link search wrapped back to end of buffer"))
12009 (setq org-link-search-failed nil)
12010 (let* ((pos (point))
12011 (ct (org-context))
12012 (a (assoc :link ct)))
12013 (if a (goto-char (nth 1 a)))
12014 (if (re-search-backward org-any-link-re nil t)
12015 (progn
12016 (goto-char (match-beginning 0))
12017 (if (org-invisible-p) (org-show-context)))
12018 (goto-char pos)
12019 (setq org-link-search-failed t)
12020 (error "No further link found"))))
12022 (defun org-find-file-at-mouse (ev)
12023 "Open file link or URL at mouse."
12024 (interactive "e")
12025 (mouse-set-point ev)
12026 (org-open-at-point 'in-emacs))
12028 (defun org-open-at-mouse (ev)
12029 "Open file link or URL at mouse."
12030 (interactive "e")
12031 (mouse-set-point ev)
12032 (org-open-at-point))
12034 (defvar org-window-config-before-follow-link nil
12035 "The window configuration before following a link.
12036 This is saved in case the need arises to restore it.")
12038 (defvar org-open-link-marker (make-marker)
12039 "Marker pointing to the location where `org-open-at-point; was called.")
12041 ;;;###autoload
12042 (defun org-open-at-point-global ()
12043 "Follow a link like Org-mode does.
12044 This command can be called in any mode to follow a link that has
12045 Org-mode syntax."
12046 (interactive)
12047 (org-run-like-in-org-mode 'org-open-at-point))
12049 (defun org-open-at-point (&optional in-emacs)
12050 "Open link at or after point.
12051 If there is no link at point, this function will search forward up to
12052 the end of the current subtree.
12053 Normally, files will be opened by an appropriate application. If the
12054 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12055 (interactive "P")
12056 (move-marker org-open-link-marker (point))
12057 (setq org-window-config-before-follow-link (current-window-configuration))
12058 (org-remove-occur-highlights nil nil t)
12059 (if (org-at-timestamp-p t)
12060 (org-follow-timestamp-link)
12061 (let (type path link line search (pos (point)))
12062 (catch 'match
12063 (save-excursion
12064 (skip-chars-forward "^]\n\r")
12065 (when (org-in-regexp org-bracket-link-regexp)
12066 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12067 (while (string-match " *\n *" link)
12068 (setq link (replace-match " " t t link)))
12069 (setq link (org-link-expand-abbrev link))
12070 (if (string-match org-link-re-with-space2 link)
12071 (setq type (match-string 1 link) path (match-string 2 link))
12072 (setq type "thisfile" path link))
12073 (throw 'match t)))
12075 (when (get-text-property (point) 'org-linked-text)
12076 (setq type "thisfile"
12077 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12078 (1+ (point)) (point))
12079 path (buffer-substring
12080 (previous-single-property-change pos 'org-linked-text)
12081 (next-single-property-change pos 'org-linked-text)))
12082 (throw 'match t))
12084 (save-excursion
12085 (when (or (org-in-regexp org-angle-link-re)
12086 (org-in-regexp org-plain-link-re))
12087 (setq type (match-string 1) path (match-string 2))
12088 (throw 'match t)))
12089 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12090 (setq type "tree-match"
12091 path (match-string 1))
12092 (throw 'match t))
12093 (save-excursion
12094 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12095 (setq type "tags"
12096 path (match-string 1))
12097 (while (string-match ":" path)
12098 (setq path (replace-match "+" t t path)))
12099 (throw 'match t))))
12100 (unless path
12101 (error "No link found"))
12102 ;; Remove any trailing spaces in path
12103 (if (string-match " +\\'" path)
12104 (setq path (replace-match "" t t path)))
12106 (cond
12108 ((assoc type org-link-protocols)
12109 (funcall (nth 1 (assoc type org-link-protocols)) path))
12111 ((equal type "mailto")
12112 (let ((cmd (car org-link-mailto-program))
12113 (args (cdr org-link-mailto-program)) args1
12114 (address path) (subject "") a)
12115 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12116 (setq address (match-string 1 path)
12117 subject (org-link-escape (match-string 2 path))))
12118 (while args
12119 (cond
12120 ((not (stringp (car args))) (push (pop args) args1))
12121 (t (setq a (pop args))
12122 (if (string-match "%a" a)
12123 (setq a (replace-match address t t a)))
12124 (if (string-match "%s" a)
12125 (setq a (replace-match subject t t a)))
12126 (push a args1))))
12127 (apply cmd (nreverse args1))))
12129 ((member type '("http" "https" "ftp" "news"))
12130 (browse-url (concat type ":" (org-link-escape
12131 path org-link-escape-chars-browser))))
12133 ((string= type "tags")
12134 (org-tags-view in-emacs path))
12135 ((string= type "thisfile")
12136 (if in-emacs
12137 (switch-to-buffer-other-window
12138 (org-get-buffer-for-internal-link (current-buffer)))
12139 (org-mark-ring-push))
12140 (let ((cmd `(org-link-search
12141 ,path
12142 ,(cond ((equal in-emacs '(4)) 'occur)
12143 ((equal in-emacs '(16)) 'org-occur)
12144 (t nil))
12145 ,pos)))
12146 (condition-case nil (eval cmd)
12147 (error (progn (widen) (eval cmd))))))
12149 ((string= type "tree-match")
12150 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12152 ((string= type "file")
12153 (if (string-match "::\\([0-9]+\\)\\'" path)
12154 (setq line (string-to-number (match-string 1 path))
12155 path (substring path 0 (match-beginning 0)))
12156 (if (string-match "::\\(.+\\)\\'" path)
12157 (setq search (match-string 1 path)
12158 path (substring path 0 (match-beginning 0)))))
12159 (if (string-match "[*?{]" (file-name-nondirectory path))
12160 (dired path)
12161 (org-open-file path in-emacs line search)))
12163 ((string= type "news")
12164 (org-follow-gnus-link path))
12166 ((string= type "bbdb")
12167 (org-follow-bbdb-link path))
12169 ((string= type "info")
12170 (org-follow-info-link path))
12172 ((string= type "gnus")
12173 (let (group article)
12174 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12175 (error "Error in Gnus link"))
12176 (setq group (match-string 1 path)
12177 article (match-string 3 path))
12178 (org-follow-gnus-link group article)))
12180 ((string= type "vm")
12181 (let (folder article)
12182 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12183 (error "Error in VM link"))
12184 (setq folder (match-string 1 path)
12185 article (match-string 3 path))
12186 ;; in-emacs is the prefix arg, will be interpreted as read-only
12187 (org-follow-vm-link folder article in-emacs)))
12189 ((string= type "wl")
12190 (let (folder article)
12191 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12192 (error "Error in Wanderlust link"))
12193 (setq folder (match-string 1 path)
12194 article (match-string 3 path))
12195 (org-follow-wl-link folder article)))
12197 ((string= type "mhe")
12198 (let (folder article)
12199 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12200 (error "Error in MHE link"))
12201 (setq folder (match-string 1 path)
12202 article (match-string 3 path))
12203 (org-follow-mhe-link folder article)))
12205 ((string= type "rmail")
12206 (let (folder article)
12207 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12208 (error "Error in RMAIL link"))
12209 (setq folder (match-string 1 path)
12210 article (match-string 3 path))
12211 (org-follow-rmail-link folder article)))
12213 ((string= type "shell")
12214 (let ((cmd path))
12215 ;; The following is only for backward compatibility
12216 (while (string-match "@{" cmd) (setq cmd (replace-match "<" t t cmd)))
12217 (while (string-match "@}" cmd) (setq cmd (replace-match ">" t t cmd)))
12218 (if (or (not org-confirm-shell-link-function)
12219 (funcall org-confirm-shell-link-function
12220 (format "Execute \"%s\" in shell? "
12221 (org-add-props cmd nil
12222 'face 'org-warning))))
12223 (progn
12224 (message "Executing %s" cmd)
12225 (shell-command cmd))
12226 (error "Abort"))))
12228 ((string= type "elisp")
12229 (let ((cmd path))
12230 (if (or (not org-confirm-elisp-link-function)
12231 (funcall org-confirm-elisp-link-function
12232 (format "Execute \"%s\" as elisp? "
12233 (org-add-props cmd nil
12234 'face 'org-warning))))
12235 (message "%s => %s" cmd (eval (read cmd)))
12236 (error "Abort"))))
12239 (browse-url-at-point)))))
12240 (move-marker org-open-link-marker nil))
12242 ;;; File search
12244 (defvar org-create-file-search-functions nil
12245 "List of functions to construct the right search string for a file link.
12246 These functions are called in turn with point at the location to
12247 which the link should point.
12249 A function in the hook should first test if it would like to
12250 handle this file type, for example by checking the major-mode or
12251 the file extension. If it decides not to handle this file, it
12252 should just return nil to give other functions a chance. If it
12253 does handle the file, it must return the search string to be used
12254 when following the link. The search string will be part of the
12255 file link, given after a double colon, and `org-open-at-point'
12256 will automatically search for it. If special measures must be
12257 taken to make the search successful, another function should be
12258 added to the companion hook `org-execute-file-search-functions',
12259 which see.
12261 A function in this hook may also use `setq' to set the variable
12262 `description' to provide a suggestion for the descriptive text to
12263 be used for this link when it gets inserted into an Org-mode
12264 buffer with \\[org-insert-link].")
12266 (defvar org-execute-file-search-functions nil
12267 "List of functions to execute a file search triggered by a link.
12269 Functions added to this hook must accept a single argument, the
12270 search string that was part of the file link, the part after the
12271 double colon. The function must first check if it would like to
12272 handle this search, for example by checking the major-mode or the
12273 file extension. If it decides not to handle this search, it
12274 should just return nil to give other functions a chance. If it
12275 does handle the search, it must return a non-nil value to keep
12276 other functions from trying.
12278 Each function can access the current prefix argument through the
12279 variable `current-prefix-argument'. Note that a single prefix is
12280 used to force opening a link in Emacs, so it may be good to only
12281 use a numeric or double prefix to guide the search function.
12283 In case this is needed, a function in this hook can also restore
12284 the window configuration before `org-open-at-point' was called using:
12286 (set-window-configuration org-window-config-before-follow-link)")
12288 (defun org-link-search (s &optional type avoid-pos)
12289 "Search for a link search option.
12290 If S is surrounded by forward slashes, it is interpreted as a
12291 regular expression. In org-mode files, this will create an `org-occur'
12292 sparse tree. In ordinary files, `occur' will be used to list matches.
12293 If the current buffer is in `dired-mode', grep will be used to search
12294 in all files. If AVOID-POS is given, ignore matches near that position."
12295 (let ((case-fold-search t)
12296 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12297 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12298 (append '(("") (" ") ("\t") ("\n"))
12299 org-emphasis-alist)
12300 "\\|") "\\)"))
12301 (pos (point))
12302 (pre "") (post "")
12303 words re0 re1 re2 re3 re4 re5 re2a reall)
12304 (cond
12305 ;; First check if there are any special
12306 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12307 ;; Now try the builtin stuff
12308 ((save-excursion
12309 (goto-char (point-min))
12310 (and
12311 (re-search-forward
12312 (concat "<<" (regexp-quote s0) ">>") nil t)
12313 (setq pos (match-beginning 0))))
12314 ;; There is an exact target for this
12315 (goto-char pos))
12316 ((string-match "^/\\(.*\\)/$" s)
12317 ;; A regular expression
12318 (cond
12319 ((org-mode-p)
12320 (org-occur (match-string 1 s)))
12321 ;;((eq major-mode 'dired-mode)
12322 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
12323 (t (org-do-occur (match-string 1 s)))))
12325 ;; A normal search strings
12326 (when (equal (string-to-char s) ?*)
12327 ;; Anchor on headlines, post may include tags.
12328 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
12329 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
12330 s (substring s 1)))
12331 (remove-text-properties
12332 0 (length s)
12333 '(face nil mouse-face nil keymap nil fontified nil) s)
12334 ;; Make a series of regular expressions to find a match
12335 (setq words (org-split-string s "[ \n\r\t]+")
12336 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
12337 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
12338 "\\)" markers)
12339 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
12340 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
12341 re1 (concat pre re2 post)
12342 re3 (concat pre re4 post)
12343 re5 (concat pre ".*" re4)
12344 re2 (concat pre re2)
12345 re2a (concat pre re2a)
12346 re4 (concat pre re4)
12347 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
12348 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
12349 re5 "\\)"
12351 (cond
12352 ((eq type 'org-occur) (org-occur reall))
12353 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
12354 (t (goto-char (point-min))
12355 (if (or (org-search-not-self 1 re0 nil t)
12356 (org-search-not-self 1 re1 nil t)
12357 (org-search-not-self 1 re2 nil t)
12358 (org-search-not-self 1 re2a nil t)
12359 (org-search-not-self 1 re3 nil t)
12360 (org-search-not-self 1 re4 nil t)
12361 (org-search-not-self 1 re5 nil t)
12363 (goto-char (match-beginning 1))
12364 (goto-char pos)
12365 (error "No match")))))
12367 ;; Normal string-search
12368 (goto-char (point-min))
12369 (if (search-forward s nil t)
12370 (goto-char (match-beginning 0))
12371 (error "No match"))))
12372 (and (org-mode-p) (org-show-context 'link-search))))
12374 (defun org-search-not-self (group &rest args)
12375 "Execute `re-search-forward', but only accept matches that do not
12376 enclose the position of `org-open-link-marker'."
12377 (let ((m org-open-link-marker))
12378 (catch 'exit
12379 (while (apply 're-search-forward args)
12380 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
12381 (goto-char (match-end group))
12382 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
12383 (> (match-beginning 0) (marker-position m))
12384 (< (match-end 0) (marker-position m)))
12385 (save-match-data
12386 (or (not (org-in-regexp
12387 org-bracket-link-analytic-regexp 1))
12388 (not (match-end 4)) ; no description
12389 (and (<= (match-beginning 4) (point))
12390 (>= (match-end 4) (point))))))
12391 (throw 'exit (point))))))))
12393 (defun org-get-buffer-for-internal-link (buffer)
12394 "Return a buffer to be used for displaying the link target of internal links."
12395 (cond
12396 ((not org-display-internal-link-with-indirect-buffer)
12397 buffer)
12398 ((string-match "(Clone)$" (buffer-name buffer))
12399 (message "Buffer is already a clone, not making another one")
12400 ;; we also do not modify visibility in this case
12401 buffer)
12402 (t ; make a new indirect buffer for displaying the link
12403 (let* ((bn (buffer-name buffer))
12404 (ibn (concat bn "(Clone)"))
12405 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
12406 (with-current-buffer ib (org-overview))
12407 ib))))
12409 (defun org-do-occur (regexp &optional cleanup)
12410 "Call the Emacs command `occur'.
12411 If CLEANUP is non-nil, remove the printout of the regular expression
12412 in the *Occur* buffer. This is useful if the regex is long and not useful
12413 to read."
12414 (occur regexp)
12415 (when cleanup
12416 (let ((cwin (selected-window)) win beg end)
12417 (when (setq win (get-buffer-window "*Occur*"))
12418 (select-window win))
12419 (goto-char (point-min))
12420 (when (re-search-forward "match[a-z]+" nil t)
12421 (setq beg (match-end 0))
12422 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
12423 (setq end (1- (match-beginning 0)))))
12424 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
12425 (goto-char (point-min))
12426 (select-window cwin))))
12428 ;;; The mark ring for links jumps
12430 (defvar org-mark-ring nil
12431 "Mark ring for positions before jumps in Org-mode.")
12432 (defvar org-mark-ring-last-goto nil
12433 "Last position in the mark ring used to go back.")
12434 ;; Fill and close the ring
12435 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
12436 (loop for i from 1 to org-mark-ring-length do
12437 (push (make-marker) org-mark-ring))
12438 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
12439 org-mark-ring)
12441 (defun org-mark-ring-push (&optional pos buffer)
12442 "Put the current position or POS into the mark ring and rotate it."
12443 (interactive)
12444 (setq pos (or pos (point)))
12445 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
12446 (move-marker (car org-mark-ring)
12447 (or pos (point))
12448 (or buffer (current-buffer)))
12449 (message
12450 (substitute-command-keys
12451 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
12453 (defun org-mark-ring-goto (&optional n)
12454 "Jump to the previous position in the mark ring.
12455 With prefix arg N, jump back that many stored positions. When
12456 called several times in succession, walk through the entire ring.
12457 Org-mode commands jumping to a different position in the current file,
12458 or to another Org-mode file, automatically push the old position
12459 onto the ring."
12460 (interactive "p")
12461 (let (p m)
12462 (if (eq last-command this-command)
12463 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
12464 (setq p org-mark-ring))
12465 (setq org-mark-ring-last-goto p)
12466 (setq m (car p))
12467 (switch-to-buffer (marker-buffer m))
12468 (goto-char m)
12469 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
12471 (defun org-remove-angle-brackets (s)
12472 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
12473 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
12475 (defun org-add-angle-brackets (s)
12476 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
12477 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
12480 ;;; Following specific links
12482 (defun org-follow-timestamp-link ()
12483 (cond
12484 ((org-at-date-range-p t)
12485 (let ((org-agenda-start-on-weekday)
12486 (t1 (match-string 1))
12487 (t2 (match-string 2)))
12488 (setq t1 (time-to-days (org-time-string-to-time t1))
12489 t2 (time-to-days (org-time-string-to-time t2)))
12490 (org-agenda-list nil t1 (1+ (- t2 t1)))))
12491 ((org-at-timestamp-p t)
12492 (org-agenda-list nil (time-to-days (org-time-string-to-time
12493 (substring (match-string 1) 0 10)))
12495 (t (error "This should not happen"))))
12498 (defun org-follow-bbdb-link (name)
12499 "Follow a BBDB link to NAME."
12500 (require 'bbdb)
12501 (let ((inhibit-redisplay (not debug-on-error))
12502 (bbdb-electric-p nil))
12503 (catch 'exit
12504 ;; Exact match on name
12505 (bbdb-name (concat "\\`" name "\\'") nil)
12506 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12507 ;; Exact match on name
12508 (bbdb-company (concat "\\`" name "\\'") nil)
12509 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12510 ;; Partial match on name
12511 (bbdb-name name nil)
12512 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12513 ;; Partial match on company
12514 (bbdb-company name nil)
12515 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
12516 ;; General match including network address and notes
12517 (bbdb name nil)
12518 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
12519 (delete-window (get-buffer-window "*BBDB*"))
12520 (error "No matching BBDB record")))))
12522 (defun org-follow-info-link (name)
12523 "Follow an info file & node link to NAME."
12524 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
12525 (string-match "\\(.*\\)" name))
12526 (progn
12527 (require 'info)
12528 (if (match-string 2 name) ; If there isn't a node, choose "Top"
12529 (Info-find-node (match-string 1 name) (match-string 2 name))
12530 (Info-find-node (match-string 1 name) "Top")))
12531 (message (concat "Could not open: " name))))
12533 (defun org-follow-gnus-link (&optional group article)
12534 "Follow a Gnus link to GROUP and ARTICLE."
12535 (require 'gnus)
12536 (funcall (cdr (assq 'gnus org-link-frame-setup)))
12537 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
12538 (cond ((and group article)
12539 (gnus-group-read-group 1 nil group)
12540 (gnus-summary-goto-article (string-to-number article) nil t))
12541 (group (gnus-group-jump-to-group group))))
12543 (defun org-follow-vm-link (&optional folder article readonly)
12544 "Follow a VM link to FOLDER and ARTICLE."
12545 (require 'vm)
12546 (setq article (org-add-angle-brackets article))
12547 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
12548 ;; ange-ftp or efs or tramp access
12549 (let ((user (or (match-string 1 folder) (user-login-name)))
12550 (host (match-string 2 folder))
12551 (file (match-string 3 folder)))
12552 (cond
12553 ((featurep 'tramp)
12554 ;; use tramp to access the file
12555 (if (featurep 'xemacs)
12556 (setq folder (format "[%s@%s]%s" user host file))
12557 (setq folder (format "/%s@%s:%s" user host file))))
12559 ;; use ange-ftp or efs
12560 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
12561 (setq folder (format "/%s@%s:%s" user host file))))))
12562 (when folder
12563 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
12564 (sit-for 0.1)
12565 (when article
12566 (vm-select-folder-buffer)
12567 (widen)
12568 (let ((case-fold-search t))
12569 (goto-char (point-min))
12570 (if (not (re-search-forward
12571 (concat "^" "message-id: *" (regexp-quote article))))
12572 (error "Could not find the specified message in this folder"))
12573 (vm-isearch-update)
12574 (vm-isearch-narrow)
12575 (vm-beginning-of-message)
12576 (vm-summarize)))))
12578 (defun org-follow-wl-link (folder article)
12579 "Follow a Wanderlust link to FOLDER and ARTICLE."
12580 (if (and (string= folder "%")
12581 article
12582 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
12583 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
12584 ;; Thus, we recompose folder and article ids.
12585 (setq folder (format "%s#%s" folder (match-string 1 article))
12586 article (match-string 3 article)))
12587 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
12588 (error "No such folder: %s" folder))
12589 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
12590 (and article
12591 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
12592 (wl-summary-redisplay)))
12594 (defun org-follow-rmail-link (folder article)
12595 "Follow an RMAIL link to FOLDER and ARTICLE."
12596 (setq article (org-add-angle-brackets article))
12597 (let (message-number)
12598 (save-excursion
12599 (save-window-excursion
12600 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12601 (setq message-number
12602 (save-restriction
12603 (widen)
12604 (goto-char (point-max))
12605 (if (re-search-backward
12606 (concat "^Message-ID:\\s-+" (regexp-quote
12607 (or article "")))
12608 nil t)
12609 (rmail-what-message))))))
12610 (if message-number
12611 (progn
12612 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
12613 (rmail-show-message message-number)
12614 message-number)
12615 (error "Message not found"))))
12617 ;;; mh-e integration based on planner-mode
12618 (defun org-mhe-get-message-real-folder ()
12619 "Return the name of the current message real folder, so if you use
12620 sequences, it will now work."
12621 (save-excursion
12622 (let* ((folder
12623 (if (equal major-mode 'mh-folder-mode)
12624 mh-current-folder
12625 ;; Refer to the show buffer
12626 mh-show-folder-buffer))
12627 (end-index
12628 (if (boundp 'mh-index-folder)
12629 (min (length mh-index-folder) (length folder))))
12631 ;; a simple test on mh-index-data does not work, because
12632 ;; mh-index-data is always nil in a show buffer.
12633 (if (and (boundp 'mh-index-folder)
12634 (string= mh-index-folder (substring folder 0 end-index)))
12635 (if (equal major-mode 'mh-show-mode)
12636 (save-window-excursion
12637 (let (pop-up-frames)
12638 (when (buffer-live-p (get-buffer folder))
12639 (progn
12640 (pop-to-buffer folder)
12641 (org-mhe-get-message-folder-from-index)
12644 (org-mhe-get-message-folder-from-index)
12646 folder
12650 (defun org-mhe-get-message-folder-from-index ()
12651 "Returns the name of the message folder in a index folder buffer."
12652 (save-excursion
12653 (mh-index-previous-folder)
12654 (re-search-forward "^\\(+.*\\)$" nil t)
12655 (message (match-string 1))))
12657 (defun org-mhe-get-message-folder ()
12658 "Return the name of the current message folder. Be careful if you
12659 use sequences."
12660 (save-excursion
12661 (if (equal major-mode 'mh-folder-mode)
12662 mh-current-folder
12663 ;; Refer to the show buffer
12664 mh-show-folder-buffer)))
12666 (defun org-mhe-get-message-num ()
12667 "Return the number of the current message. Be careful if you
12668 use sequences."
12669 (save-excursion
12670 (if (equal major-mode 'mh-folder-mode)
12671 (mh-get-msg-num nil)
12672 ;; Refer to the show buffer
12673 (mh-show-buffer-message-number))))
12675 (defun org-mhe-get-header (header)
12676 "Return a header of the message in folder mode. This will create a
12677 show buffer for the corresponding message. If you have a more clever
12678 idea..."
12679 (let* ((folder (org-mhe-get-message-folder))
12680 (num (org-mhe-get-message-num))
12681 (buffer (get-buffer-create (concat "show-" folder)))
12682 (header-field))
12683 (with-current-buffer buffer
12684 (mh-display-msg num folder)
12685 (if (equal major-mode 'mh-folder-mode)
12686 (mh-header-display)
12687 (mh-show-header-display))
12688 (set-buffer buffer)
12689 (setq header-field (mh-get-header-field header))
12690 (if (equal major-mode 'mh-folder-mode)
12691 (mh-show)
12692 (mh-show-show))
12693 header-field)))
12695 (defun org-follow-mhe-link (folder article)
12696 "Follow an MHE link to FOLDER and ARTICLE.
12697 If ARTICLE is nil FOLDER is shown. If the configuration variable
12698 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
12699 ARTICLE is searched in all folders. Indexed searches (swish++,
12700 namazu, and others supported by MH-E) will always search in all
12701 folders."
12702 (require 'mh-e)
12703 (require 'mh-search)
12704 (require 'mh-utils)
12705 (mh-find-path)
12706 (if (not article)
12707 (mh-visit-folder (mh-normalize-folder-name folder))
12708 (setq article (org-add-angle-brackets article))
12709 (mh-search-choose)
12710 (if (equal mh-searcher 'pick)
12711 (progn
12712 (mh-search folder (list "--message-id" article))
12713 (when (and org-mhe-search-all-folders
12714 (not (org-mhe-get-message-real-folder)))
12715 (kill-this-buffer)
12716 (mh-search "+" (list "--message-id" article))))
12717 (mh-search "+" article))
12718 (if (org-mhe-get-message-real-folder)
12719 (mh-show-msg 1)
12720 (kill-this-buffer)
12721 (error "Message not found"))))
12723 ;;; BibTeX links
12725 ;; Use the custom search meachnism to construct and use search strings for
12726 ;; file links to BibTeX database entries.
12728 (defun org-create-file-search-in-bibtex ()
12729 "Create the search string and description for a BibTeX database entry."
12730 (when (eq major-mode 'bibtex-mode)
12731 ;; yes, we want to construct this search string.
12732 ;; Make a good description for this entry, using names, year and the title
12733 ;; Put it into the `description' variable which is dynamically scoped.
12734 (let ((bibtex-autokey-names 1)
12735 (bibtex-autokey-names-stretch 1)
12736 (bibtex-autokey-name-case-convert-function 'identity)
12737 (bibtex-autokey-name-separator " & ")
12738 (bibtex-autokey-additional-names " et al.")
12739 (bibtex-autokey-year-length 4)
12740 (bibtex-autokey-name-year-separator " ")
12741 (bibtex-autokey-titlewords 3)
12742 (bibtex-autokey-titleword-separator " ")
12743 (bibtex-autokey-titleword-case-convert-function 'identity)
12744 (bibtex-autokey-titleword-length 'infty)
12745 (bibtex-autokey-year-title-separator ": "))
12746 (setq description (bibtex-generate-autokey)))
12747 ;; Now parse the entry, get the key and return it.
12748 (save-excursion
12749 (bibtex-beginning-of-entry)
12750 (cdr (assoc "=key=" (bibtex-parse-entry))))))
12752 (defun org-execute-file-search-in-bibtex (s)
12753 "Find the link search string S as a key for a database entry."
12754 (when (eq major-mode 'bibtex-mode)
12755 ;; Yes, we want to do the search in this file.
12756 ;; We construct a regexp that searches for "@entrytype{" followed by the key
12757 (goto-char (point-min))
12758 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
12759 (regexp-quote s) "[ \t\n]*,") nil t)
12760 (goto-char (match-beginning 0)))
12761 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
12762 ;; Use double prefix to indicate that any web link should be browsed
12763 (let ((b (current-buffer)) (p (point)))
12764 ;; Restore the window configuration because we just use the web link
12765 (set-window-configuration org-window-config-before-follow-link)
12766 (save-excursion (set-buffer b) (goto-char p)
12767 (bibtex-url)))
12768 (recenter 0)) ; Move entry start to beginning of window
12769 ;; return t to indicate that the search is done.
12772 ;; Finally add the functions to the right hooks.
12773 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
12774 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
12776 ;; end of Bibtex link setup
12778 ;;; Following file links
12780 (defun org-open-file (path &optional in-emacs line search)
12781 "Open the file at PATH.
12782 First, this expands any special file name abbreviations. Then the
12783 configuration variable `org-file-apps' is checked if it contains an
12784 entry for this file type, and if yes, the corresponding command is launched.
12785 If no application is found, Emacs simply visits the file.
12786 With optional argument IN-EMACS, Emacs will visit the file.
12787 Optional LINE specifies a line to go to, optional SEARCH a string to
12788 search for. If LINE or SEARCH is given, the file will always be
12789 opened in Emacs.
12790 If the file does not exist, an error is thrown."
12791 (setq in-emacs (or in-emacs line search))
12792 (let* ((file (if (equal path "")
12793 buffer-file-name
12794 (substitute-in-file-name (expand-file-name path))))
12795 (apps (append org-file-apps (org-default-apps)))
12796 (remp (and (assq 'remote apps) (org-file-remote-p file)))
12797 (dirp (if remp nil (file-directory-p file)))
12798 (dfile (downcase file))
12799 (old-buffer (current-buffer))
12800 (old-pos (point))
12801 (old-mode major-mode)
12802 ext cmd)
12803 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
12804 (setq ext (match-string 1 dfile))
12805 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
12806 (setq ext (match-string 1 dfile))))
12807 (if in-emacs
12808 (setq cmd 'emacs)
12809 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
12810 (and dirp (cdr (assoc 'directory apps)))
12811 (cdr (assoc ext apps))
12812 (cdr (assoc t apps)))))
12813 (when (eq cmd 'mailcap)
12814 (require 'mailcap)
12815 (mailcap-parse-mailcaps)
12816 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
12817 (command (mailcap-mime-info mime-type)))
12818 (if (stringp command)
12819 (setq cmd command)
12820 (setq cmd 'emacs))))
12821 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
12822 (not (file-exists-p file))
12823 (not org-open-non-existing-files))
12824 (error "No such file: %s" file))
12825 (cond
12826 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
12827 ;; Remove quotes around the file name - we'll use shell-quote-argument.
12828 (if (string-match "['\"]%s['\"]" cmd)
12829 (setq cmd (replace-match "%s" t t cmd)))
12830 (setq cmd (format cmd (shell-quote-argument file)))
12831 (save-window-excursion
12832 (start-process-shell-command cmd nil cmd)))
12833 ((or (stringp cmd)
12834 (eq cmd 'emacs))
12835 (funcall (cdr (assq 'file org-link-frame-setup)) file)
12836 (widen)
12837 (if line (goto-line line)
12838 (if search (org-link-search search))))
12839 ((consp cmd)
12840 (eval cmd))
12841 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
12842 (and (org-mode-p) (eq old-mode 'org-mode)
12843 (or (not (equal old-buffer (current-buffer)))
12844 (not (equal old-pos (point))))
12845 (org-mark-ring-push old-pos old-buffer))))
12847 (defun org-default-apps ()
12848 "Return the default applications for this operating system."
12849 (cond
12850 ((eq system-type 'darwin)
12851 org-file-apps-defaults-macosx)
12852 ((eq system-type 'windows-nt)
12853 org-file-apps-defaults-windowsnt)
12854 (t org-file-apps-defaults-gnu)))
12856 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
12857 (defun org-file-remote-p (file)
12858 "Test whether FILE specifies a location on a remote system.
12859 Return non-nil if the location is indeed remote.
12861 For example, the filename \"/user@host:/foo\" specifies a location
12862 on the system \"/user@host:\"."
12863 (cond ((fboundp 'file-remote-p)
12864 (file-remote-p file))
12865 ((fboundp 'tramp-handle-file-remote-p)
12866 (tramp-handle-file-remote-p file))
12867 ((and (boundp 'ange-ftp-name-format)
12868 (string-match (car ange-ftp-name-format) file))
12870 (t nil)))
12873 ;;;; Hooks for remember.el
12875 ;;;###autoload
12876 (defun org-remember-insinuate ()
12877 "Setup remember.el for use wiht Org-mode."
12878 (require 'remember)
12879 (setq remember-annotation-functions '(org-remember-annotation))
12880 (setq remember-handler-functions '(org-remember-handler))
12881 (add-hook 'remember-mode-hook 'org-remember-apply-template))
12883 ;;;###autoload
12884 (defun org-remember-annotation ()
12885 "Return a link to the current location as an annotation for remember.el.
12886 If you are using Org-mode files as target for data storage with
12887 remember.el, then the annotations should include a link compatible with the
12888 conventions in Org-mode. This function returns such a link."
12889 (org-store-link nil))
12891 (defconst org-remember-help
12892 "Select a destination location for the note.
12893 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
12894 RET on headline -> Store as sublevel entry to current headline
12895 RET at beg-of-buf -> Append to file as level 2 headline
12896 <left>/<right> -> before/after current headline, same headings level")
12898 (defvar org-remember-previous-location nil)
12899 (defvar org-force-remember-template-char) ;; dynamically scoped
12901 (defun org-select-remember-template (&optional use-char)
12902 (when org-remember-templates
12903 (let* ((templates (mapcar (lambda (x)
12904 (if (stringp (car x))
12905 (append (list (nth 1 x) (car x)) (cddr x))
12906 (append (list (car x) "") (cdr x))))
12907 org-remember-templates))
12908 (char (or use-char
12909 (cond
12910 ((= (length templates) 1)
12911 (caar templates))
12912 ((and (boundp 'org-force-remember-template-char)
12913 org-force-remember-template-char)
12914 (if (stringp org-force-remember-template-char)
12915 (string-to-char org-force-remember-template-char)
12916 org-force-remember-template-char))
12918 (message "Select template: %s"
12919 (mapconcat
12920 (lambda (x)
12921 (cond
12922 ((not (string-match "\\S-" (nth 1 x)))
12923 (format "[%c]" (car x)))
12924 ((equal (downcase (car x))
12925 (downcase (aref (nth 1 x) 0)))
12926 (format "[%c]%s" (car x)
12927 (substring (nth 1 x) 1)))
12928 (t (format "[%c]%s" (car x) (nth 1 x)))))
12929 templates " "))
12930 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
12931 (when (equal char0 ?\C-g)
12932 (jump-to-register remember-register)
12933 (kill-buffer remember-buffer))
12934 char0))))))
12935 (cddr (assoc char templates)))))
12937 ;;;###autoload
12938 (defun org-remember-apply-template (&optional use-char skip-interactive)
12939 "Initialize *remember* buffer with template, invoke `org-mode'.
12940 This function should be placed into `remember-mode-hook' and in fact requires
12941 to be run from that hook to function properly."
12942 (unless (fboundp 'remember-finalize)
12943 (defalias 'remember-finalize 'remember-buffer))
12944 (if org-remember-templates
12945 (let* ((entry (org-select-remember-template use-char))
12946 (tpl (car entry))
12947 (plist-p (if org-store-link-plist t nil))
12948 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
12949 (string-match "\\S-" (nth 1 entry)))
12950 (nth 1 entry)
12951 org-default-notes-file))
12952 (headline (nth 2 entry))
12953 (v-c (current-kill 0)) ;; FIXME: protection needed?
12954 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
12955 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
12956 (v-u (concat "[" (substring v-t 1 -1) "]"))
12957 (v-U (concat "[" (substring v-T 1 -1) "]"))
12958 ;; `initial' and `annotation' are bound in `remember'
12959 (v-i (if (boundp 'initial) initial))
12960 (v-a (if (and (boundp 'annotation) annotation)
12961 (if (equal annotation "[[]]") "" annotation)
12962 ""))
12963 (v-A (if (and v-a
12964 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
12965 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
12966 v-a))
12967 (v-n user-full-name)
12968 (org-startup-folded nil)
12969 org-time-was-given org-end-time-was-given x prompt char time pos)
12970 (setq org-store-link-plist
12971 (append (list :annotation v-a :initial v-i)
12972 org-store-link-plist))
12973 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
12974 (erase-buffer)
12975 (insert (substitute-command-keys
12976 (format
12977 "## Filing location: Select interactively, default, or last used:
12978 ## %s to select file and header location interactively.
12979 ## %s \"%s\" -> \"* %s\"
12980 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
12981 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
12982 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
12983 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
12984 (abbreviate-file-name (or file org-default-notes-file))
12985 (or headline "")
12986 (or (car org-remember-previous-location) "???")
12987 (or (cdr org-remember-previous-location) "???"))))
12988 (insert tpl) (goto-char (point-min))
12989 ;; Simple %-escapes
12990 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
12991 (when (and initial (equal (match-string 0) "%i"))
12992 (save-match-data
12993 (let* ((lead (buffer-substring
12994 (point-at-bol) (match-beginning 0))))
12995 (setq v-i (mapconcat 'identity
12996 (org-split-string initial "\n")
12997 (concat "\n" lead))))))
12998 (replace-match
12999 (or (eval (intern (concat "v-" (match-string 1)))) "")
13000 t t))
13002 ;; %[] Insert contents of a file.
13003 (goto-char (point-min))
13004 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13005 (let ((start (match-beginning 0))
13006 (end (match-end 0))
13007 (filename (expand-file-name (match-string 1))))
13008 (goto-char start)
13009 (delete-region start end)
13010 (condition-case error
13011 (insert-file-contents filename)
13012 (error (insert (format "%%![Couldn't insert %s: %s]"
13013 filename error))))))
13014 ;; %() embedded elisp
13015 (goto-char (point-min))
13016 (while (re-search-forward "%\\((.+)\\)" nil t)
13017 (goto-char (match-beginning 0))
13018 (let ((template-start (point)))
13019 (forward-char 1)
13020 (let ((result
13021 (condition-case error
13022 (eval (read (current-buffer)))
13023 (error (format "%%![Error: %s]" error)))))
13024 (delete-region template-start (point))
13025 (insert result))))
13027 ;; From the property list
13028 (when plist-p
13029 (goto-char (point-min))
13030 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13031 (and (setq x (or (plist-get org-store-link-plist
13032 (intern (match-string 1))) ""))
13033 (replace-match x t t))))
13035 ;; Turn on org-mode in the remember buffer, set local variables
13036 (org-mode)
13037 (org-set-local 'org-finish-function 'remember-finalize)
13038 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13039 (org-set-local 'org-default-notes-file file))
13040 (if (and headline (stringp headline) (string-match "\\S-" headline))
13041 (org-set-local 'org-remember-default-headline headline))
13042 ;; Interactive template entries
13043 (goto-char (point-min))
13044 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([guUtT]\\)?" nil t)
13045 (setq char (if (match-end 3) (match-string 3))
13046 prompt (if (match-end 2) (match-string 2)))
13047 (goto-char (match-beginning 0))
13048 (replace-match "")
13049 (cond
13050 ((member char '("G" "g"))
13051 (let* ((org-last-tags-completion-table
13052 (org-global-tags-completion-table
13053 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13054 (org-add-colon-after-tag-completion t)
13055 (ins (completing-read
13056 (if prompt (concat prompt ": ") "Tags: ")
13057 'org-tags-completion-function nil nil nil
13058 'org-tags-history)))
13059 (setq ins (mapconcat 'identity
13060 (org-split-string ins (org-re "[^[:alnum:]]+"))
13061 ":"))
13062 (when (string-match "\\S-" ins)
13063 (or (equal (char-before) ?:) (insert ":"))
13064 (insert ins)
13065 (or (equal (char-after) ?:) (insert ":")))))
13066 (char
13067 (setq org-time-was-given (equal (upcase char) char))
13068 (setq time (org-read-date (equal (upcase char) "U") t nil
13069 prompt))
13070 (org-insert-time-stamp time org-time-was-given
13071 (member char '("u" "U"))
13072 nil nil (list org-end-time-was-given)))
13074 (insert (read-string
13075 (if prompt (concat prompt ": ") "Enter string"))))))
13076 (goto-char (point-min))
13077 (if (re-search-forward "%\\?" nil t)
13078 (replace-match "")
13079 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13080 (org-mode)
13081 (org-set-local 'org-finish-function 'remember-finalize)))
13083 ;;;###autoload
13084 (defun org-remember (&optional goto org-force-remember-template-char)
13085 "Call `remember'. If this is already a remember buffer, re-apply template.
13086 If there is an active region, make sure remember uses it as initial content
13087 of the remember buffer.
13089 When called interactively with a `C-u' prefix argument GOTO, don't remember
13090 anything, just go to the file/headline where the selected templated usually
13091 stores its notes.
13093 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13094 associated with a template in `org-remember-tempates'."
13095 (interactive "P")
13096 (if (equal goto '(4))
13097 (org-go-to-remember-target)
13098 (if (eq org-finish-function 'remember-buffer)
13099 (progn
13100 (when (< (length org-remember-templates) 2)
13101 (error "No other template available"))
13102 (erase-buffer)
13103 (let ((annotation (plist-get org-store-link-plist :annotation))
13104 (initial (plist-get org-store-link-plist :initial)))
13105 (org-remember-apply-template))
13106 (message "Press C-c C-c to remember data"))
13107 (if (org-region-active-p)
13108 (remember (buffer-substring (point) (mark)))
13109 (call-interactively 'remember)))))
13111 (defun org-go-to-remember-target (&optional template-key)
13112 "Go to the target location of a remember template.
13113 The user is queried for the template."
13114 (interactive)
13115 (let* ((entry (org-select-remember-template template-key))
13116 (file (nth 1 entry))
13117 (heading (nth 2 entry))
13118 visiting)
13119 (unless (and file (stringp file) (string-match "\\S-" file))
13120 (setq file org-default-notes-file))
13121 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13122 (setq heading org-remember-default-headline))
13123 (setq visiting (org-find-base-buffer-visiting file))
13124 (if (not visiting) (find-file-noselect file))
13125 (switch-to-buffer (or visiting (get-file-buffer file)))
13126 (widen)
13127 (goto-char (point-min))
13128 (if (re-search-forward
13129 (concat "^\\*+[ \t]+" (regexp-quote heading)
13130 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13131 nil t)
13132 (goto-char (match-beginning 0))
13133 (error "Target headline not found: %s" heading))))
13135 (defvar org-note-abort nil) ; dynamically scoped
13137 ;;;###autoload
13138 (defun org-remember-handler ()
13139 "Store stuff from remember.el into an org file.
13140 First prompts for an org file. If the user just presses return, the value
13141 of `org-default-notes-file' is used.
13142 Then the command offers the headings tree of the selected file in order to
13143 file the text at a specific location.
13144 You can either immediately press RET to get the note appended to the
13145 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13146 find a better place. Then press RET or <left> or <right> in insert the note.
13148 Key Cursor position Note gets inserted
13149 -----------------------------------------------------------------------------
13150 RET buffer-start as level 1 heading at end of file
13151 RET on headline as sublevel of the heading at cursor
13152 RET no heading at cursor position, level taken from context.
13153 Or use prefix arg to specify level manually.
13154 <left> on headline as same level, before current heading
13155 <right> on headline as same level, after current heading
13157 So the fastest way to store the note is to press RET RET to append it to
13158 the default file. This way your current train of thought is not
13159 interrupted, in accordance with the principles of remember.el.
13160 You can also get the fast execution without prompting by using
13161 C-u C-c C-c to exit the remember buffer. See also the variable
13162 `org-remember-store-without-prompt'.
13164 Before being stored away, the function ensures that the text has a
13165 headline, i.e. a first line that starts with a \"*\". If not, a headline
13166 is constructed from the current date and some additional data.
13168 If the variable `org-adapt-indentation' is non-nil, the entire text is
13169 also indented so that it starts in the same column as the headline
13170 \(i.e. after the stars).
13172 See also the variable `org-reverse-note-order'."
13173 (goto-char (point-min))
13174 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13175 (replace-match ""))
13176 (goto-char (point-max))
13177 (catch 'quit
13178 (if org-note-abort (throw 'quit nil))
13179 (let* ((txt (buffer-substring (point-min) (point-max)))
13180 (fastp (org-xor (equal current-prefix-arg '(4))
13181 org-remember-store-without-prompt))
13182 (file (if fastp org-default-notes-file (org-get-org-file)))
13183 (heading org-remember-default-headline)
13184 (visiting (org-find-base-buffer-visiting file))
13185 (org-startup-folded nil)
13186 (org-startup-align-all-tables nil)
13187 (org-goto-start-pos 1)
13188 spos exitcmd level indent reversed)
13189 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13190 (setq file (car org-remember-previous-location)
13191 heading (cdr org-remember-previous-location)))
13192 (setq current-prefix-arg nil)
13193 ;; Modify text so that it becomes a nice subtree which can be inserted
13194 ;; into an org tree.
13195 (let* ((lines (split-string txt "\n"))
13196 first)
13197 (setq first (car lines) lines (cdr lines))
13198 (if (string-match "^\\*+ " first)
13199 ;; Is already a headline
13200 (setq indent nil)
13201 ;; We need to add a headline: Use time and first buffer line
13202 (setq lines (cons first lines)
13203 first (concat "* " (current-time-string)
13204 " (" (remember-buffer-desc) ")")
13205 indent " "))
13206 (if (and org-adapt-indentation indent)
13207 (setq lines (mapcar
13208 (lambda (x)
13209 (if (string-match "\\S-" x)
13210 (concat indent x) x))
13211 lines)))
13212 (setq txt (concat first "\n"
13213 (mapconcat 'identity lines "\n"))))
13214 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
13215 (setq txt (replace-match "\n\n" t t txt))
13216 (if (string-match "[ \t\n]*\\'" txt)
13217 (setq txt (replace-match "\n" t t txt))))
13218 ;; Find the file
13219 (if (not visiting) (find-file-noselect file))
13220 (with-current-buffer (or visiting (get-file-buffer file))
13221 (unless (org-mode-p)
13222 (error "Target files for remember notes must be in Org-mode"))
13223 (save-excursion
13224 (save-restriction
13225 (widen)
13226 (and (goto-char (point-min))
13227 (not (re-search-forward "^\\* " nil t))
13228 (insert "\n* " (or heading "Notes") "\n"))
13229 (setq reversed (org-notes-order-reversed-p))
13231 ;; Find the default location
13232 (when (and heading (stringp heading) (string-match "\\S-" heading))
13233 (goto-char (point-min))
13234 (if (re-search-forward
13235 (concat "^\\*+[ \t]+" (regexp-quote heading)
13236 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13237 nil t)
13238 (setq org-goto-start-pos (match-beginning 0))
13239 (when fastp
13240 (goto-char (point-max))
13241 (unless (bolp) (newline))
13242 (insert "* " heading "\n")
13243 (setq org-goto-start-pos (point-at-bol 0)))))
13245 ;; Ask the User for a location
13246 (if fastp
13247 (setq spos org-goto-start-pos
13248 exitcmd 'return)
13249 (setq spos (org-get-location (current-buffer) org-remember-help)
13250 exitcmd (cdr spos)
13251 spos (car spos)))
13252 (if (not spos) (throw 'quit nil)) ; return nil to show we did
13253 ; not handle this note
13254 (goto-char spos)
13255 (cond ((org-on-heading-p t)
13256 (org-back-to-heading t)
13257 (setq level (funcall outline-level))
13258 (cond
13259 ((eq exitcmd 'return)
13260 ;; sublevel of current
13261 (setq org-remember-previous-location
13262 (cons (abbreviate-file-name file)
13263 (org-get-heading 'notags)))
13264 (if reversed
13265 (outline-next-heading)
13266 (org-end-of-subtree)
13267 (if (not (bolp))
13268 (if (looking-at "[ \t]*\n")
13269 (beginning-of-line 2)
13270 (end-of-line 1)
13271 (insert "\n"))))
13272 (org-paste-subtree (org-get-legal-level level 1) txt))
13273 ((eq exitcmd 'left)
13274 ;; before current
13275 (org-paste-subtree level txt))
13276 ((eq exitcmd 'right)
13277 ;; after current
13278 (org-end-of-subtree t)
13279 (org-paste-subtree level txt))
13280 (t (error "This should not happen"))))
13282 ((and (bobp) (not reversed))
13283 ;; Put it at the end, one level below level 1
13284 (save-restriction
13285 (widen)
13286 (goto-char (point-max))
13287 (if (not (bolp)) (newline))
13288 (org-paste-subtree (org-get-legal-level 1 1) txt)))
13290 ((and (bobp) reversed)
13291 ;; Put it at the start, as level 1
13292 (save-restriction
13293 (widen)
13294 (goto-char (point-min))
13295 (re-search-forward "^\\*+ " nil t)
13296 (beginning-of-line 1)
13297 (org-paste-subtree 1 txt)))
13299 ;; Put it right there, with automatic level determined by
13300 ;; org-paste-subtree or from prefix arg
13301 (org-paste-subtree
13302 (if (numberp current-prefix-arg) current-prefix-arg)
13303 txt)))
13304 (when remember-save-after-remembering
13305 (save-buffer)
13306 (if (not visiting) (kill-buffer (current-buffer)))))))))
13307 t) ;; return t to indicate that we took care of this note.
13309 (defun org-get-org-file ()
13310 "Read a filename, with default directory `org-directory'."
13311 (let ((default (or org-default-notes-file remember-data-file)))
13312 (read-file-name (format "File name [%s]: " default)
13313 (file-name-as-directory org-directory)
13314 default)))
13316 (defun org-notes-order-reversed-p ()
13317 "Check if the current file should receive notes in reversed order."
13318 (cond
13319 ((not org-reverse-note-order) nil)
13320 ((eq t org-reverse-note-order) t)
13321 ((not (listp org-reverse-note-order)) nil)
13322 (t (catch 'exit
13323 (let ((all org-reverse-note-order)
13324 entry)
13325 (while (setq entry (pop all))
13326 (if (string-match (car entry) buffer-file-name)
13327 (throw 'exit (cdr entry))))
13328 nil)))))
13330 ;;;; Dynamic blocks
13332 (defun org-find-dblock (name)
13333 "Find the first dynamic block with name NAME in the buffer.
13334 If not found, stay at current position and return nil."
13335 (let (pos)
13336 (save-excursion
13337 (goto-char (point-min))
13338 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
13339 nil t)
13340 (match-beginning 0))))
13341 (if pos (goto-char pos))
13342 pos))
13344 (defconst org-dblock-start-re
13345 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
13346 "Matches the startline of a dynamic block, with parameters.")
13348 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
13349 "Matches the end of a dyhamic block.")
13351 (defun org-create-dblock (plist)
13352 "Create a dynamic block section, with parameters taken from PLIST.
13353 PLIST must containe a :name entry which is used as name of the block."
13354 (unless (bolp) (newline))
13355 (let ((name (plist-get plist :name)))
13356 (insert "#+BEGIN: " name)
13357 (while plist
13358 (if (eq (car plist) :name)
13359 (setq plist (cddr plist))
13360 (insert " " (prin1-to-string (pop plist)))))
13361 (insert "\n\n#+END:\n")
13362 (beginning-of-line -2)))
13364 (defun org-prepare-dblock ()
13365 "Prepare dynamic block for refresh.
13366 This empties the block, puts the cursor at the insert position and returns
13367 the property list including an extra property :name with the block name."
13368 (unless (looking-at org-dblock-start-re)
13369 (error "Not at a dynamic block"))
13370 (let* ((begdel (1+ (match-end 0)))
13371 (name (org-no-properties (match-string 1)))
13372 (params (append (list :name name)
13373 (read (concat "(" (match-string 3) ")")))))
13374 (unless (re-search-forward org-dblock-end-re nil t)
13375 (error "Dynamic block not terminated"))
13376 (delete-region begdel (match-beginning 0))
13377 (goto-char begdel)
13378 (open-line 1)
13379 params))
13381 (defun org-map-dblocks (&optional command)
13382 "Apply COMMAND to all dynamic blocks in the current buffer.
13383 If COMMAND is not given, use `org-update-dblock'."
13384 (let ((cmd (or command 'org-update-dblock))
13385 pos)
13386 (save-excursion
13387 (goto-char (point-min))
13388 (while (re-search-forward org-dblock-start-re nil t)
13389 (goto-char (setq pos (match-beginning 0)))
13390 (condition-case nil
13391 (funcall cmd)
13392 (error (message "Error during update of dynamic block")))
13393 (goto-char pos)
13394 (unless (re-search-forward org-dblock-end-re nil t)
13395 (error "Dynamic block not terminated"))))))
13397 (defun org-dblock-update (&optional arg)
13398 "User command for updating dynamic blocks.
13399 Update the dynamic block at point. With prefix ARG, update all dynamic
13400 blocks in the buffer."
13401 (interactive "P")
13402 (if arg
13403 (org-update-all-dblocks)
13404 (or (looking-at org-dblock-start-re)
13405 (org-beginning-of-dblock))
13406 (org-update-dblock)))
13408 (defun org-update-dblock ()
13409 "Update the dynamic block at point
13410 This means to empty the block, parse for parameters and then call
13411 the correct writing function."
13412 (save-window-excursion
13413 (let* ((pos (point))
13414 (line (org-current-line))
13415 (params (org-prepare-dblock))
13416 (name (plist-get params :name))
13417 (cmd (intern (concat "org-dblock-write:" name))))
13418 (message "Updating dynamic block `%s' at line %d..." name line)
13419 (funcall cmd params)
13420 (message "Updating dynamic block `%s' at line %d...done" name line)
13421 (goto-char pos))))
13423 (defun org-beginning-of-dblock ()
13424 "Find the beginning of the dynamic block at point.
13425 Error if there is no scuh block at point."
13426 (let ((pos (point))
13427 beg)
13428 (end-of-line 1)
13429 (if (and (re-search-backward org-dblock-start-re nil t)
13430 (setq beg (match-beginning 0))
13431 (re-search-forward org-dblock-end-re nil t)
13432 (> (match-end 0) pos))
13433 (goto-char beg)
13434 (goto-char pos)
13435 (error "Not in a dynamic block"))))
13437 (defun org-update-all-dblocks ()
13438 "Update all dynamic blocks in the buffer.
13439 This function can be used in a hook."
13440 (when (org-mode-p)
13441 (org-map-dblocks 'org-update-dblock)))
13444 ;;;; Completion
13446 (defconst org-additional-option-like-keywords
13447 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
13448 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
13449 "BEGIN_EXAMPLE" "END_EXAMPLE"))
13451 (defun org-complete (&optional arg)
13452 "Perform completion on word at point.
13453 At the beginning of a headline, this completes TODO keywords as given in
13454 `org-todo-keywords'.
13455 If the current word is preceded by a backslash, completes the TeX symbols
13456 that are supported for HTML support.
13457 If the current word is preceded by \"#+\", completes special words for
13458 setting file options.
13459 In the line after \"#+STARTUP:, complete valid keywords.\"
13460 At all other locations, this simply calls the value of
13461 `org-completion-fallback-command'."
13462 (interactive "P")
13463 (org-without-partial-completion
13464 (catch 'exit
13465 (let* ((end (point))
13466 (beg1 (save-excursion
13467 (skip-chars-backward (org-re "[:alnum:]_@"))
13468 (point)))
13469 (beg (save-excursion
13470 (skip-chars-backward "a-zA-Z0-9_:$")
13471 (point)))
13472 (confirm (lambda (x) (stringp (car x))))
13473 (searchhead (equal (char-before beg) ?*))
13474 (tag (and (equal (char-before beg1) ?:)
13475 (equal (char-after (point-at-bol)) ?*)))
13476 (prop (and (equal (char-before beg1) ?:)
13477 (not (equal (char-after (point-at-bol)) ?*))))
13478 (texp (equal (char-before beg) ?\\))
13479 (link (equal (char-before beg) ?\[))
13480 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
13481 beg)
13482 "#+"))
13483 (startup (string-match "^#\\+STARTUP:.*"
13484 (buffer-substring (point-at-bol) (point))))
13485 (completion-ignore-case opt)
13486 (type nil)
13487 (tbl nil)
13488 (table (cond
13489 (opt
13490 (setq type :opt)
13491 (append
13492 (mapcar
13493 (lambda (x)
13494 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
13495 (cons (match-string 2 x) (match-string 1 x)))
13496 (org-split-string (org-get-current-options) "\n"))
13497 (mapcar 'list org-additional-option-like-keywords)))
13498 (startup
13499 (setq type :startup)
13500 org-startup-options)
13501 (link (append org-link-abbrev-alist-local
13502 org-link-abbrev-alist))
13503 (texp
13504 (setq type :tex)
13505 org-html-entities)
13506 ((string-match "\\`\\*+[ \t]+\\'"
13507 (buffer-substring (point-at-bol) beg))
13508 (setq type :todo)
13509 (mapcar 'list org-todo-keywords-1))
13510 (searchhead
13511 (setq type :searchhead)
13512 (save-excursion
13513 (goto-char (point-min))
13514 (while (re-search-forward org-todo-line-regexp nil t)
13515 (push (list
13516 (org-make-org-heading-search-string
13517 (match-string 3) t))
13518 tbl)))
13519 tbl)
13520 (tag (setq type :tag beg beg1)
13521 (or org-tag-alist (org-get-buffer-tags)))
13522 (prop (setq type :prop beg beg1)
13523 (mapcar 'list (org-buffer-property-keys)))
13524 (t (progn
13525 (call-interactively org-completion-fallback-command)
13526 (throw 'exit nil)))))
13527 (pattern (buffer-substring-no-properties beg end))
13528 (completion (try-completion pattern table confirm)))
13529 (cond ((eq completion t)
13530 (if (not (assoc (upcase pattern) table))
13531 (message "Already complete")
13532 (if (equal type :opt)
13533 (insert (substring (cdr (assoc (upcase pattern) table))
13534 (length pattern)))
13535 (if (memq type '(:tag :prop)) (insert ":")))))
13536 ((null completion)
13537 (message "Can't find completion for \"%s\"" pattern)
13538 (ding))
13539 ((not (string= pattern completion))
13540 (delete-region beg end)
13541 (if (string-match " +$" completion)
13542 (setq completion (replace-match "" t t completion)))
13543 (insert completion)
13544 (if (get-buffer-window "*Completions*")
13545 (delete-window (get-buffer-window "*Completions*")))
13546 (if (assoc completion table)
13547 (if (eq type :todo) (insert " ")
13548 (if (memq type '(:tag :prop)) (insert ":"))))
13549 (if (and (equal type :opt) (assoc completion table))
13550 (message "%s" (substitute-command-keys
13551 "Press \\[org-complete] again to insert example settings"))))
13553 (message "Making completion list...")
13554 (let ((list (sort (all-completions pattern table confirm)
13555 'string<)))
13556 (with-output-to-temp-buffer "*Completions*"
13557 (condition-case nil
13558 ;; Protection needed for XEmacs and emacs 21
13559 (display-completion-list list pattern)
13560 (error (display-completion-list list)))))
13561 (message "Making completion list...%s" "done")))))))
13563 ;;;; TODO, DEADLINE, Comments
13565 (defun org-toggle-comment ()
13566 "Change the COMMENT state of an entry."
13567 (interactive)
13568 (save-excursion
13569 (org-back-to-heading)
13570 (let (case-fold-search)
13571 (if (looking-at (concat outline-regexp
13572 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
13573 (replace-match "" t t nil 1)
13574 (if (looking-at outline-regexp)
13575 (progn
13576 (goto-char (match-end 0))
13577 (insert org-comment-string " ")))))))
13579 (defvar org-last-todo-state-is-todo nil
13580 "This is non-nil when the last TODO state change led to a TODO state.
13581 If the last change removed the TODO tag or switched to DONE, then
13582 this is nil.")
13584 (defvar org-setting-tags nil) ; dynamically skiped
13586 ;; FIXME: better place
13587 (defun org-property-or-variable-value (var &optional inherit)
13588 "Check if there is a property fixing the value of VAR.
13589 If yes, return this value. If not, return the current value of the variable."
13590 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
13591 (if (and prop (stringp prop) (string-match "\\S-" prop))
13592 (read prop)
13593 (symbol-value var))))
13595 (defun org-parse-local-options (string var)
13596 "Parse STRING for startup setting relevant for variable VAR."
13597 (let ((rtn (symbol-value var))
13598 e opts)
13599 (save-match-data
13600 (if (or (not string) (not (string-match "\\S-" string)))
13602 (setq opts (delq nil (mapcar (lambda (x)
13603 (setq e (assoc x org-startup-options))
13604 (if (eq (nth 1 e) var) e nil))
13605 (org-split-string string "[ \t]+"))))
13606 (if (not opts)
13608 (setq rtn nil)
13609 (while (setq e (pop opts))
13610 (if (not (nth 3 e))
13611 (setq rtn (nth 2 e))
13612 (if (not (listp rtn)) (setq rtn nil))
13613 (push (nth 2 e) rtn)))
13614 rtn)))))
13616 (defvar org-blocker-hook nil
13617 "Hook for functions that are allowed to block a state change.
13619 Each function gets as its single argument a property list, see
13620 `org-trigger-hook' for more information about this list.
13622 If any of the functions in this hook returns nil, the state change
13623 is blocked.")
13625 (defvar org-trigger-hook nil
13626 "Hook for functions that are triggered by a state change.
13628 Each function gets as its single argument a property list with at least
13629 the following elements:
13631 (:type type-of-change :position pos-at-entry-start
13632 :from old-state :to new-state)
13634 Depending on the type, more properties may be present.
13636 This mechanism is currently implemented for:
13638 TODO state changes
13639 ------------------
13640 :type todo-state-change
13641 :from previous state (keyword as a string), or nil
13642 :to new state (keyword as a string), or nil")
13645 (defun org-todo (&optional arg)
13646 "Change the TODO state of an item.
13647 The state of an item is given by a keyword at the start of the heading,
13648 like
13649 *** TODO Write paper
13650 *** DONE Call mom
13652 The different keywords are specified in the variable `org-todo-keywords'.
13653 By default the available states are \"TODO\" and \"DONE\".
13654 So for this example: when the item starts with TODO, it is changed to DONE.
13655 When it starts with DONE, the DONE is removed. And when neither TODO nor
13656 DONE are present, add TODO at the beginning of the heading.
13658 With C-u prefix arg, use completion to determine the new state.
13659 With numeric prefix arg, switch to that state.
13661 For calling through lisp, arg is also interpreted in the following way:
13662 'none -> empty state
13663 \"\"(empty string) -> switch to empty state
13664 'done -> switch to DONE
13665 'nextset -> switch to the next set of keywords
13666 'previousset -> switch to the previous set of keywords
13667 \"WAITING\" -> switch to the specified keyword, but only if it
13668 really is a member of `org-todo-keywords'."
13669 (interactive "P")
13670 (save-excursion
13671 (catch 'exit
13672 (org-back-to-heading)
13673 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
13674 (or (looking-at (concat " +" org-todo-regexp " *"))
13675 (looking-at " *"))
13676 (let* ((match-data (match-data))
13677 (startpos (point-at-bol))
13678 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
13679 (org-log-done (org-parse-local-options logging 'org-log-done))
13680 (org-log-repeat (org-parse-local-options logging 'org-log-repeat))
13681 (this (match-string 1))
13682 (hl-pos (match-beginning 0))
13683 (head (org-get-todo-sequence-head this))
13684 (ass (assoc head org-todo-kwd-alist))
13685 (interpret (nth 1 ass))
13686 (done-word (nth 3 ass))
13687 (final-done-word (nth 4 ass))
13688 (last-state (or this ""))
13689 (completion-ignore-case t)
13690 (member (member this org-todo-keywords-1))
13691 (tail (cdr member))
13692 (state (cond
13693 ((and org-todo-key-trigger
13694 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
13695 (and (not arg) org-use-fast-todo-selection
13696 (not (eq org-use-fast-todo-selection 'prefix)))))
13697 ;; Use fast selection
13698 (org-fast-todo-selection))
13699 ((and (equal arg '(4))
13700 (or (not org-use-fast-todo-selection)
13701 (not org-todo-key-trigger)))
13702 ;; Read a state with completion
13703 (completing-read "State: " (mapcar (lambda(x) (list x))
13704 org-todo-keywords-1)
13705 nil t))
13706 ((eq arg 'right)
13707 (if this
13708 (if tail (car tail) nil)
13709 (car org-todo-keywords-1)))
13710 ((eq arg 'left)
13711 (if (equal member org-todo-keywords-1)
13713 (if this
13714 (nth (- (length org-todo-keywords-1) (length tail) 2)
13715 org-todo-keywords-1)
13716 (org-last org-todo-keywords-1))))
13717 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
13718 (setq arg nil))) ; hack to fall back to cycling
13719 (arg
13720 ;; user or caller requests a specific state
13721 (cond
13722 ((equal arg "") nil)
13723 ((eq arg 'none) nil)
13724 ((eq arg 'done) (or done-word (car org-done-keywords)))
13725 ((eq arg 'nextset)
13726 (or (car (cdr (member head org-todo-heads)))
13727 (car org-todo-heads)))
13728 ((eq arg 'previousset)
13729 (let ((org-todo-heads (reverse org-todo-heads)))
13730 (or (car (cdr (member head org-todo-heads)))
13731 (car org-todo-heads))))
13732 ((car (member arg org-todo-keywords-1)))
13733 ((nth (1- (prefix-numeric-value arg))
13734 org-todo-keywords-1))))
13735 ((null member) (or head (car org-todo-keywords-1)))
13736 ((equal this final-done-word) nil) ;; -> make empty
13737 ((null tail) nil) ;; -> first entry
13738 ((eq interpret 'sequence)
13739 (car tail))
13740 ((memq interpret '(type priority))
13741 (if (eq this-command last-command)
13742 (car tail)
13743 (if (> (length tail) 0)
13744 (or done-word (car org-done-keywords))
13745 nil)))
13746 (t nil)))
13747 (next (if state (concat " " state " ") " "))
13748 (change-plist (list :type 'todo-state-change :from this :to state
13749 :position startpos))
13750 dostates)
13751 (when org-blocker-hook
13752 (unless (save-excursion
13753 (save-match-data
13754 (run-hook-with-args-until-failure
13755 'org-blocker-hook change-plist)))
13756 (if (interactive-p)
13757 (error "TODO state change from %s to %s blocked" this state)
13758 ;; fail silently
13759 (message "TODO state change from %s to %s blocked" this state)
13760 (throw 'exit nil))))
13761 (store-match-data match-data)
13762 (replace-match next t t)
13763 (unless (pos-visible-in-window-p hl-pos)
13764 (message "TODO state changed to %s" (org-trim next)))
13765 (unless head
13766 (setq head (org-get-todo-sequence-head state)
13767 ass (assoc head org-todo-kwd-alist)
13768 interpret (nth 1 ass)
13769 done-word (nth 3 ass)
13770 final-done-word (nth 4 ass)))
13771 (when (memq arg '(nextset previousset))
13772 (message "Keyword-Set %d/%d: %s"
13773 (- (length org-todo-sets) -1
13774 (length (memq (assoc state org-todo-sets) org-todo-sets)))
13775 (length org-todo-sets)
13776 (mapconcat 'identity (assoc state org-todo-sets) " ")))
13777 (setq org-last-todo-state-is-todo
13778 (not (member state org-done-keywords)))
13779 (when (and org-log-done (not (memq arg '(nextset previousset))))
13780 (setq dostates (and (listp org-log-done) (memq 'state org-log-done)
13781 (or (not org-todo-log-states)
13782 (member state org-todo-log-states))))
13784 (cond
13785 ((and state (member state org-not-done-keywords)
13786 (not (member this org-not-done-keywords)))
13787 ;; This is now a todo state and was not one before
13788 ;; Remove any CLOSED timestamp, and possibly log the state change
13789 (org-add-planning-info nil nil 'closed)
13790 (and dostates (org-add-log-maybe 'state state 'findpos)))
13791 ((and state dostates)
13792 ;; This is a non-nil state, and we need to log it
13793 (org-add-log-maybe 'state state 'findpos))
13794 ((and (member state org-done-keywords)
13795 (not (member this org-done-keywords)))
13796 ;; It is now done, and it was not done before
13797 (org-add-planning-info 'closed (org-current-time))
13798 (org-add-log-maybe 'done state 'findpos))))
13799 ;; Fixup tag positioning
13800 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
13801 (run-hooks 'org-after-todo-state-change-hook)
13802 (and (member state org-done-keywords) (org-auto-repeat-maybe))
13803 (if (and arg (not (member state org-done-keywords)))
13804 (setq head (org-get-todo-sequence-head state)))
13805 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
13806 ;; Fixup cursor location if close to the keyword
13807 (if (and (outline-on-heading-p)
13808 (not (bolp))
13809 (save-excursion (beginning-of-line 1)
13810 (looking-at org-todo-line-regexp))
13811 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
13812 (progn
13813 (goto-char (or (match-end 2) (match-end 1)))
13814 (just-one-space)))
13815 (when org-trigger-hook
13816 (save-excursion
13817 (run-hook-with-args 'org-trigger-hook change-plist)))))))
13819 (defun org-get-todo-sequence-head (kwd)
13820 "Return the head of the TODO sequence to which KWD belongs.
13821 If KWD is not set, check if there is a text property remembering the
13822 right sequence."
13823 (let (p)
13824 (cond
13825 ((not kwd)
13826 (or (get-text-property (point-at-bol) 'org-todo-head)
13827 (progn
13828 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13829 nil (point-at-eol)))
13830 (get-text-property p 'org-todo-head))))
13831 ((not (member kwd org-todo-keywords-1))
13832 (car org-todo-keywords-1))
13833 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13835 (defun org-fast-todo-selection ()
13836 "Fast TODO keyword selection with single keys.
13837 Returns the new TODO keyword, or nil if no state change should occur."
13838 (let* ((fulltable org-todo-key-alist)
13839 (done-keywords org-done-keywords) ;; needed for the faces.
13840 (maxlen (apply 'max (mapcar
13841 (lambda (x)
13842 (if (stringp (car x)) (string-width (car x)) 0))
13843 fulltable)))
13844 (expert nil)
13845 (fwidth (+ maxlen 3 1 3))
13846 (ncol (/ (- (window-width) 4) fwidth))
13847 tg cnt e c tbl
13848 groups ingroup)
13849 (save-window-excursion
13850 (if expert
13851 (set-buffer (get-buffer-create " *Org todo*"))
13852 ; (delete-other-windows)
13853 ; (split-window-vertically)
13854 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13855 (erase-buffer)
13856 (org-set-local 'org-done-keywords done-keywords)
13857 (setq tbl fulltable cnt 0)
13858 (while (setq e (pop tbl))
13859 (cond
13860 ((equal e '(:startgroup))
13861 (push '() groups) (setq ingroup t)
13862 (when (not (= cnt 0))
13863 (setq cnt 0)
13864 (insert "\n"))
13865 (insert "{ "))
13866 ((equal e '(:endgroup))
13867 (setq ingroup nil cnt 0)
13868 (insert "}\n"))
13870 (setq tg (car e) c (cdr e))
13871 (if ingroup (push tg (car groups)))
13872 (setq tg (org-add-props tg nil 'face
13873 (org-get-todo-face tg)))
13874 (if (and (= cnt 0) (not ingroup)) (insert " "))
13875 (insert "[" c "] " tg (make-string
13876 (- fwidth 4 (length tg)) ?\ ))
13877 (when (= (setq cnt (1+ cnt)) ncol)
13878 (insert "\n")
13879 (if ingroup (insert " "))
13880 (setq cnt 0)))))
13881 (insert "\n")
13882 (goto-char (point-min))
13883 (if (and (not expert) (fboundp 'fit-window-to-buffer))
13884 (fit-window-to-buffer))
13885 (message "[a-z..]:Set [SPC]:clear")
13886 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13887 (cond
13888 ((or (= c ?\C-g)
13889 (and (= c ?q) (not (rassoc c fulltable))))
13890 (setq quit-flag t))
13891 ((= c ?\ ) nil)
13892 ((setq e (rassoc c fulltable) tg (car e))
13894 (t (setq quit-flag t))))))
13896 (defun org-get-repeat ()
13897 "Check if tere is a deadline/schedule with repeater in this entry."
13898 (save-match-data
13899 (save-excursion
13900 (org-back-to-heading t)
13901 (if (re-search-forward
13902 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
13903 (match-string 1)))))
13905 (defvar org-last-changed-timestamp)
13906 (defvar org-log-post-message)
13907 (defun org-auto-repeat-maybe ()
13908 "Check if the current headline contains a repeated deadline/schedule.
13909 If yes, set TODO state back to what it was and change the base date
13910 of repeating deadline/scheduled time stamps to new date.
13911 This function should be run in the `org-after-todo-state-change-hook'."
13912 ;; last-state is dynamically scoped into this function
13913 (let* ((repeat (org-get-repeat))
13914 (aa (assoc last-state org-todo-kwd-alist))
13915 (interpret (nth 1 aa))
13916 (head (nth 2 aa))
13917 (done-word (nth 3 aa))
13918 (whata '(("d" . day) ("m" . month) ("y" . year)))
13919 (msg "Entry repeats: ")
13920 (org-log-done)
13921 re type n what ts)
13922 (when repeat
13923 (org-todo (if (eq interpret 'type) last-state head))
13924 (when (and org-log-repeat
13925 (not (memq 'org-add-log-note
13926 (default-value 'post-command-hook))))
13927 ;; Make sure a note is taken
13928 (let ((org-log-done '(done)))
13929 (org-add-log-maybe 'done (or done-word (car org-done-keywords))
13930 'findpos)))
13931 (org-back-to-heading t)
13932 (org-add-planning-info nil nil 'closed)
13933 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
13934 org-deadline-time-regexp "\\)"))
13935 (while (re-search-forward
13936 re (save-excursion (outline-next-heading) (point)) t)
13937 (setq type (if (match-end 1) org-scheduled-string org-deadline-string)
13938 ts (match-string (if (match-end 2) 2 4)))
13939 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
13940 (setq n (string-to-number (match-string 1 ts))
13941 what (match-string 2 ts))
13942 (if (equal what "w") (setq n (* n 7) what "d"))
13943 (org-timestamp-change n (cdr (assoc what whata))))
13944 (setq msg (concat msg type org-last-changed-timestamp " ")))
13945 (setq org-log-post-message msg)
13946 (message msg))))
13948 (defun org-show-todo-tree (arg)
13949 "Make a compact tree which shows all headlines marked with TODO.
13950 The tree will show the lines where the regexp matches, and all higher
13951 headlines above the match.
13952 With \\[universal-argument] prefix, also show the DONE entries.
13953 With a numeric prefix N, construct a sparse tree for the Nth element
13954 of `org-todo-keywords-1'."
13955 (interactive "P")
13956 (let ((case-fold-search nil)
13957 (kwd-re
13958 (cond ((null arg) org-not-done-regexp)
13959 ((equal arg '(4))
13960 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
13961 (mapcar 'list org-todo-keywords-1))))
13962 (concat "\\("
13963 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13964 "\\)\\>")))
13965 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13966 (regexp-quote (nth (1- (prefix-numeric-value arg))
13967 org-todo-keywords-1)))
13968 (t (error "Invalid prefix argument: %s" arg)))))
13969 (message "%d TODO entries found"
13970 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
13972 (defun org-deadline (&optional remove)
13973 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13974 With argument REMOVE, remove any deadline from the item."
13975 (interactive "P")
13976 (if remove
13977 (progn
13978 (org-add-planning-info nil nil 'deadline)
13979 (message "Item no longer has a deadline."))
13980 (org-add-planning-info 'deadline nil 'closed)))
13982 (defun org-schedule (&optional remove)
13983 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13984 With argument REMOVE, remove any scheduling date from the item."
13985 (interactive "P")
13986 (if remove
13987 (progn
13988 (org-add-planning-info nil nil 'scheduled)
13989 (message "Item is no longer scheduled."))
13990 (org-add-planning-info 'scheduled nil 'closed)))
13992 (defun org-add-planning-info (what &optional time &rest remove)
13993 "Insert new timestamp with keyword in the line directly after the headline.
13994 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
13995 If non is given, the user is prompted for a date.
13996 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
13997 be removed."
13998 (interactive)
13999 (let (org-time-was-given org-end-time-was-given)
14000 (when what (setq time (or time (org-read-date nil 'to-time))))
14001 (when (and org-insert-labeled-timestamps-at-point
14002 (member what '(scheduled deadline)))
14003 (insert
14004 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
14005 (org-insert-time-stamp time org-time-was-given
14006 nil nil nil (list org-end-time-was-given))
14007 (setq what nil))
14008 (save-excursion
14009 (save-restriction
14010 (let (col list elt ts buffer-invisibility-spec)
14011 (org-back-to-heading t)
14012 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
14013 (goto-char (match-end 1))
14014 (setq col (current-column))
14015 (goto-char (match-end 0))
14016 (if (eobp) (insert "\n") (forward-char 1))
14017 (if (and (not (looking-at outline-regexp))
14018 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
14019 "[^\r\n]*"))
14020 (not (equal (match-string 1) org-clock-string)))
14021 (narrow-to-region (match-beginning 0) (match-end 0))
14022 (insert-before-markers "\n")
14023 (backward-char 1)
14024 (narrow-to-region (point) (point))
14025 (indent-to-column col))
14026 ;; Check if we have to remove something.
14027 (setq list (cons what remove))
14028 (while list
14029 (setq elt (pop list))
14030 (goto-char (point-min))
14031 (when (or (and (eq elt 'scheduled)
14032 (re-search-forward org-scheduled-time-regexp nil t))
14033 (and (eq elt 'deadline)
14034 (re-search-forward org-deadline-time-regexp nil t))
14035 (and (eq elt 'closed)
14036 (re-search-forward org-closed-time-regexp nil t)))
14037 (replace-match "")
14038 (if (looking-at "--+<[^>]+>") (replace-match ""))
14039 (if (looking-at " +") (replace-match ""))))
14040 (goto-char (point-max))
14041 (when what
14042 (insert
14043 (if (not (equal (char-before) ?\ )) " " "")
14044 (cond ((eq what 'scheduled) org-scheduled-string)
14045 ((eq what 'deadline) org-deadline-string)
14046 ((eq what 'closed) org-closed-string))
14047 " ")
14048 (setq ts (org-insert-time-stamp
14049 time
14050 (or org-time-was-given
14051 (and (eq what 'closed) org-log-done-with-time))
14052 (eq what 'closed)
14053 nil nil (list org-end-time-was-given)))
14054 (end-of-line 1))
14055 (goto-char (point-min))
14056 (widen)
14057 (if (looking-at "[ \t]+\r?\n")
14058 (replace-match ""))
14059 ts)))))
14061 (defvar org-log-note-marker (make-marker))
14062 (defvar org-log-note-purpose nil)
14063 (defvar org-log-note-state nil)
14064 (defvar org-log-note-window-configuration nil)
14065 (defvar org-log-note-return-to (make-marker))
14066 (defvar org-log-post-message nil
14067 "Message to be displayed after a log note has been stored.
14068 The auto-repeater uses this.")
14070 (defun org-add-log-maybe (&optional purpose state findpos)
14071 "Set up the post command hook to take a note."
14072 (save-excursion
14073 (when (and (listp org-log-done)
14074 (memq purpose org-log-done))
14075 (when findpos
14076 (org-back-to-heading t)
14077 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
14078 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
14079 "[^\r\n]*\\)?"))
14080 (goto-char (match-end 0))
14081 (unless org-log-states-order-reversed
14082 (and (= (char-after) ?\n) (forward-char 1))
14083 (org-skip-over-state-notes)
14084 (skip-chars-backward " \t\n\r")))
14085 (move-marker org-log-note-marker (point))
14086 (setq org-log-note-purpose purpose)
14087 (setq org-log-note-state state)
14088 (add-hook 'post-command-hook 'org-add-log-note 'append))))
14090 (defun org-skip-over-state-notes ()
14091 "Skip past the list of State notes in an entry."
14092 (if (looking-at "\n[ \t]*- State") (forward-char 1))
14093 (while (looking-at "[ \t]*- State")
14094 (condition-case nil
14095 (org-next-item)
14096 (error (org-end-of-item)))))
14098 (defun org-add-log-note (&optional purpose)
14099 "Pop up a window for taking a note, and add this note later at point."
14100 (remove-hook 'post-command-hook 'org-add-log-note)
14101 (setq org-log-note-window-configuration (current-window-configuration))
14102 (delete-other-windows)
14103 (move-marker org-log-note-return-to (point))
14104 (switch-to-buffer (marker-buffer org-log-note-marker))
14105 (goto-char org-log-note-marker)
14106 (org-switch-to-buffer-other-window "*Org Note*")
14107 (erase-buffer)
14108 (let ((org-inhibit-startup t)) (org-mode))
14109 (insert (format "# Insert note for %s.
14110 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
14111 (cond
14112 ((eq org-log-note-purpose 'clock-out) "stopped clock")
14113 ((eq org-log-note-purpose 'done) "closed todo item")
14114 ((eq org-log-note-purpose 'state)
14115 (format "state change to \"%s\"" org-log-note-state))
14116 (t (error "This should not happen")))))
14117 (org-set-local 'org-finish-function 'org-store-log-note))
14119 (defun org-store-log-note ()
14120 "Finish taking a log note, and insert it to where it belongs."
14121 (let ((txt (buffer-string))
14122 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
14123 lines ind)
14124 (kill-buffer (current-buffer))
14125 (while (string-match "\\`#.*\n[ \t\n]*" txt)
14126 (setq txt (replace-match "" t t txt)))
14127 (if (string-match "\\s-+\\'" txt)
14128 (setq txt (replace-match "" t t txt)))
14129 (setq lines (org-split-string txt "\n"))
14130 (when (and note (string-match "\\S-" note))
14131 (setq note
14132 (org-replace-escapes
14133 note
14134 (list (cons "%u" (user-login-name))
14135 (cons "%U" user-full-name)
14136 (cons "%t" (format-time-string
14137 (org-time-stamp-format 'long 'inactive)
14138 (current-time)))
14139 (cons "%s" (if org-log-note-state
14140 (concat "\"" org-log-note-state "\"")
14141 "")))))
14142 (if lines (setq note (concat note " \\\\")))
14143 (push note lines))
14144 (when (or current-prefix-arg org-note-abort) (setq lines nil))
14145 (when lines
14146 (save-excursion
14147 (set-buffer (marker-buffer org-log-note-marker))
14148 (save-excursion
14149 (goto-char org-log-note-marker)
14150 (move-marker org-log-note-marker nil)
14151 (end-of-line 1)
14152 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
14153 (indent-relative nil)
14154 (insert "- " (pop lines))
14155 (org-indent-line-function)
14156 (beginning-of-line 1)
14157 (looking-at "[ \t]*")
14158 (setq ind (concat (match-string 0) " "))
14159 (end-of-line 1)
14160 (while lines (insert "\n" ind (pop lines)))))))
14161 (set-window-configuration org-log-note-window-configuration)
14162 (with-current-buffer (marker-buffer org-log-note-return-to)
14163 (goto-char org-log-note-return-to))
14164 (move-marker org-log-note-return-to nil)
14165 (and org-log-post-message (message org-log-post-message)))
14167 ;; FIXME: what else would be useful?
14168 ;; - priority
14169 ;; - date
14171 (defun org-sparse-tree (&optional arg)
14172 "Create a sparse tree, prompt for the details.
14173 This command can create sparse trees. You first need to select the type
14174 of match used to create the tree:
14176 t Show entries with a specific TODO keyword.
14177 T Show entries selected by a tags match.
14178 p Enter a property name and its value (both with completion on existing
14179 names/values) and show entries with that property.
14180 r Show entries matching a regular expression"
14181 (interactive "P")
14182 (let (ans kwd value)
14183 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines")
14184 (setq ans (read-char-exclusive))
14185 (cond
14186 ((equal ans ?d)
14187 (call-interactively 'org-check-deadlines))
14188 ((equal ans ?t)
14189 (org-show-todo-tree '(4)))
14190 ((equal ans ?T)
14191 (call-interactively 'org-tags-sparse-tree))
14192 ((member ans '(?p ?P))
14193 (setq kwd (completing-read "Property: "
14194 (mapcar 'list (org-buffer-property-keys))))
14195 (setq value (completing-read "Value: "
14196 (mapcar 'list (org-property-values kwd))))
14197 (unless (string-match "\\`{.*}\\'" value)
14198 (setq value (concat "\"" value "\"")))
14199 (org-tags-sparse-tree arg (concat kwd "=" value)))
14200 ((member ans '(?r ?R ?/))
14201 (call-interactively 'org-occur))
14202 (t (error "No such sparse tree command \"%c\"" ans)))))
14204 (defvar org-occur-highlights nil)
14205 (make-variable-buffer-local 'org-occur-highlights)
14207 (defun org-occur (regexp &optional keep-previous callback)
14208 "Make a compact tree which shows all matches of REGEXP.
14209 The tree will show the lines where the regexp matches, and all higher
14210 headlines above the match. It will also show the heading after the match,
14211 to make sure editing the matching entry is easy.
14212 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
14213 call to `org-occur' will be kept, to allow stacking of calls to this
14214 command.
14215 If CALLBACK is non-nil, it is a function which is called to confirm
14216 that the match should indeed be shown."
14217 (interactive "sRegexp: \nP")
14218 (or keep-previous (org-remove-occur-highlights nil nil t))
14219 (let ((cnt 0))
14220 (save-excursion
14221 (goto-char (point-min))
14222 (if (or (not keep-previous) ; do not want to keep
14223 (not org-occur-highlights)) ; no previous matches
14224 ;; hide everything
14225 (org-overview))
14226 (while (re-search-forward regexp nil t)
14227 (when (or (not callback)
14228 (save-match-data (funcall callback)))
14229 (setq cnt (1+ cnt))
14230 (when org-highlight-sparse-tree-matches
14231 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14232 (org-show-context 'occur-tree))))
14233 (when org-remove-highlights-with-change
14234 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
14235 nil 'local))
14236 (unless org-sparse-tree-open-archived-trees
14237 (org-hide-archived-subtrees (point-min) (point-max)))
14238 (run-hooks 'org-occur-hook)
14239 (if (interactive-p)
14240 (message "%d match(es) for regexp %s" cnt regexp))
14241 cnt))
14243 (defun org-show-context (&optional key)
14244 "Make sure point and context and visible.
14245 How much context is shown depends upon the variables
14246 `org-show-hierarchy-above', `org-show-following-heading'. and
14247 `org-show-siblings'."
14248 (let ((heading-p (org-on-heading-p t))
14249 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
14250 (following-p (org-get-alist-option org-show-following-heading key))
14251 (entry-p (org-get-alist-option org-show-entry-below key))
14252 (siblings-p (org-get-alist-option org-show-siblings key)))
14253 (catch 'exit
14254 ;; Show heading or entry text
14255 (if (and heading-p (not entry-p))
14256 (org-flag-heading nil) ; only show the heading
14257 (and (or entry-p (org-invisible-p) (org-invisible-p2))
14258 (org-show-hidden-entry))) ; show entire entry
14259 (when following-p
14260 ;; Show next sibling, or heading below text
14261 (save-excursion
14262 (and (if heading-p (org-goto-sibling) (outline-next-heading))
14263 (org-flag-heading nil))))
14264 (when siblings-p (org-show-siblings))
14265 (when hierarchy-p
14266 ;; show all higher headings, possibly with siblings
14267 (save-excursion
14268 (while (and (condition-case nil
14269 (progn (org-up-heading-all 1) t)
14270 (error nil))
14271 (not (bobp)))
14272 (org-flag-heading nil)
14273 (when siblings-p (org-show-siblings))))))))
14275 (defun org-reveal (&optional siblings)
14276 "Show current entry, hierarchy above it, and the following headline.
14277 This can be used to show a consistent set of context around locations
14278 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
14279 not t for the search context.
14281 With optional argument SIBLINGS, on each level of the hierarchy all
14282 siblings are shown. This repairs the tree structure to what it would
14283 look like when opened with hierarchical calls to `org-cycle'."
14284 (interactive "P")
14285 (let ((org-show-hierarchy-above t)
14286 (org-show-following-heading t)
14287 (org-show-siblings (if siblings t org-show-siblings)))
14288 (org-show-context nil)))
14290 (defun org-highlight-new-match (beg end)
14291 "Highlight from BEG to END and mark the highlight is an occur headline."
14292 (let ((ov (org-make-overlay beg end)))
14293 (org-overlay-put ov 'face 'secondary-selection)
14294 (push ov org-occur-highlights)))
14296 (defun org-remove-occur-highlights (&optional beg end noremove)
14297 "Remove the occur highlights from the buffer.
14298 BEG and END are ignored. If NOREMOVE is nil, remove this function
14299 from the `before-change-functions' in the current buffer."
14300 (interactive)
14301 (unless org-inhibit-highlight-removal
14302 (mapc 'org-delete-overlay org-occur-highlights)
14303 (setq org-occur-highlights nil)
14304 (unless noremove
14305 (remove-hook 'before-change-functions
14306 'org-remove-occur-highlights 'local))))
14308 ;;;; Priorities
14310 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14311 "Regular expression matching the priority indicator.")
14313 (defvar org-remove-priority-next-time nil)
14315 (defun org-priority-up ()
14316 "Increase the priority of the current item."
14317 (interactive)
14318 (org-priority 'up))
14320 (defun org-priority-down ()
14321 "Decrease the priority of the current item."
14322 (interactive)
14323 (org-priority 'down))
14325 (defun org-priority (&optional action)
14326 "Change the priority of an item by ARG.
14327 ACTION can be `set', `up', `down', or a character."
14328 (interactive)
14329 (setq action (or action 'set))
14330 (let (current new news have remove)
14331 (save-excursion
14332 (org-back-to-heading)
14333 (if (looking-at org-priority-regexp)
14334 (setq current (string-to-char (match-string 2))
14335 have t)
14336 (setq current org-default-priority))
14337 (cond
14338 ((or (eq action 'set) (integerp action))
14339 (if (integerp action)
14340 (setq new action)
14341 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
14342 (setq new (read-char-exclusive)))
14343 (if (and (= (upcase org-highest-priority) org-highest-priority)
14344 (= (upcase org-lowest-priority) org-lowest-priority))
14345 (setq new (upcase new)))
14346 (cond ((equal new ?\ ) (setq remove t))
14347 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14348 (error "Priority must be between `%c' and `%c'"
14349 org-highest-priority org-lowest-priority))))
14350 ((eq action 'up)
14351 (if (and (not have) (eq last-command this-command))
14352 (setq new org-lowest-priority)
14353 (setq new (if (and org-priority-start-cycle-with-default (not have))
14354 org-default-priority (1- current)))))
14355 ((eq action 'down)
14356 (if (and (not have) (eq last-command this-command))
14357 (setq new org-highest-priority)
14358 (setq new (if (and org-priority-start-cycle-with-default (not have))
14359 org-default-priority (1+ current)))))
14360 (t (error "Invalid action")))
14361 (if (or (< (upcase new) org-highest-priority)
14362 (> (upcase new) org-lowest-priority))
14363 (setq remove t))
14364 (setq news (format "%c" new))
14365 (if have
14366 (if remove
14367 (replace-match "" t t nil 1)
14368 (replace-match news t t nil 2))
14369 (if remove
14370 (error "No priority cookie found in line")
14371 (looking-at org-todo-line-regexp)
14372 (if (match-end 2)
14373 (progn
14374 (goto-char (match-end 2))
14375 (insert " [#" news "]"))
14376 (goto-char (match-beginning 3))
14377 (insert "[#" news "] ")))))
14378 (org-preserve-lc (org-set-tags nil 'align))
14379 (if remove
14380 (message "Priority removed")
14381 (message "Priority of current item set to %s" news))))
14384 (defun org-get-priority (s)
14385 "Find priority cookie and return priority."
14386 (save-match-data
14387 (if (not (string-match org-priority-regexp s))
14388 (* 1000 (- org-lowest-priority org-default-priority))
14389 (* 1000 (- org-lowest-priority
14390 (string-to-char (match-string 2 s)))))))
14392 ;;;; Tags
14394 (defun org-scan-tags (action matcher &optional todo-only)
14395 "Scan headline tags with inheritance and produce output ACTION.
14396 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
14397 evaluated, testing if a given set of tags qualifies a headline for
14398 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
14399 are included in the output."
14400 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
14401 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14402 (org-re
14403 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
14404 (props (list 'face nil
14405 'done-face 'org-done
14406 'undone-face nil
14407 'mouse-face 'highlight
14408 'org-not-done-regexp org-not-done-regexp
14409 'org-todo-regexp org-todo-regexp
14410 'keymap org-agenda-keymap
14411 'help-echo
14412 (format "mouse-2 or RET jump to org file %s"
14413 (abbreviate-file-name
14414 (or (buffer-file-name (buffer-base-buffer))
14415 (buffer-name (buffer-base-buffer)))))))
14416 (case-fold-search nil)
14417 lspos
14418 tags tags-list tags-alist (llast 0) rtn level category i txt
14419 todo marker entry priority)
14420 (save-excursion
14421 (goto-char (point-min))
14422 (when (eq action 'sparse-tree)
14423 (org-overview)
14424 (org-remove-occur-highlights))
14425 (while (re-search-forward re nil t)
14426 (catch :skip
14427 (setq todo (if (match-end 1) (match-string 2))
14428 tags (if (match-end 4) (match-string 4)))
14429 (goto-char (setq lspos (1+ (match-beginning 0))))
14430 (setq level (org-reduced-level (funcall outline-level))
14431 category (org-get-category))
14432 (setq i llast llast level)
14433 ;; remove tag lists from same and sublevels
14434 (while (>= i level)
14435 (when (setq entry (assoc i tags-alist))
14436 (setq tags-alist (delete entry tags-alist)))
14437 (setq i (1- i)))
14438 ;; add the nex tags
14439 (when tags
14440 (setq tags (mapcar 'downcase (org-split-string tags ":"))
14441 tags-alist
14442 (cons (cons level tags) tags-alist)))
14443 ;; compile tags for current headline
14444 (setq tags-list
14445 (if org-use-tag-inheritance
14446 (apply 'append (mapcar 'cdr tags-alist))
14447 tags))
14448 (when (and (or (not todo-only) (member todo org-not-done-keywords))
14449 (eval matcher)
14450 (or (not org-agenda-skip-archived-trees)
14451 (not (member org-archive-tag tags-list))))
14452 (and (eq action 'agenda) (org-agenda-skip))
14453 ;; list this headline
14455 (if (eq action 'sparse-tree)
14456 (progn
14457 (and org-highlight-sparse-tree-matches
14458 (org-get-heading) (match-end 0)
14459 (org-highlight-new-match
14460 (match-beginning 0) (match-beginning 1)))
14461 (org-show-context 'tags-tree))
14462 (setq txt (org-format-agenda-item
14464 (concat
14465 (if org-tags-match-list-sublevels
14466 (make-string (1- level) ?.) "")
14467 (org-get-heading))
14468 category tags-list)
14469 priority (org-get-priority txt))
14470 (goto-char lspos)
14471 (setq marker (org-agenda-new-marker))
14472 (org-add-props txt props
14473 'org-marker marker 'org-hd-marker marker 'org-category category
14474 'priority priority 'type "tagsmatch")
14475 (push txt rtn))
14476 ;; if we are to skip sublevels, jump to end of subtree
14477 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
14478 (when (and (eq action 'sparse-tree)
14479 (not org-sparse-tree-open-archived-trees))
14480 (org-hide-archived-subtrees (point-min) (point-max)))
14481 (nreverse rtn)))
14483 (defvar todo-only) ;; dynamically scoped
14485 (defun org-tags-sparse-tree (&optional todo-only match)
14486 "Create a sparse tree according to tags string MATCH.
14487 MATCH can contain positive and negative selection of tags, like
14488 \"+WORK+URGENT-WITHBOSS\".
14489 If optional argument TODO_ONLY is non-nil, only select lines that are
14490 also TODO lines."
14491 (interactive "P")
14492 (org-prepare-agenda-buffers (list (current-buffer)))
14493 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
14495 (defvar org-cached-props nil)
14496 (defun org-cached-entry-get (pom property)
14497 (if (or (eq t org-use-property-inheritance)
14498 (member property org-use-property-inheritance))
14499 ;; Caching is not possible, check it directly
14500 (org-entry-get pom property 'inherit)
14501 ;; Get all properties, so that we can do complicated checks easily
14502 (cdr (assoc property (or org-cached-props
14503 (setq org-cached-props
14504 (org-entry-properties pom)))))))
14506 (defun org-global-tags-completion-table (&optional files)
14507 "Return the list of all tags in all agenda buffer/files."
14508 (save-excursion
14509 (org-uniquify
14510 (apply 'append
14511 (mapcar
14512 (lambda (file)
14513 (set-buffer (find-file-noselect file))
14514 (org-get-buffer-tags))
14515 (if (and files (car files))
14516 files
14517 (org-agenda-files)))))))
14519 (defun org-make-tags-matcher (match)
14520 "Create the TAGS//TODO matcher form for the selection string MATCH."
14521 ;; todo-only is scoped dynamically into this function, and the function
14522 ;; may change it it the matcher asksk for it.
14523 (unless match
14524 ;; Get a new match request, with completion
14525 (let ((org-last-tags-completion-table
14526 (org-global-tags-completion-table)))
14527 (setq match (completing-read
14528 "Match: " 'org-tags-completion-function nil nil nil
14529 'org-tags-history))))
14531 ;; Parse the string and create a lisp form
14532 (let ((match0 match)
14533 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]+\"\\)\\|[[:alnum:]_@]+\\)"))
14534 minus tag mm
14535 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
14536 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
14537 (if (string-match "/+" match)
14538 ;; match contains also a todo-matching request
14539 (progn
14540 (setq tagsmatch (substring match 0 (match-beginning 0))
14541 todomatch (substring match (match-end 0)))
14542 (if (string-match "^!" todomatch)
14543 (setq todo-only t todomatch (substring todomatch 1)))
14544 (if (string-match "^\\s-*$" todomatch)
14545 (setq todomatch nil)))
14546 ;; only matching tags
14547 (setq tagsmatch match todomatch nil))
14549 ;; Make the tags matcher
14550 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
14551 (setq tagsmatcher t)
14552 (setq orterms (org-split-string tagsmatch "|") orlist nil)
14553 (while (setq term (pop orterms))
14554 (while (and (equal (substring term -1) "\\") orterms)
14555 (setq term (concat term "|" (pop orterms)))) ; repair bad split
14556 (while (string-match re term)
14557 (setq minus (and (match-end 1)
14558 (equal (match-string 1 term) "-"))
14559 tag (match-string 2 term)
14560 re-p (equal (string-to-char tag) ?{)
14561 level-p (match-end 3)
14562 prop-p (match-end 4)
14563 mm (cond
14564 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
14565 (level-p `(= level ,(string-to-number
14566 (match-string 3 term))))
14567 (prop-p
14568 (setq pn (match-string 4 term)
14569 pv (match-string 5 term)
14570 cat-p (equal pn "CATEGORY")
14571 re-p (equal (string-to-char pv) ?{)
14572 pv (substring pv 1 -1))
14573 (if (equal pn "CATEGORY")
14574 (setq gv '(get-text-property (point) 'org-category))
14575 (setq gv `(org-cached-entry-get nil ,pn)))
14576 (if re-p
14577 `(string-match ,pv (or ,gv ""))
14578 `(equal ,pv ,gv)))
14579 (t `(member ,(downcase tag) tags-list)))
14580 mm (if minus (list 'not mm) mm)
14581 term (substring term (match-end 0)))
14582 (push mm tagsmatcher))
14583 (push (if (> (length tagsmatcher) 1)
14584 (cons 'and tagsmatcher)
14585 (car tagsmatcher))
14586 orlist)
14587 (setq tagsmatcher nil))
14588 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
14589 (setq tagsmatcher
14590 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
14592 ;; Make the todo matcher
14593 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
14594 (setq todomatcher t)
14595 (setq orterms (org-split-string todomatch "|") orlist nil)
14596 (while (setq term (pop orterms))
14597 (while (string-match re term)
14598 (setq minus (and (match-end 1)
14599 (equal (match-string 1 term) "-"))
14600 kwd (match-string 2 term)
14601 re-p (equal (string-to-char kwd) ?{)
14602 term (substring term (match-end 0))
14603 mm (if re-p
14604 `(string-match ,(substring kwd 1 -1) todo)
14605 (list 'equal 'todo kwd))
14606 mm (if minus (list 'not mm) mm))
14607 (push mm todomatcher))
14608 (push (if (> (length todomatcher) 1)
14609 (cons 'and todomatcher)
14610 (car todomatcher))
14611 orlist)
14612 (setq todomatcher nil))
14613 (setq todomatcher (if (> (length orlist) 1)
14614 (cons 'or orlist) (car orlist))))
14616 ;; Return the string and lisp forms of the matcher
14617 (setq matcher (if todomatcher
14618 (list 'and tagsmatcher todomatcher)
14619 tagsmatcher))
14620 (cons match0 matcher)))
14622 (defun org-match-any-p (re list)
14623 "Does re match any element of list?"
14624 (setq list (mapcar (lambda (x) (string-match re x)) list))
14625 (delq nil list))
14627 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
14628 (defvar org-tags-overlay (org-make-overlay 1 1))
14629 (org-detach-overlay org-tags-overlay)
14631 (defun org-align-tags-here (to-col)
14632 ;; Assumes that this is a headline
14633 (let ((pos (point)) (col (current-column)) tags)
14634 (beginning-of-line 1)
14635 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14636 (< pos (match-beginning 2)))
14637 (progn
14638 (setq tags (match-string 2))
14639 (goto-char (match-beginning 1))
14640 (insert " ")
14641 (delete-region (point) (1+ (match-end 0)))
14642 (backward-char 1)
14643 (move-to-column
14644 (max (1+ (current-column))
14645 (1+ col)
14646 (if (> to-col 0)
14647 to-col
14648 (- (abs to-col) (length tags))))
14650 (insert tags)
14651 (move-to-column (min (current-column) col) t))
14652 (goto-char pos))))
14654 (defun org-set-tags (&optional arg just-align)
14655 "Set the tags for the current headline.
14656 With prefix ARG, realign all tags in headings in the current buffer."
14657 (interactive "P")
14658 (let* ((re (concat "^" outline-regexp))
14659 (current (org-get-tags-string))
14660 (col (current-column))
14661 (org-setting-tags t)
14662 table current-tags inherited-tags ; computed below when needed
14663 tags p0 c0 c1 rpl)
14664 (if arg
14665 (save-excursion
14666 (goto-char (point-min))
14667 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14668 (while (re-search-forward re nil t)
14669 (org-set-tags nil t)
14670 (end-of-line 1)))
14671 (message "All tags realigned to column %d" org-tags-column))
14672 (if just-align
14673 (setq tags current)
14674 ;; Get a new set of tags from the user
14675 (save-excursion
14676 (setq table (or org-tag-alist (org-get-buffer-tags))
14677 org-last-tags-completion-table table
14678 current-tags (org-split-string current ":")
14679 inherited-tags (nreverse
14680 (nthcdr (length current-tags)
14681 (nreverse (org-get-tags-at))))
14682 tags
14683 (if (or (eq t org-use-fast-tag-selection)
14684 (and org-use-fast-tag-selection
14685 (delq nil (mapcar 'cdr table))))
14686 (org-fast-tag-selection
14687 current-tags inherited-tags table
14688 (if org-fast-tag-selection-include-todo org-todo-key-alist))
14689 (let ((org-add-colon-after-tag-completion t))
14690 (org-trim
14691 (org-without-partial-completion
14692 (completing-read "Tags: " 'org-tags-completion-function
14693 nil nil current 'org-tags-history)))))))
14694 (while (string-match "[-+&]+" tags)
14695 ;; No boolean logic, just a list
14696 (setq tags (replace-match ":" t t tags))))
14698 (if (string-match "\\`[\t ]*\\'" tags)
14699 (setq tags "")
14700 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
14701 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
14703 ;; Insert new tags at the correct column
14704 (beginning-of-line 1)
14705 (cond
14706 ((and (equal current "") (equal tags "")))
14707 ((re-search-forward
14708 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14709 (point-at-eol) t)
14710 (if (equal tags "")
14711 (setq rpl "")
14712 (goto-char (match-beginning 0))
14713 (setq c0 (current-column) p0 (point)
14714 c1 (max (1+ c0) (if (> org-tags-column 0)
14715 org-tags-column
14716 (- (- org-tags-column) (length tags))))
14717 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
14718 (replace-match rpl t t)
14719 (and (not (featurep 'xemacs)) c0 (tabify p0 (point)))
14720 tags)
14721 (t (error "Tags alignment failed")))
14722 (move-to-column col)
14723 (unless just-align
14724 (run-hooks 'org-after-tags-change-hook)))))
14726 (defun org-change-tag-in-region (beg end tag off)
14727 "Add or remove TAG for each entry in the region.
14728 This works in the agenda, and also in an org-mode buffer."
14729 (interactive
14730 (list (region-beginning) (region-end)
14731 (let ((org-last-tags-completion-table
14732 (if (org-mode-p)
14733 (org-get-buffer-tags)
14734 (org-global-tags-completion-table))))
14735 (completing-read
14736 "Tag: " 'org-tags-completion-function nil nil nil
14737 'org-tags-history))
14738 (progn
14739 (message "[s]et or [r]emove? ")
14740 (equal (read-char-exclusive) ?r))))
14741 (if (fboundp 'deactivate-mark) (deactivate-mark))
14742 (let ((agendap (equal major-mode 'org-agenda-mode))
14743 l1 l2 m buf pos newhead (cnt 0))
14744 (goto-char end)
14745 (setq l2 (1- (org-current-line)))
14746 (goto-char beg)
14747 (setq l1 (org-current-line))
14748 (loop for l from l1 to l2 do
14749 (goto-line l)
14750 (setq m (get-text-property (point) 'org-hd-marker))
14751 (when (or (and (org-mode-p) (org-on-heading-p))
14752 (and agendap m))
14753 (setq buf (if agendap (marker-buffer m) (current-buffer))
14754 pos (if agendap m (point)))
14755 (with-current-buffer buf
14756 (save-excursion
14757 (save-restriction
14758 (goto-char pos)
14759 (setq cnt (1+ cnt))
14760 (org-toggle-tag tag (if off 'off 'on))
14761 (setq newhead (org-get-heading)))))
14762 (and agendap (org-agenda-change-all-lines newhead m))))
14763 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
14765 (defun org-tags-completion-function (string predicate &optional flag)
14766 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
14767 (confirm (lambda (x) (stringp (car x)))))
14768 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
14769 (setq s1 (match-string 1 string)
14770 s2 (match-string 2 string))
14771 (setq s1 "" s2 string))
14772 (cond
14773 ((eq flag nil)
14774 ;; try completion
14775 (setq rtn (try-completion s2 ctable confirm))
14776 (if (stringp rtn)
14777 (setq rtn
14778 (concat s1 s2 (substring rtn (length s2))
14779 (if (and org-add-colon-after-tag-completion
14780 (assoc rtn ctable))
14781 ":" ""))))
14782 rtn)
14783 ((eq flag t)
14784 ;; all-completions
14785 (all-completions s2 ctable confirm)
14787 ((eq flag 'lambda)
14788 ;; exact match?
14789 (assoc s2 ctable)))
14792 (defun org-fast-tag-insert (kwd tags face &optional end)
14793 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
14794 (insert (format "%-12s" (concat kwd ":"))
14795 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
14796 (or end "")))
14798 (defun org-fast-tag-show-exit (flag)
14799 (save-excursion
14800 (goto-line 3)
14801 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
14802 (replace-match ""))
14803 (when flag
14804 (end-of-line 1)
14805 (move-to-column (- (window-width) 19) t)
14806 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
14808 (defun org-set-current-tags-overlay (current prefix)
14809 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
14810 (if (featurep 'xemacs)
14811 (org-overlay-display org-tags-overlay (concat prefix s)
14812 'secondary-selection)
14813 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
14814 (org-overlay-display org-tags-overlay (concat prefix s)))))
14816 (defun org-fast-tag-selection (current inherited table &optional todo-table)
14817 "Fast tag selection with single keys.
14818 CURRENT is the current list of tags in the headline, INHERITED is the
14819 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
14820 possibly with grouping information. TODO-TABLE is a similar table with
14821 TODO keywords, should these have keys assigned to them.
14822 If the keys are nil, a-z are automatically assigned.
14823 Returns the new tags string, or nil to not change the current settings."
14824 (let* ((fulltable (append table todo-table))
14825 (maxlen (apply 'max (mapcar
14826 (lambda (x)
14827 (if (stringp (car x)) (string-width (car x)) 0))
14828 fulltable)))
14829 (buf (current-buffer))
14830 (expert (eq org-fast-tag-selection-single-key 'expert))
14831 (buffer-tags nil)
14832 (fwidth (+ maxlen 3 1 3))
14833 (ncol (/ (- (window-width) 4) fwidth))
14834 (i-face 'org-done)
14835 (c-face 'org-todo)
14836 tg cnt e c char c1 c2 ntable tbl rtn
14837 ov-start ov-end ov-prefix
14838 (exit-after-next org-fast-tag-selection-single-key)
14839 (done-keywords org-done-keywords)
14840 groups ingroup)
14841 (save-excursion
14842 (beginning-of-line 1)
14843 (if (looking-at
14844 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14845 (setq ov-start (match-beginning 1)
14846 ov-end (match-end 1)
14847 ov-prefix "")
14848 (setq ov-start (1- (point-at-eol))
14849 ov-end (1+ ov-start))
14850 (skip-chars-forward "^\n\r")
14851 (setq ov-prefix
14852 (concat
14853 (buffer-substring (1- (point)) (point))
14854 (if (> (current-column) org-tags-column)
14856 (make-string (- org-tags-column (current-column)) ?\ ))))))
14857 (org-move-overlay org-tags-overlay ov-start ov-end)
14858 (save-window-excursion
14859 (if expert
14860 (set-buffer (get-buffer-create " *Org tags*"))
14861 (delete-other-windows)
14862 (split-window-vertically)
14863 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
14864 (erase-buffer)
14865 (org-set-local 'org-done-keywords done-keywords)
14866 (org-fast-tag-insert "Inherited" inherited i-face "\n")
14867 (org-fast-tag-insert "Current" current c-face "\n\n")
14868 (org-fast-tag-show-exit exit-after-next)
14869 (org-set-current-tags-overlay current ov-prefix)
14870 (setq tbl fulltable char ?a cnt 0)
14871 (while (setq e (pop tbl))
14872 (cond
14873 ((equal e '(:startgroup))
14874 (push '() groups) (setq ingroup t)
14875 (when (not (= cnt 0))
14876 (setq cnt 0)
14877 (insert "\n"))
14878 (insert "{ "))
14879 ((equal e '(:endgroup))
14880 (setq ingroup nil cnt 0)
14881 (insert "}\n"))
14883 (setq tg (car e) c2 nil)
14884 (if (cdr e)
14885 (setq c (cdr e))
14886 ;; automatically assign a character.
14887 (setq c1 (string-to-char
14888 (downcase (substring
14889 tg (if (= (string-to-char tg) ?@) 1 0)))))
14890 (if (or (rassoc c1 ntable) (rassoc c1 table))
14891 (while (or (rassoc char ntable) (rassoc char table))
14892 (setq char (1+ char)))
14893 (setq c2 c1))
14894 (setq c (or c2 char)))
14895 (if ingroup (push tg (car groups)))
14896 (setq tg (org-add-props tg nil 'face
14897 (cond
14898 ((not (assoc tg table))
14899 (org-get-todo-face tg))
14900 ((member tg current) c-face)
14901 ((member tg inherited) i-face)
14902 (t nil))))
14903 (if (and (= cnt 0) (not ingroup)) (insert " "))
14904 (insert "[" c "] " tg (make-string
14905 (- fwidth 4 (length tg)) ?\ ))
14906 (push (cons tg c) ntable)
14907 (when (= (setq cnt (1+ cnt)) ncol)
14908 (insert "\n")
14909 (if ingroup (insert " "))
14910 (setq cnt 0)))))
14911 (setq ntable (nreverse ntable))
14912 (insert "\n")
14913 (goto-char (point-min))
14914 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14915 (fit-window-to-buffer))
14916 (setq rtn
14917 (catch 'exit
14918 (while t
14919 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
14920 (if groups " [!] no groups" " [!]groups")
14921 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
14922 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14923 (cond
14924 ((= c ?\r) (throw 'exit t))
14925 ((= c ?!)
14926 (setq groups (not groups))
14927 (goto-char (point-min))
14928 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
14929 ((= c ?\C-c)
14930 (if (not expert)
14931 (org-fast-tag-show-exit
14932 (setq exit-after-next (not exit-after-next)))
14933 (setq expert nil)
14934 (delete-other-windows)
14935 (split-window-vertically)
14936 (org-switch-to-buffer-other-window " *Org tags*")
14937 (and (fboundp 'fit-window-to-buffer)
14938 (fit-window-to-buffer))))
14939 ((or (= c ?\C-g)
14940 (and (= c ?q) (not (rassoc c ntable))))
14941 (org-detach-overlay org-tags-overlay)
14942 (setq quit-flag t))
14943 ((= c ?\ )
14944 (setq current nil)
14945 (if exit-after-next (setq exit-after-next 'now)))
14946 ((= c ?\t)
14947 (condition-case nil
14948 (setq tg (completing-read
14949 "Tag: "
14950 (or buffer-tags
14951 (with-current-buffer buf
14952 (org-get-buffer-tags)))))
14953 (quit (setq tg "")))
14954 (when (string-match "\\S-" tg)
14955 (add-to-list 'buffer-tags (list tg))
14956 (if (member tg current)
14957 (setq current (delete tg current))
14958 (push tg current)))
14959 (if exit-after-next (setq exit-after-next 'now)))
14960 ((setq e (rassoc c todo-table) tg (car e))
14961 (with-current-buffer buf
14962 (save-excursion (org-todo tg)))
14963 (if exit-after-next (setq exit-after-next 'now)))
14964 ((setq e (rassoc c ntable) tg (car e))
14965 (if (member tg current)
14966 (setq current (delete tg current))
14967 (loop for g in groups do
14968 (if (member tg g)
14969 (mapc (lambda (x)
14970 (setq current (delete x current)))
14971 g)))
14972 (push tg current))
14973 (if exit-after-next (setq exit-after-next 'now))))
14975 ;; Create a sorted list
14976 (setq current
14977 (sort current
14978 (lambda (a b)
14979 (assoc b (cdr (memq (assoc a ntable) ntable))))))
14980 (if (eq exit-after-next 'now) (throw 'exit t))
14981 (goto-char (point-min))
14982 (beginning-of-line 2)
14983 (delete-region (point) (point-at-eol))
14984 (org-fast-tag-insert "Current" current c-face)
14985 (org-set-current-tags-overlay current ov-prefix)
14986 (while (re-search-forward
14987 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
14988 (setq tg (match-string 1))
14989 (add-text-properties
14990 (match-beginning 1) (match-end 1)
14991 (list 'face
14992 (cond
14993 ((member tg current) c-face)
14994 ((member tg inherited) i-face)
14995 (t (get-text-property (match-beginning 1) 'face))))))
14996 (goto-char (point-min)))))
14997 (org-detach-overlay org-tags-overlay)
14998 (if rtn
14999 (mapconcat 'identity current ":")
15000 nil))))
15002 (defun org-get-tags-string ()
15003 "Get the TAGS string in the current headline."
15004 (unless (org-on-heading-p t)
15005 (error "Not on a heading"))
15006 (save-excursion
15007 (beginning-of-line 1)
15008 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15009 (org-match-string-no-properties 1)
15010 "")))
15012 (defun org-get-tags ()
15013 "Get the list of tags specified in the current headline."
15014 (org-split-string (org-get-tags-string) ":"))
15016 (defun org-get-buffer-tags ()
15017 "Get a table of all tags used in the buffer, for completion."
15018 (let (tags)
15019 (save-excursion
15020 (goto-char (point-min))
15021 (while (re-search-forward
15022 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
15023 (when (equal (char-after (point-at-bol 0)) ?*)
15024 (mapc (lambda (x) (add-to-list 'tags x))
15025 (org-split-string (org-match-string-no-properties 1) ":")))))
15026 (mapcar 'list tags)))
15029 ;;;; Properties
15031 ;;; Setting and retrieving properties
15033 (defconst org-special-properties
15034 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
15035 "TIMESTAMP" "TIMESTAMP_IA")
15036 "The special properties valid in Org-mode.
15038 These are properties that are not defined in the property drawer,
15039 but in some other way.")
15041 (defconst org-default-properties
15042 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
15043 "LOCATION" "LOGGING" "COLUMNS")
15044 "Some properties that are used by Org-mode for various purposes.
15045 Being in this list makes sure that they are offered for completion.")
15047 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
15048 "Regular expression matching the first line of a property drawer.")
15050 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
15051 "Regular expression matching the first line of a property drawer.")
15053 (defun org-property-action ()
15054 "Do an action on properties."
15055 (interactive)
15056 (let (c)
15057 (org-at-property-p)
15058 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15059 (setq c (read-char-exclusive))
15060 (cond
15061 ((equal c ?s)
15062 (call-interactively 'org-set-property))
15063 ((equal c ?d)
15064 (call-interactively 'org-delete-property))
15065 ((equal c ?D)
15066 (call-interactively 'org-delete-property-globally))
15067 ((equal c ?c)
15068 (call-interactively 'org-compute-property-at-point))
15069 (t (error "No such property action %c" c)))))
15071 (defun org-at-property-p ()
15072 "Is the cursor in a property line?"
15073 ;; FIXME: Does not check if we are actually in the drawer.
15074 ;; FIXME: also returns true on any drawers.....
15075 ;; This is used by C-c C-c for property action.
15076 (save-excursion
15077 (beginning-of-line 1)
15078 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
15080 (defmacro org-with-point-at (pom &rest body)
15081 "Move to buffer and point of point-or-marker POM for the duration of BODY."
15082 (declare (indent 1) (debug t))
15083 `(save-excursion
15084 (if (markerp pom) (set-buffer (marker-buffer pom)))
15085 (save-excursion
15086 (goto-char (or pom (point)))
15087 ,@body)))
15089 (defun org-get-property-block (&optional beg end force)
15090 "Return the (beg . end) range of the body of the property drawer.
15091 BEG and END can be beginning and end of subtree, if not given
15092 they will be found.
15093 If the drawer does not exist and FORCE is non-nil, create the drawer."
15094 (catch 'exit
15095 (save-excursion
15096 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
15097 (end (or end (progn (outline-next-heading) (point)))))
15098 (goto-char beg)
15099 (if (re-search-forward org-property-start-re end t)
15100 (setq beg (1+ (match-end 0)))
15101 (if force
15102 (save-excursion
15103 (org-insert-property-drawer)
15104 (setq end (progn (outline-next-heading) (point))))
15105 (throw 'exit nil))
15106 (goto-char beg)
15107 (if (re-search-forward org-property-start-re end t)
15108 (setq beg (1+ (match-end 0)))))
15109 (if (re-search-forward org-property-end-re end t)
15110 (setq end (match-beginning 0))
15111 (or force (throw 'exit nil))
15112 (goto-char beg)
15113 (setq end beg)
15114 (org-indent-line-function)
15115 (insert ":END:\n"))
15116 (cons beg end)))))
15118 (defun org-entry-properties (&optional pom which)
15119 "Get all properties of the entry at point-or-marker POM.
15120 This includes the TODO keyword, the tags, time strings for deadline,
15121 scheduled, and clocking, and any additional properties defined in the
15122 entry. The return value is an alist, keys may occur multiple times
15123 if the property key was used several times.
15124 POM may also be nil, in which case the current entry is used.
15125 If WHICH is nil or `all', get all properties. If WHICH is
15126 `special' or `standard', only get that subclass."
15127 (setq which (or which 'all))
15128 (org-with-point-at pom
15129 (let ((clockstr (substring org-clock-string 0 -1))
15130 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
15131 beg end range props sum-props key value string)
15132 (save-excursion
15133 (when (condition-case nil (org-back-to-heading t) (error nil))
15134 (setq beg (point))
15135 (setq sum-props (get-text-property (point) 'org-summaries))
15136 (outline-next-heading)
15137 (setq end (point))
15138 (when (memq which '(all special))
15139 ;; Get the special properties, like TODO and tags
15140 (goto-char beg)
15141 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15142 (push (cons "TODO" (org-match-string-no-properties 2)) props))
15143 (when (looking-at org-priority-regexp)
15144 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
15145 (when (and (setq value (org-get-tags-string))
15146 (string-match "\\S-" value))
15147 (push (cons "TAGS" value) props))
15148 (when (setq value (org-get-tags-at))
15149 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
15150 props))
15151 (while (re-search-forward org-maybe-keyword-time-regexp end t)
15152 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
15153 string (if (equal key clockstr)
15154 (org-no-properties
15155 (org-trim
15156 (buffer-substring
15157 (match-beginning 3) (goto-char (point-at-eol)))))
15158 (substring (org-match-string-no-properties 3) 1 -1)))
15159 (unless key
15160 (if (= (char-after (match-beginning 3)) ?\[)
15161 (setq key "TIMESTAMP_IA")
15162 (setq key "TIMESTAMP")))
15163 (when (or (equal key clockstr) (not (assoc key props)))
15164 (push (cons key string) props)))
15168 (when (memq which '(all standard))
15169 ;; Get the standard properties, like :PORP: ...
15170 (setq range (org-get-property-block beg end))
15171 (when range
15172 (goto-char (car range))
15173 (while (re-search-forward
15174 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
15175 (cdr range) t)
15176 (setq key (org-match-string-no-properties 1)
15177 value (org-trim (or (org-match-string-no-properties 2) "")))
15178 (unless (member key excluded)
15179 (push (cons key (or value "")) props)))))
15180 (append sum-props (nreverse props)))))))
15182 (defun org-entry-get (pom property &optional inherit)
15183 "Get value of PROPERTY for entry at point-or-marker POM.
15184 If INHERIT is non-nil and the entry does not have the property,
15185 then also check higher levels of the hierarchy.
15186 If the property is present but empty, the return value is the empty string.
15187 If the property is not present at all, nil is returned."
15188 (org-with-point-at pom
15189 (if inherit
15190 (org-entry-get-with-inheritance property)
15191 (if (member property org-special-properties)
15192 ;; We need a special property. Use brute force, get all properties.
15193 (cdr (assoc property (org-entry-properties nil 'special)))
15194 (let ((range (org-get-property-block)))
15195 (if (and range
15196 (goto-char (car range))
15197 (re-search-forward
15198 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
15199 (cdr range) t))
15200 ;; Found the property, return it.
15201 (if (match-end 1)
15202 (org-match-string-no-properties 1)
15203 "")))))))
15205 (defun org-entry-delete (pom property)
15206 "Delete the property PROPERTY from entry at point-or-marker POM."
15207 (org-with-point-at pom
15208 (if (member property org-special-properties)
15209 nil ; cannot delete these properties.
15210 (let ((range (org-get-property-block)))
15211 (if (and range
15212 (goto-char (car range))
15213 (re-search-forward
15214 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
15215 (cdr range) t))
15216 (progn
15217 (delete-region (match-beginning 0) (1+ (point-at-eol)))
15219 nil)))))
15221 ;; Multi-values properties are properties that contain multiple values
15222 ;; These values are assumed to be single words, separated by whitespace.
15223 (defun org-entry-add-to-multivalued-property (pom property value)
15224 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15225 (let* ((old (org-entry-get pom property))
15226 (values (and old (org-split-string old "[ \t]"))))
15227 (unless (member value values)
15228 (setq values (cons value values))
15229 (org-entry-put pom property
15230 (mapconcat 'identity values " ")))))
15232 (defun org-entry-remove-from-multivalued-property (pom property value)
15233 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15234 (let* ((old (org-entry-get pom property))
15235 (values (and old (org-split-string old "[ \t]"))))
15236 (when (member value values)
15237 (setq values (delete value values))
15238 (org-entry-put pom property
15239 (mapconcat 'identity values " ")))))
15241 (defun org-entry-member-in-multivalued-property (pom property value)
15242 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15243 (let* ((old (org-entry-get pom property))
15244 (values (and old (org-split-string old "[ \t]"))))
15245 (member value values)))
15247 (defvar org-entry-property-inherited-from (make-marker))
15249 (defun org-entry-get-with-inheritance (property)
15250 "Get entry property, and search higher levels if not present."
15251 (let (tmp)
15252 (save-excursion
15253 (save-restriction
15254 (widen)
15255 (catch 'ex
15256 (while t
15257 (when (setq tmp (org-entry-get nil property))
15258 (org-back-to-heading t)
15259 (move-marker org-entry-property-inherited-from (point))
15260 (throw 'ex tmp))
15261 (or (org-up-heading-safe) (throw 'ex nil)))))
15262 (or tmp (cdr (assoc property org-local-properties))
15263 (cdr (assoc property org-global-properties))))))
15265 (defun org-entry-put (pom property value)
15266 "Set PROPERTY to VALUE for entry at point-or-marker POM."
15267 (org-with-point-at pom
15268 (org-back-to-heading t)
15269 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
15270 range)
15271 (cond
15272 ((equal property "TODO")
15273 (when (and (stringp value) (string-match "\\S-" value)
15274 (not (member value org-todo-keywords-1)))
15275 (error "\"%s\" is not a valid TODO state" value))
15276 (if (or (not value)
15277 (not (string-match "\\S-" value)))
15278 (setq value 'none))
15279 (org-todo value)
15280 (org-set-tags nil 'align))
15281 ((equal property "PRIORITY")
15282 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
15283 (string-to-char value) ?\ ))
15284 (org-set-tags nil 'align))
15285 ((equal property "SCHEDULED")
15286 (if (re-search-forward org-scheduled-time-regexp end t)
15287 (cond
15288 ((eq value 'earlier) (org-timestamp-change -1 'day))
15289 ((eq value 'later) (org-timestamp-change 1 'day))
15290 (t (call-interactively 'org-schedule)))
15291 (call-interactively 'org-schedule)))
15292 ((equal property "DEADLINE")
15293 (if (re-search-forward org-deadline-time-regexp end t)
15294 (cond
15295 ((eq value 'earlier) (org-timestamp-change -1 'day))
15296 ((eq value 'later) (org-timestamp-change 1 'day))
15297 (t (call-interactively 'org-deadline)))
15298 (call-interactively 'org-deadline)))
15299 ((member property org-special-properties)
15300 (error "The %s property can not yet be set with `org-entry-put'"
15301 property))
15302 (t ; a non-special property
15303 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
15304 (setq range (org-get-property-block beg end 'force))
15305 (goto-char (car range))
15306 (if (re-search-forward
15307 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
15308 (progn
15309 (delete-region (match-beginning 1) (match-end 1))
15310 (goto-char (match-beginning 1)))
15311 (goto-char (cdr range))
15312 (insert "\n")
15313 (backward-char 1)
15314 (org-indent-line-function)
15315 (insert ":" property ":"))
15316 (and value (insert " " value))
15317 (org-indent-line-function)))))))
15319 (defun org-buffer-property-keys (&optional include-specials include-defaults)
15320 "Get all property keys in the current buffer.
15321 With INCLUDE-SPECIALS, also list the special properties that relect things
15322 like tags and TODO state.
15323 With INCLUDE-DEFAULTS, also include properties that has special meaning
15324 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING."
15325 (let (rtn range)
15326 (save-excursion
15327 (save-restriction
15328 (widen)
15329 (goto-char (point-min))
15330 (while (re-search-forward org-property-start-re nil t)
15331 (setq range (org-get-property-block))
15332 (goto-char (car range))
15333 (while (re-search-forward
15334 (org-re "^[ \t]*:\\([[:alnum:]_-]+\\):")
15335 (cdr range) t)
15336 (add-to-list 'rtn (org-match-string-no-properties 1)))
15337 (outline-next-heading))))
15339 (when include-specials
15340 (setq rtn (append org-special-properties rtn)))
15342 (when include-defaults
15343 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
15345 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
15347 (defun org-property-values (key)
15348 "Return a list of all values of property KEY."
15349 (save-excursion
15350 (save-restriction
15351 (widen)
15352 (goto-char (point-min))
15353 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
15354 values)
15355 (while (re-search-forward re nil t)
15356 (add-to-list 'values (org-trim (match-string 1))))
15357 (delete "" values)))))
15359 (defun org-insert-property-drawer ()
15360 "Insert a property drawer into the current entry."
15361 (interactive)
15362 (org-back-to-heading t)
15363 (looking-at outline-regexp)
15364 (let ((indent (- (match-end 0)(match-beginning 0)))
15365 (beg (point))
15366 (re (concat "^[ \t]*" org-keyword-time-regexp))
15367 end hiddenp)
15368 (outline-next-heading)
15369 (setq end (point))
15370 (goto-char beg)
15371 (while (re-search-forward re end t))
15372 (setq hiddenp (org-invisible-p))
15373 (end-of-line 1)
15374 (and (equal (char-after) ?\n) (forward-char 1))
15375 (org-skip-over-state-notes)
15376 (skip-chars-backward " \t\n\r")
15377 (if (eq (char-before) ?*) (forward-char 1))
15378 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
15379 (beginning-of-line 0)
15380 (indent-to-column indent)
15381 (beginning-of-line 2)
15382 (indent-to-column indent)
15383 (beginning-of-line 0)
15384 (if hiddenp
15385 (save-excursion
15386 (org-back-to-heading t)
15387 (hide-entry))
15388 (org-flag-drawer t))))
15390 (defun org-set-property (property value)
15391 "In the current entry, set PROPERTY to VALUE.
15392 When called interactively, this will prompt for a property name, offering
15393 completion on existing and default properties. And then it will prompt
15394 for a value, offering competion either on allowed values (via an inherited
15395 xxx_ALL property) or on existing values in other instances of this property
15396 in the current file."
15397 (interactive
15398 (let* ((prop (completing-read
15399 "Property: " (mapcar 'list (org-buffer-property-keys nil t))))
15400 (cur (org-entry-get nil prop))
15401 (allowed (org-property-get-allowed-values nil prop 'table))
15402 (existing (mapcar 'list (org-property-values prop)))
15403 (val (if allowed
15404 (completing-read "Value: " allowed nil 'req-match)
15405 (completing-read
15406 (concat "Value" (if (and cur (string-match "\\S-" cur))
15407 (concat "[" cur "]") "")
15408 ": ")
15409 existing nil nil "" nil cur))))
15410 (list prop (if (equal val "") cur val))))
15411 (unless (equal (org-entry-get nil property) value)
15412 (org-entry-put nil property value)))
15414 (defun org-delete-property (property)
15415 "In the current entry, delete PROPERTY."
15416 (interactive
15417 (let* ((prop (completing-read
15418 "Property: " (org-entry-properties nil 'standard))))
15419 (list prop)))
15420 (message (concat "Property " property
15421 (if (org-entry-delete nil property)
15422 " deleted"
15423 " was not present in the entry"))))
15425 (defun org-delete-property-globally (property)
15426 "Remove PROPERTY globally, from all entries."
15427 (interactive
15428 (let* ((prop (completing-read
15429 "Globally remove property: "
15430 (mapcar 'list (org-buffer-property-keys)))))
15431 (list prop)))
15432 (save-excursion
15433 (save-restriction
15434 (widen)
15435 (goto-char (point-min))
15436 (let ((cnt 0))
15437 (while (re-search-forward
15438 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
15439 nil t)
15440 (setq cnt (1+ cnt))
15441 (replace-match ""))
15442 (message "Property \"%s\" removed from %d entries" property cnt)))))
15444 (defvar org-columns-current-fmt-compiled) ; defined below
15446 (defun org-compute-property-at-point ()
15447 "Compute the property at point.
15448 This looks for an enclosing column format, extracts the operator and
15449 then applies it to the proerty in the column format's scope."
15450 (interactive)
15451 (unless (org-at-property-p)
15452 (error "Not at a property"))
15453 (let ((prop (org-match-string-no-properties 2)))
15454 (org-columns-get-format-and-top-level)
15455 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
15456 (error "No operator defined for property %s" prop))
15457 (org-columns-compute prop)))
15459 (defun org-property-get-allowed-values (pom property &optional table)
15460 "Get allowed values for the property PROPERTY.
15461 When TABLE is non-nil, return an alist that can directly be used for
15462 completion."
15463 (let (vals)
15464 (cond
15465 ((equal property "TODO")
15466 (setq vals (org-with-point-at pom
15467 (append org-todo-keywords-1 '("")))))
15468 ((equal property "PRIORITY")
15469 (let ((n org-lowest-priority))
15470 (while (>= n org-highest-priority)
15471 (push (char-to-string n) vals)
15472 (setq n (1- n)))))
15473 ((member property org-special-properties))
15475 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
15477 (when (and vals (string-match "\\S-" vals))
15478 (setq vals (car (read-from-string (concat "(" vals ")"))))
15479 (setq vals (mapcar (lambda (x)
15480 (cond ((stringp x) x)
15481 ((numberp x) (number-to-string x))
15482 ((symbolp x) (symbol-name x))
15483 (t "???")))
15484 vals)))))
15485 (if table (mapcar 'list vals) vals)))
15487 (defun org-property-previous-allowed-value (&optional previous)
15488 "Switch to the next allowed value for this property."
15489 (interactive)
15490 (org-property-next-allowed-value t))
15492 (defun org-property-next-allowed-value (&optional previous)
15493 "Switch to the next allowed value for this property."
15494 (interactive)
15495 (unless (org-at-property-p)
15496 (error "Not at a property"))
15497 (let* ((key (match-string 2))
15498 (value (match-string 3))
15499 (allowed (or (org-property-get-allowed-values (point) key)
15500 (and (member value '("[ ]" "[-]" "[X]"))
15501 '("[ ]" "[X]"))))
15502 nval)
15503 (unless allowed
15504 (error "Allowed values for this property have not been defined"))
15505 (if previous (setq allowed (reverse allowed)))
15506 (if (member value allowed)
15507 (setq nval (car (cdr (member value allowed)))))
15508 (setq nval (or nval (car allowed)))
15509 (if (equal nval value)
15510 (error "Only one allowed value for this property"))
15511 (org-at-property-p)
15512 (replace-match (concat " :" key ": " nval) t t)
15513 (org-indent-line-function)
15514 (beginning-of-line 1)
15515 (skip-chars-forward " \t")))
15517 (defun org-find-entry-with-id (ident)
15518 "Locate the entry that contains the ID property with exact value IDENT.
15519 IDENT can be a string, a symbol or a number, this function will search for
15520 the string representation of it.
15521 Return the position where this entry starts, or nil if there is no such entry."
15522 (let ((id (cond
15523 ((stringp ident) ident)
15524 ((symbol-name ident) (symbol-name ident))
15525 ((numberp ident) (number-to-string ident))
15526 (t (error "IDENT %s must be a string, symbol or number" ident))))
15527 (case-fold-search nil))
15528 (save-excursion
15529 (save-restriction
15530 (goto-char (point-min))
15531 (when (re-search-forward
15532 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
15533 nil t)
15534 (org-back-to-heading)
15535 (point))))))
15537 ;;; Column View
15539 (defvar org-columns-overlays nil
15540 "Holds the list of current column overlays.")
15542 (defvar org-columns-current-fmt nil
15543 "Local variable, holds the currently active column format.")
15544 (defvar org-columns-current-fmt-compiled nil
15545 "Local variable, holds the currently active column format.
15546 This is the compiled version of the format.")
15547 (defvar org-columns-current-widths nil
15548 "Loval variable, holds the currently widths of fields.")
15549 (defvar org-columns-current-maxwidths nil
15550 "Loval variable, holds the currently active maximum column widths.")
15551 (defvar org-columns-begin-marker (make-marker)
15552 "Points to the position where last a column creation command was called.")
15553 (defvar org-columns-top-level-marker (make-marker)
15554 "Points to the position where current columns region starts.")
15556 (defvar org-columns-map (make-sparse-keymap)
15557 "The keymap valid in column display.")
15559 (defun org-columns-content ()
15560 "Switch to contents view while in columns view."
15561 (interactive)
15562 (org-overview)
15563 (org-content))
15565 (org-defkey org-columns-map "c" 'org-columns-content)
15566 (org-defkey org-columns-map "o" 'org-overview)
15567 (org-defkey org-columns-map "e" 'org-columns-edit-value)
15568 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
15569 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
15570 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
15571 (org-defkey org-columns-map "v" 'org-columns-show-value)
15572 (org-defkey org-columns-map "q" 'org-columns-quit)
15573 (org-defkey org-columns-map "r" 'org-columns-redo)
15574 (org-defkey org-columns-map [left] 'backward-char)
15575 (org-defkey org-columns-map "\M-b" 'backward-char)
15576 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
15577 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
15578 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
15579 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
15580 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
15581 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
15582 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
15583 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
15584 (org-defkey org-columns-map "<" 'org-columns-narrow)
15585 (org-defkey org-columns-map ">" 'org-columns-widen)
15586 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
15587 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
15588 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
15589 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
15591 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
15592 '("Column"
15593 ["Edit property" org-columns-edit-value t]
15594 ["Next allowed value" org-columns-next-allowed-value t]
15595 ["Previous allowed value" org-columns-previous-allowed-value t]
15596 ["Show full value" org-columns-show-value t]
15597 ["Edit allowed values" org-columns-edit-allowed t]
15598 "--"
15599 ["Edit column attributes" org-columns-edit-attributes t]
15600 ["Increase column width" org-columns-widen t]
15601 ["Decrease column width" org-columns-narrow t]
15602 "--"
15603 ["Move column right" org-columns-move-right t]
15604 ["Move column left" org-columns-move-left t]
15605 ["Add column" org-columns-new t]
15606 ["Delete column" org-columns-delete t]
15607 "--"
15608 ["CONTENTS" org-columns-content t]
15609 ["OVERVIEW" org-overview t]
15610 ["Refresh columns display" org-columns-redo t]
15611 "--"
15612 ["Open link" org-columns-open-link t]
15613 "--"
15614 ["Quit" org-columns-quit t]))
15616 (defun org-columns-new-overlay (beg end &optional string face)
15617 "Create a new column overlay and add it to the list."
15618 (let ((ov (org-make-overlay beg end)))
15619 (org-overlay-put ov 'face (or face 'secondary-selection))
15620 (org-overlay-display ov string face)
15621 (push ov org-columns-overlays)
15622 ov))
15624 (defun org-columns-display-here (&optional props)
15625 "Overlay the current line with column display."
15626 (interactive)
15627 (let* ((fmt org-columns-current-fmt-compiled)
15628 (beg (point-at-bol))
15629 (level-face (save-excursion
15630 (beginning-of-line 1)
15631 (and (looking-at "\\(\\**\\)\\(\\* \\)")
15632 (org-get-level-face 2))))
15633 (color (list :foreground
15634 (face-attribute (or level-face 'default) :foreground)))
15635 props pom property ass width f string ov column val modval)
15636 ;; Check if the entry is in another buffer.
15637 (unless props
15638 (if (eq major-mode 'org-agenda-mode)
15639 (setq pom (or (get-text-property (point) 'org-hd-marker)
15640 (get-text-property (point) 'org-marker))
15641 props (if pom (org-entry-properties pom) nil))
15642 (setq props (org-entry-properties nil))))
15643 ;; Walk the format
15644 (while (setq column (pop fmt))
15645 (setq property (car column)
15646 ass (if (equal property "ITEM")
15647 (cons "ITEM"
15648 (save-match-data
15649 (org-no-properties
15650 (org-remove-tabs
15651 (buffer-substring-no-properties
15652 (point-at-bol) (point-at-eol))))))
15653 (assoc property props))
15654 width (or (cdr (assoc property org-columns-current-maxwidths))
15655 (nth 2 column)
15656 (length property))
15657 f (format "%%-%d.%ds | " width width)
15658 val (or (cdr ass) "")
15659 modval (if (equal property "ITEM")
15660 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
15661 string (format f (or modval val)))
15662 ;; Create the overlay
15663 (org-unmodified
15664 (setq ov (org-columns-new-overlay
15665 beg (setq beg (1+ beg)) string
15666 (list color 'org-column)))
15667 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
15668 (org-overlay-put ov 'keymap org-columns-map)
15669 (org-overlay-put ov 'org-columns-key property)
15670 (org-overlay-put ov 'org-columns-value (cdr ass))
15671 (org-overlay-put ov 'org-columns-value-modified modval)
15672 (org-overlay-put ov 'org-columns-pom pom)
15673 (org-overlay-put ov 'org-columns-format f))
15674 (if (or (not (char-after beg))
15675 (equal (char-after beg) ?\n))
15676 (let ((inhibit-read-only t))
15677 (save-excursion
15678 (goto-char beg)
15679 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
15680 ;; Make the rest of the line disappear.
15681 (org-unmodified
15682 (setq ov (org-columns-new-overlay beg (point-at-eol)))
15683 (org-overlay-put ov 'invisible t)
15684 (org-overlay-put ov 'keymap org-columns-map)
15685 (org-overlay-put ov 'intangible t)
15686 (push ov org-columns-overlays)
15687 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
15688 (org-overlay-put ov 'keymap org-columns-map)
15689 (push ov org-columns-overlays)
15690 (let ((inhibit-read-only t))
15691 (put-text-property (max (point-min) (1- (point-at-bol)))
15692 (min (point-max) (1+ (point-at-eol)))
15693 'read-only "Type `e' to edit property")))))
15695 (defvar org-previous-header-line-format nil
15696 "The header line format before column view was turned on.")
15697 (defvar org-columns-inhibit-recalculation nil
15698 "Inhibit recomputing of columns on column view startup.")
15701 (defvar header-line-format)
15702 (defun org-columns-display-here-title ()
15703 "Overlay the newline before the current line with the table title."
15704 (interactive)
15705 (let ((fmt org-columns-current-fmt-compiled)
15706 string (title "")
15707 property width f column str widths)
15708 (while (setq column (pop fmt))
15709 (setq property (car column)
15710 str (or (nth 1 column) property)
15711 width (or (cdr (assoc property org-columns-current-maxwidths))
15712 (nth 2 column)
15713 (length str))
15714 widths (push width widths)
15715 f (format "%%-%d.%ds | " width width)
15716 string (format f str)
15717 title (concat title string)))
15718 (setq title (concat
15719 (org-add-props " " nil 'display '(space :align-to 0))
15720 (org-add-props title nil 'face '(:weight bold :underline t))))
15721 (org-set-local 'org-previous-header-line-format header-line-format)
15722 (org-set-local 'org-columns-current-widths (nreverse widths))
15723 (setq header-line-format title)))
15725 (defun org-columns-remove-overlays ()
15726 "Remove all currently active column overlays."
15727 (interactive)
15728 (when (marker-buffer org-columns-begin-marker)
15729 (with-current-buffer (marker-buffer org-columns-begin-marker)
15730 (when (local-variable-p 'org-previous-header-line-format)
15731 (setq header-line-format org-previous-header-line-format)
15732 (kill-local-variable 'org-previous-header-line-format))
15733 (move-marker org-columns-begin-marker nil)
15734 (move-marker org-columns-top-level-marker nil)
15735 (org-unmodified
15736 (mapc 'org-delete-overlay org-columns-overlays)
15737 (setq org-columns-overlays nil)
15738 (let ((inhibit-read-only t))
15739 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
15741 (defun org-columns-cleanup-item (item fmt)
15742 "Remove from ITEM what is a column in the format FMT."
15743 (if (not org-complex-heading-regexp)
15744 item
15745 (when (string-match org-complex-heading-regexp item)
15746 (concat
15747 (org-add-props (concat (match-string 1 item) " ") nil
15748 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
15749 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
15750 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
15751 " " (match-string 4 item)
15752 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
15754 (defun org-columns-show-value ()
15755 "Show the full value of the property."
15756 (interactive)
15757 (let ((value (get-char-property (point) 'org-columns-value)))
15758 (message "Value is: %s" (or value ""))))
15760 (defun org-columns-quit ()
15761 "Remove the column overlays and in this way exit column editing."
15762 (interactive)
15763 (org-unmodified
15764 (org-columns-remove-overlays)
15765 (let ((inhibit-read-only t))
15766 (remove-text-properties (point-min) (point-max) '(read-only t))))
15767 (when (eq major-mode 'org-agenda-mode)
15768 (message
15769 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
15771 (defun org-columns-check-computed ()
15772 "Check if this column value is computed.
15773 If yes, throw an error indicating that changing it does not make sense."
15774 (let ((val (get-char-property (point) 'org-columns-value)))
15775 (when (and (stringp val)
15776 (get-char-property 0 'org-computed val))
15777 (error "This value is computed from the entry's children"))))
15779 (defun org-columns-todo (&optional arg)
15780 "Change the TODO state during column view."
15781 (interactive "P")
15782 (org-columns-edit-value "TODO"))
15784 (defun org-columns-set-tags-or-toggle (&optional arg)
15785 "Toggle checkbox at point, or set tags for current headline."
15786 (interactive "P")
15787 (if (string-match "\\`\\[[ xX-]\\]\\'"
15788 (get-char-property (point) 'org-columns-value))
15789 (org-columns-next-allowed-value)
15790 (org-columns-edit-value "TAGS")))
15792 (defun org-columns-edit-value (&optional key)
15793 "Edit the value of the property at point in column view.
15794 Where possible, use the standard interface for changing this line."
15795 (interactive)
15796 (org-columns-check-computed)
15797 (let* ((external-key key)
15798 (col (current-column))
15799 (key (or key (get-char-property (point) 'org-columns-key)))
15800 (value (get-char-property (point) 'org-columns-value))
15801 (bol (point-at-bol)) (eol (point-at-eol))
15802 (pom (or (get-text-property bol 'org-hd-marker)
15803 (point))) ; keep despite of compiler waring
15804 (line-overlays
15805 (delq nil (mapcar (lambda (x)
15806 (and (eq (overlay-buffer x) (current-buffer))
15807 (>= (overlay-start x) bol)
15808 (<= (overlay-start x) eol)
15810 org-columns-overlays)))
15811 nval eval allowed)
15812 (cond
15813 ((equal key "ITEM")
15814 (setq eval '(org-with-point-at pom
15815 (org-edit-headline))))
15816 ((equal key "TODO")
15817 (setq eval '(org-with-point-at pom
15818 (let ((current-prefix-arg
15819 (if external-key current-prefix-arg '(4))))
15820 (call-interactively 'org-todo)))))
15821 ((equal key "PRIORITY")
15822 (setq eval '(org-with-point-at pom
15823 (call-interactively 'org-priority))))
15824 ((equal key "TAGS")
15825 (setq eval '(org-with-point-at pom
15826 (let ((org-fast-tag-selection-single-key
15827 (if (eq org-fast-tag-selection-single-key 'expert)
15828 t org-fast-tag-selection-single-key)))
15829 (call-interactively 'org-set-tags)))))
15830 ((equal key "DEADLINE")
15831 (setq eval '(org-with-point-at pom
15832 (call-interactively 'org-deadline))))
15833 ((equal key "SCHEDULED")
15834 (setq eval '(org-with-point-at pom
15835 (call-interactively 'org-schedule))))
15837 (setq allowed (org-property-get-allowed-values pom key 'table))
15838 (if allowed
15839 (setq nval (completing-read "Value: " allowed nil t))
15840 (setq nval (read-string "Edit: " value)))
15841 (setq nval (org-trim nval))
15842 (when (not (equal nval value))
15843 (setq eval '(org-entry-put pom key nval)))))
15844 (when eval
15845 (let ((inhibit-read-only t))
15846 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
15847 (unwind-protect
15848 (progn
15849 (setq org-columns-overlays
15850 (org-delete-all line-overlays org-columns-overlays))
15851 (mapc 'org-delete-overlay line-overlays)
15852 (org-columns-eval eval))
15853 (org-columns-display-here))))
15854 (move-to-column col)
15855 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15856 (org-columns-update key))))
15858 (defun org-edit-headline () ; FIXME: this is not columns specific
15859 "Edit the current headline, the part without TODO keyword, TAGS."
15860 (org-back-to-heading)
15861 (when (looking-at org-todo-line-regexp)
15862 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
15863 (txt (match-string 3))
15864 (post "")
15865 txt2)
15866 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
15867 (setq post (match-string 0 txt)
15868 txt (substring txt 0 (match-beginning 0))))
15869 (setq txt2 (read-string "Edit: " txt))
15870 (when (not (equal txt txt2))
15871 (beginning-of-line 1)
15872 (insert pre txt2 post)
15873 (delete-region (point) (point-at-eol))
15874 (org-set-tags nil t)))))
15876 (defun org-columns-edit-allowed ()
15877 "Edit the list of allowed values for the current property."
15878 (interactive)
15879 (let* ((key (get-char-property (point) 'org-columns-key))
15880 (key1 (concat key "_ALL"))
15881 (allowed (org-entry-get (point) key1 t))
15882 nval)
15883 ;; FIXME: Cover editing TODO, TAGS etc inbiffer settings.????
15884 (setq nval (read-string "Allowed: " allowed))
15885 (org-entry-put
15886 (cond ((marker-position org-entry-property-inherited-from)
15887 org-entry-property-inherited-from)
15888 ((marker-position org-columns-top-level-marker)
15889 org-columns-top-level-marker))
15890 key1 nval)))
15892 (defmacro org-no-warnings (&rest body)
15893 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
15895 (defun org-columns-eval (form)
15896 (let (hidep)
15897 (save-excursion
15898 (beginning-of-line 1)
15899 ;; `next-line' is needed here, because it skips invisible line.
15900 ;; FIXME: RMS says this should be wrapped into `with-no-warnings'
15901 ;; but I don't know how to do this and keep the code XEmacs compatible.
15902 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
15903 (setq hidep (org-on-heading-p 1)))
15904 (eval form)
15905 (and hidep (hide-entry))))
15907 (defun org-columns-previous-allowed-value ()
15908 "Switch to the previous allowed value for this column."
15909 (interactive)
15910 (org-columns-next-allowed-value t))
15912 (defun org-columns-next-allowed-value (&optional previous)
15913 "Switch to the next allowed value for this column."
15914 (interactive)
15915 (org-columns-check-computed)
15916 (let* ((col (current-column))
15917 (key (get-char-property (point) 'org-columns-key))
15918 (value (get-char-property (point) 'org-columns-value))
15919 (bol (point-at-bol)) (eol (point-at-eol))
15920 (pom (or (get-text-property bol 'org-hd-marker)
15921 (point))) ; keep despite of compiler waring
15922 (line-overlays
15923 (delq nil (mapcar (lambda (x)
15924 (and (eq (overlay-buffer x) (current-buffer))
15925 (>= (overlay-start x) bol)
15926 (<= (overlay-start x) eol)
15928 org-columns-overlays)))
15929 (allowed (or (org-property-get-allowed-values pom key)
15930 (and (equal
15931 (nth 4 (assoc key org-columns-current-fmt-compiled))
15932 'checkbox) '("[ ]" "[X]"))))
15933 nval)
15934 (when (equal key "ITEM")
15935 (error "Cannot edit item headline from here"))
15936 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
15937 (error "Allowed values for this property have not been defined"))
15938 (if (member key '("SCHEDULED" "DEADLINE"))
15939 (setq nval (if previous 'earlier 'later))
15940 (if previous (setq allowed (reverse allowed)))
15941 (if (member value allowed)
15942 (setq nval (car (cdr (member value allowed)))))
15943 (setq nval (or nval (car allowed)))
15944 (if (equal nval value)
15945 (error "Only one allowed value for this property")))
15946 (let ((inhibit-read-only t))
15947 (remove-text-properties (1- bol) eol '(read-only t))
15948 (unwind-protect
15949 (progn
15950 (setq org-columns-overlays
15951 (org-delete-all line-overlays org-columns-overlays))
15952 (mapc 'org-delete-overlay line-overlays)
15953 (org-columns-eval '(org-entry-put pom key nval)))
15954 (org-columns-display-here)))
15955 (move-to-column col)
15956 (if (nth 3 (assoc key org-columns-current-fmt-compiled))
15957 (org-columns-update key))))
15959 (defun org-verify-version (task)
15960 (cond
15961 ((eq task 'columns)
15962 (if (or (featurep 'xemacs)
15963 (< emacs-major-version 22))
15964 (error "Emacs 22 is required for the columns feature")))))
15966 (defun org-columns-open-link (&optional arg)
15967 (interactive "P")
15968 (let ((key (get-char-property (point) 'org-columns-key))
15969 (value (get-char-property (point) 'org-columns-value)))
15970 (org-open-link-from-string arg)))
15972 (defun org-open-link-from-string (s &optional arg)
15973 "Open a link in the string S, as if it was in Org-mode."
15974 (interactive)
15975 (with-temp-buffer
15976 (let ((org-inhibit-startup t))
15977 (org-mode)
15978 (insert s)
15979 (goto-char (point-min))
15980 (org-open-at-point arg))))
15982 (defun org-columns-get-format-and-top-level ()
15983 (let (fmt)
15984 (when (condition-case nil (org-back-to-heading) (error nil))
15985 (move-marker org-entry-property-inherited-from nil)
15986 (setq fmt (org-entry-get nil "COLUMNS" t)))
15987 (setq fmt (or fmt org-columns-default-format))
15988 (org-set-local 'org-columns-current-fmt fmt)
15989 (org-columns-compile-format fmt)
15990 (if (marker-position org-entry-property-inherited-from)
15991 (move-marker org-columns-top-level-marker
15992 org-entry-property-inherited-from)
15993 (move-marker org-columns-top-level-marker (point)))
15994 fmt))
15996 (defun org-columns ()
15997 "Turn on column view on an org-mode file."
15998 (interactive)
15999 (org-verify-version 'columns)
16000 (org-columns-remove-overlays)
16001 (move-marker org-columns-begin-marker (point))
16002 (let (beg end fmt cache maxwidths)
16003 (setq fmt (org-columns-get-format-and-top-level))
16004 (save-excursion
16005 (goto-char org-columns-top-level-marker)
16006 (setq beg (point))
16007 (unless org-columns-inhibit-recalculation
16008 (org-columns-compute-all))
16009 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
16010 (point-max)))
16011 (goto-char beg)
16012 ;; Get and cache the properties
16013 (while (re-search-forward (concat "^" outline-regexp) end t)
16014 (push (cons (org-current-line) (org-entry-properties)) cache))
16015 (when cache
16016 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16017 (org-set-local 'org-columns-current-maxwidths maxwidths)
16018 (org-columns-display-here-title)
16019 (mapc (lambda (x)
16020 (goto-line (car x))
16021 (org-columns-display-here (cdr x)))
16022 cache)))))
16024 (defun org-columns-new (&optional prop title width op fmt)
16025 "Insert a new column, to the leeft o the current column."
16026 (interactive)
16027 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
16028 cell)
16029 (setq prop (completing-read
16030 "Property: " (mapcar 'list (org-buffer-property-keys t))
16031 nil nil prop))
16032 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
16033 (setq width (read-string "Column width: " (if width (number-to-string width))))
16034 (if (string-match "\\S-" width)
16035 (setq width (string-to-number width))
16036 (setq width nil))
16037 (setq fmt (completing-read "Summary [none]: "
16038 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox"))
16039 nil t))
16040 (if (string-match "\\S-" fmt)
16041 (setq fmt (intern fmt))
16042 (setq fmt nil))
16043 (if (eq fmt 'none) (setq fmt nil))
16044 (if editp
16045 (progn
16046 (setcar editp prop)
16047 (setcdr editp (list title width nil fmt)))
16048 (setq cell (nthcdr (1- (current-column))
16049 org-columns-current-fmt-compiled))
16050 (setcdr cell (cons (list prop title width nil fmt)
16051 (cdr cell))))
16052 (org-columns-store-format)
16053 (org-columns-redo)))
16055 (defun org-columns-delete ()
16056 "Delete the column at point from columns view."
16057 (interactive)
16058 (let* ((n (current-column))
16059 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
16060 (when (y-or-n-p
16061 (format "Are you sure you want to remove column \"%s\"? " title))
16062 (setq org-columns-current-fmt-compiled
16063 (delq (nth n org-columns-current-fmt-compiled)
16064 org-columns-current-fmt-compiled))
16065 (org-columns-store-format)
16066 (org-columns-redo)
16067 (if (>= (current-column) (length org-columns-current-fmt-compiled))
16068 (backward-char 1)))))
16070 (defun org-columns-edit-attributes ()
16071 "Edit the attributes of the current column."
16072 (interactive)
16073 (let* ((n (current-column))
16074 (info (nth n org-columns-current-fmt-compiled)))
16075 (apply 'org-columns-new info)))
16077 (defun org-columns-widen (arg)
16078 "Make the column wider by ARG characters."
16079 (interactive "p")
16080 (let* ((n (current-column))
16081 (entry (nth n org-columns-current-fmt-compiled))
16082 (width (or (nth 2 entry)
16083 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
16084 (setq width (max 1 (+ width arg)))
16085 (setcar (nthcdr 2 entry) width)
16086 (org-columns-store-format)
16087 (org-columns-redo)))
16089 (defun org-columns-narrow (arg)
16090 "Make the column nrrower by ARG characters."
16091 (interactive "p")
16092 (org-columns-widen (- arg)))
16094 (defun org-columns-move-right ()
16095 "Swap this column with the one to the right."
16096 (interactive)
16097 (let* ((n (current-column))
16098 (cell (nthcdr n org-columns-current-fmt-compiled))
16100 (when (>= n (1- (length org-columns-current-fmt-compiled)))
16101 (error "Cannot shift this column further to the right"))
16102 (setq e (car cell))
16103 (setcar cell (car (cdr cell)))
16104 (setcdr cell (cons e (cdr (cdr cell))))
16105 (org-columns-store-format)
16106 (org-columns-redo)
16107 (forward-char 1)))
16109 (defun org-columns-move-left ()
16110 "Swap this column with the one to the left."
16111 (interactive)
16112 (let* ((n (current-column)))
16113 (when (= n 0)
16114 (error "Cannot shift this column further to the left"))
16115 (backward-char 1)
16116 (org-columns-move-right)
16117 (backward-char 1)))
16119 (defun org-columns-store-format ()
16120 "Store the text version of the current columns format in appropriate place.
16121 This is either in the COLUMNS property of the node starting the current column
16122 display, or in the #+COLUMNS line of the current buffer."
16123 (let (fmt (cnt 0))
16124 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
16125 (org-set-local 'org-columns-current-fmt fmt)
16126 (if (marker-position org-columns-top-level-marker)
16127 (save-excursion
16128 (goto-char org-columns-top-level-marker)
16129 (if (and (org-at-heading-p)
16130 (org-entry-get nil "COLUMNS"))
16131 (org-entry-put nil "COLUMNS" fmt)
16132 (goto-char (point-min))
16133 ;; Overwrite all #+COLUMNS lines....
16134 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
16135 (setq cnt (1+ cnt))
16136 (replace-match (concat "#+COLUMNS: " fmt) t t))
16137 (unless (> cnt 0)
16138 (goto-char (point-min))
16139 (or (org-on-heading-p t) (outline-next-heading))
16140 (let ((inhibit-read-only t))
16141 (insert-before-markers "#+COLUMNS: " fmt "\n")))
16142 (org-set-local 'org-columns-default-format fmt))))))
16144 (defvar org-overriding-columns-format nil
16145 "When set, overrides any other definition.")
16146 (defvar org-agenda-view-columns-initially nil
16147 "When set, switch to columns view immediately after creating the agenda.")
16149 (defun org-agenda-columns ()
16150 "Turn on column view in the agenda."
16151 (interactive)
16152 (org-verify-version 'columns)
16153 (org-columns-remove-overlays)
16154 (move-marker org-columns-begin-marker (point))
16155 (let (fmt cache maxwidths m)
16156 (cond
16157 ((and (local-variable-p 'org-overriding-columns-format)
16158 org-overriding-columns-format)
16159 (setq fmt org-overriding-columns-format))
16160 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
16161 (setq fmt (org-entry-get m "COLUMNS" t)))
16162 ((and (boundp 'org-columns-current-fmt)
16163 (local-variable-p 'org-columns-current-fmt)
16164 org-columns-current-fmt)
16165 (setq fmt org-columns-current-fmt))
16166 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
16167 (setq m (get-text-property m 'org-hd-marker))
16168 (setq fmt (org-entry-get m "COLUMNS" t))))
16169 (setq fmt (or fmt org-columns-default-format))
16170 (org-set-local 'org-columns-current-fmt fmt)
16171 (org-columns-compile-format fmt)
16172 (save-excursion
16173 ;; Get and cache the properties
16174 (goto-char (point-min))
16175 (while (not (eobp))
16176 (when (setq m (or (get-text-property (point) 'org-hd-marker)
16177 (get-text-property (point) 'org-marker)))
16178 (push (cons (org-current-line) (org-entry-properties m)) cache))
16179 (beginning-of-line 2))
16180 (when cache
16181 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
16182 (org-set-local 'org-columns-current-maxwidths maxwidths)
16183 (org-columns-display-here-title)
16184 (mapc (lambda (x)
16185 (goto-line (car x))
16186 (org-columns-display-here (cdr x)))
16187 cache)))))
16189 (defun org-columns-get-autowidth-alist (s cache)
16190 "Derive the maximum column widths from the format and the cache."
16191 (let ((start 0) rtn)
16192 (while (string-match (org-re "%\\([[:alpha:]]\\S-*\\)") s start)
16193 (push (cons (match-string 1 s) 1) rtn)
16194 (setq start (match-end 0)))
16195 (mapc (lambda (x)
16196 (setcdr x (apply 'max
16197 (mapcar
16198 (lambda (y)
16199 (length (or (cdr (assoc (car x) (cdr y))) " ")))
16200 cache))))
16201 rtn)
16202 rtn))
16204 (defun org-columns-compute-all ()
16205 "Compute all columns that have operators defined."
16206 (org-unmodified
16207 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
16208 (let ((columns org-columns-current-fmt-compiled) col)
16209 (while (setq col (pop columns))
16210 (when (nth 3 col)
16211 (save-excursion
16212 (org-columns-compute (car col)))))))
16214 (defun org-columns-update (property)
16215 "Recompute PROPERTY, and update the columns display for it."
16216 (org-columns-compute property)
16217 (let (fmt val pos)
16218 (save-excursion
16219 (mapc (lambda (ov)
16220 (when (equal (org-overlay-get ov 'org-columns-key) property)
16221 (setq pos (org-overlay-start ov))
16222 (goto-char pos)
16223 (when (setq val (cdr (assoc property
16224 (get-text-property
16225 (point-at-bol) 'org-summaries))))
16226 (setq fmt (org-overlay-get ov 'org-columns-format))
16227 (org-overlay-put ov 'org-columns-value val)
16228 (org-overlay-put ov 'display (format fmt val)))))
16229 org-columns-overlays))))
16231 (defun org-columns-compute (property)
16232 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
16233 (interactive)
16234 (let* ((re (concat "^" outline-regexp))
16235 (lmax 30) ; Does anyone use deeper levels???
16236 (lsum (make-vector lmax 0))
16237 (lflag (make-vector lmax nil))
16238 (level 0)
16239 (ass (assoc property org-columns-current-fmt-compiled))
16240 (format (nth 4 ass))
16241 (printf (nth 5 ass))
16242 (beg org-columns-top-level-marker)
16243 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
16244 (save-excursion
16245 ;; Find the region to compute
16246 (goto-char beg)
16247 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
16248 (goto-char end)
16249 ;; Walk the tree from the back and do the computations
16250 (while (re-search-backward re beg t)
16251 (setq sumpos (match-beginning 0)
16252 last-level level
16253 level (org-outline-level)
16254 val (org-entry-get nil property)
16255 valflag (and val (string-match "\\S-" val)))
16256 (cond
16257 ((< level last-level)
16258 ;; put the sum of lower levels here as a property
16259 (setq sum (aref lsum last-level) ; current sum
16260 flag (aref lflag last-level) ; any valid entries from children?
16261 str (org-column-number-to-string sum format printf)
16262 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
16263 useval (if flag str1 (if valflag val ""))
16264 sum-alist (get-text-property sumpos 'org-summaries))
16265 (if (assoc property sum-alist)
16266 (setcdr (assoc property sum-alist) useval)
16267 (push (cons property useval) sum-alist)
16268 (org-unmodified
16269 (add-text-properties sumpos (1+ sumpos)
16270 (list 'org-summaries sum-alist))))
16271 (when val
16272 (org-entry-put nil property (if flag str val)))
16273 ;; add current to current level accumulator
16274 (when (or flag valflag)
16275 ;; FIXME: is this ok?????????
16276 (aset lsum level (+ (aref lsum level)
16277 (if flag sum (org-column-string-to-number
16278 (if flag str val) format))))
16279 (aset lflag level t))
16280 ;; clear accumulators for deeper levels
16281 (loop for l from (1+ level) to (1- lmax) do
16282 (aset lsum l 0)
16283 (aset lflag l nil)))
16284 ((>= level last-level)
16285 ;; add what we have here to the accumulator for this level
16286 (aset lsum level (+ (aref lsum level)
16287 (org-column-string-to-number (or val "0") format)))
16288 (and valflag (aset lflag level t)))
16289 (t (error "This should not happen")))))))
16291 (defun org-columns-redo ()
16292 "Construct the column display again."
16293 (interactive)
16294 (message "Recomputing columns...")
16295 (save-excursion
16296 (if (marker-position org-columns-begin-marker)
16297 (goto-char org-columns-begin-marker))
16298 (org-columns-remove-overlays)
16299 (if (org-mode-p)
16300 (call-interactively 'org-columns)
16301 (call-interactively 'org-agenda-columns)))
16302 (message "Recomputing columns...done"))
16304 (defun org-columns-not-in-agenda ()
16305 (if (eq major-mode 'org-agenda-mode)
16306 (error "This command is only allowed in Org-mode buffers")))
16309 (defun org-string-to-number (s)
16310 "Convert string to number, and interpret hh:mm:ss."
16311 (if (not (string-match ":" s))
16312 (string-to-number s)
16313 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16314 (while l
16315 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16316 sum)))
16318 (defun org-column-number-to-string (n fmt printf)
16319 "Convert a computed column number to a string value, according to FMT."
16320 (cond
16321 ((eq fmt 'add_times)
16322 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
16323 (format "%d:%02d" h m)))
16324 ((eq fmt 'checkbox)
16325 (cond ((= n (floor n)) "[X]")
16326 ((> n 1.) "[-]")
16327 (t "[ ]")))
16328 (printf (format printf n))
16329 ((eq fmt 'currency)
16330 (format "%.2f" n))
16331 (t (number-to-string n))))
16333 (defun org-column-string-to-number (s fmt)
16334 "Convert a column value to a number that can be used for column computing."
16335 (cond
16336 ((string-match ":" s)
16337 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
16338 (while l
16339 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
16340 sum))
16341 ((eq fmt 'checkbox)
16342 (if (equal s "[X]") 1. 0.000001))
16343 (t (string-to-number s))))
16345 (defun org-columns-uncompile-format (cfmt)
16346 "Turn the compiled columns format back into a string representation."
16347 (let ((rtn "") e s prop title op width fmt printf)
16348 (while (setq e (pop cfmt))
16349 (setq prop (car e)
16350 title (nth 1 e)
16351 width (nth 2 e)
16352 op (nth 3 e)
16353 fmt (nth 4 e)
16354 printf (nth 5 e))
16355 (cond
16356 ((eq fmt 'add_times) (setq op ":"))
16357 ((eq fmt 'checkbox) (setq op "X"))
16358 ((eq fmt 'add_numbers) (setq op "+"))
16359 ((eq fmt 'currency) (setq op "$")))
16360 (if (and op printf) (setq op (concat op ";" printf)))
16361 (if (equal title prop) (setq title nil))
16362 (setq s (concat "%" (if width (number-to-string width))
16363 prop
16364 (if title (concat "(" title ")"))
16365 (if op (concat "{" op "}"))))
16366 (setq rtn (concat rtn " " s)))
16367 (org-trim rtn)))
16369 (defun org-columns-compile-format (fmt)
16370 "Turn a column format string into an alist of specifications.
16371 The alist has one entry for each column in the format. The elements of
16372 that list are:
16373 property the property
16374 title the title field for the columns
16375 width the column width in characters, can be nil for automatic
16376 operator the operator if any
16377 format the output format for computed results, derived from operator
16378 printf a printf format for computed values"
16379 (let ((start 0) width prop title op f printf)
16380 (setq org-columns-current-fmt-compiled nil)
16381 (while (string-match
16382 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
16383 fmt start)
16384 (setq start (match-end 0)
16385 width (match-string 1 fmt)
16386 prop (match-string 2 fmt)
16387 title (or (match-string 3 fmt) prop)
16388 op (match-string 4 fmt)
16389 f nil
16390 printf nil)
16391 (if width (setq width (string-to-number width)))
16392 (when (and op (string-match ";" op))
16393 (setq printf (substring op (match-end 0))
16394 op (substring op 0 (match-beginning 0))))
16395 (cond
16396 ((equal op "+") (setq f 'add_numbers))
16397 ((equal op "$") (setq f 'currency))
16398 ((equal op ":") (setq f 'add_times))
16399 ((equal op "X") (setq f 'checkbox)))
16400 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
16401 (setq org-columns-current-fmt-compiled
16402 (nreverse org-columns-current-fmt-compiled))))
16405 ;;; Dynamic block for Column view
16407 (defun org-columns-capture-view ()
16408 "Get the column view of the current buffer and return it as a list.
16409 The list will contains the title row and all other rows. Each row is
16410 a list of fields."
16411 (save-excursion
16412 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
16413 (n (length title)) row tbl)
16414 (goto-char (point-min))
16415 (while (re-search-forward "^\\*+ " nil t)
16416 (when (get-char-property (match-beginning 0) 'org-columns-key)
16417 (setq row nil)
16418 (loop for i from 0 to (1- n) do
16419 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
16420 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
16422 row))
16423 (setq row (nreverse row))
16424 (push row tbl)))
16425 (append (list title 'hline) (nreverse tbl)))))
16427 (defun org-dblock-write:columnview (params)
16428 "Write the column view table.
16429 PARAMS is a property list of parameters:
16431 :width enforce same column widths with <N> specifiers.
16432 :id the :ID: property of the entry where the columns view
16433 should be built, as a string. When `local', call locally.
16434 When `global' call column view with the cursor at the beginning
16435 of the buffer (usually this means that the whole buffer switches
16436 to column view).
16437 :hlines When t, insert a hline before each item. When a number, insert
16438 a hline before each level <= that number.
16439 :vlines When t, make each column a colgroup to enforce vertical lines."
16440 (let ((pos (move-marker (make-marker) (point)))
16441 (hlines (plist-get params :hlines))
16442 (vlines (plist-get params :vlines))
16443 tbl id idpos nfields tmp)
16444 (save-excursion
16445 (save-restriction
16446 (when (setq id (plist-get params :id))
16447 (cond ((not id) nil)
16448 ((eq id 'global) (goto-char (point-min)))
16449 ((eq id 'local) nil)
16450 ((setq idpos (org-find-entry-with-id id))
16451 (goto-char idpos))
16452 (t (error "Cannot find entry with :ID: %s" id))))
16453 (org-columns)
16454 (setq tbl (org-columns-capture-view))
16455 (setq nfields (length (car tbl)))
16456 (org-columns-quit)))
16457 (goto-char pos)
16458 (move-marker pos nil)
16459 (when tbl
16460 (when (plist-get params :hlines)
16461 (setq tmp nil)
16462 (while tbl
16463 (if (eq (car tbl) 'hline)
16464 (push (pop tbl) tmp)
16465 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
16466 (if (and (not (eq (car tmp) 'hline))
16467 (or (eq hlines t)
16468 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
16469 (push 'hline tmp)))
16470 (push (pop tbl) tmp)))
16471 (setq tbl (nreverse tmp)))
16472 (when vlines
16473 (setq tbl (mapcar (lambda (x)
16474 (if (eq 'hline x) x (cons "" x)))
16475 tbl))
16476 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
16477 (setq pos (point))
16478 (insert (org-listtable-to-string tbl))
16479 (when (plist-get params :width)
16480 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
16481 org-columns-current-widths "|")))
16482 (goto-char pos)
16483 (org-table-align))))
16485 (defun org-listtable-to-string (tbl)
16486 "Convert a listtable TBL to a string that contains the Org-mode table.
16487 The table still need to be alligned. The resulting string has no leading
16488 and tailing newline characters."
16489 (mapconcat
16490 (lambda (x)
16491 (cond
16492 ((listp x)
16493 (concat "|" (mapconcat 'identity x "|") "|"))
16494 ((eq x 'hline) "|-|")
16495 (t (error "Garbage in listtable: %s" x))))
16496 tbl "\n"))
16498 (defun org-insert-columns-dblock ()
16499 "Create a dynamic block capturing a column view table."
16500 (interactive)
16501 (let ((defaults '(:name "columnview" :hlines 1))
16502 (id (completing-read
16503 "Capture columns (local, global, entry with :ID: property) [local]: "
16504 (append '(("global") ("local"))
16505 (mapcar 'list (org-property-values "ID"))))))
16506 (if (equal id "") (setq id 'local))
16507 (if (equal id "global") (setq id 'global))
16508 (setq defaults (append defaults (list :id id)))
16509 (org-create-dblock defaults)
16510 (org-update-dblock)))
16512 ;;;; Timestamps
16514 (defvar org-last-changed-timestamp nil)
16515 (defvar org-time-was-given) ; dynamically scoped parameter
16516 (defvar org-end-time-was-given) ; dynamically scoped parameter
16517 (defvar org-ts-what) ; dynamically scoped parameter
16519 (defun org-time-stamp (arg)
16520 "Prompt for a date/time and insert a time stamp.
16521 If the user specifies a time like HH:MM, or if this command is called
16522 with a prefix argument, the time stamp will contain date and time.
16523 Otherwise, only the date will be included. All parts of a date not
16524 specified by the user will be filled in from the current date/time.
16525 So if you press just return without typing anything, the time stamp
16526 will represent the current date/time. If there is already a timestamp
16527 at the cursor, it will be modified."
16528 (interactive "P")
16529 (let* ((ts nil)
16530 (default-time
16531 ;; Default time is either today, or, when entering a range,
16532 ;; the range start.
16533 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
16534 (save-excursion
16535 (re-search-backward
16536 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
16537 (- (point) 20) t)))
16538 (apply 'encode-time (org-parse-time-string (match-string 1)))
16539 (current-time)))
16540 (default-input (and ts (org-get-compact-tod ts)))
16541 org-time-was-given org-end-time-was-given time)
16542 (cond
16543 ((and (org-at-timestamp-p)
16544 (eq last-command 'org-time-stamp)
16545 (eq this-command 'org-time-stamp))
16546 (insert "--")
16547 (setq time (let ((this-command this-command))
16548 (org-read-date arg 'totime nil nil default-time default-input)))
16549 (org-insert-time-stamp time (or org-time-was-given arg)))
16550 ((org-at-timestamp-p)
16551 (setq time (let ((this-command this-command))
16552 (org-read-date arg 'totime nil nil default-time default-input)))
16553 (when (org-at-timestamp-p) ; just to get the match data
16554 (replace-match "")
16555 (setq org-last-changed-timestamp
16556 (org-insert-time-stamp
16557 time (or org-time-was-given arg)
16558 nil nil nil (list org-end-time-was-given))))
16559 (message "Timestamp updated"))
16561 (setq time (let ((this-command this-command))
16562 (org-read-date arg 'totime nil nil default-time default-input)))
16563 (org-insert-time-stamp time (or org-time-was-given arg)
16564 nil nil nil (list org-end-time-was-given))))))
16566 ;; FIXME: can we use this for something else????
16567 ;; like computing time differences?????
16568 (defun org-get-compact-tod (s)
16569 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16570 (let* ((t1 (match-string 1 s))
16571 (h1 (string-to-number (match-string 2 s)))
16572 (m1 (string-to-number (match-string 3 s)))
16573 (t2 (and (match-end 4) (match-string 5 s)))
16574 (h2 (and t2 (string-to-number (match-string 6 s))))
16575 (m2 (and t2 (string-to-number (match-string 7 s))))
16576 dh dm)
16577 (if (not t2)
16579 (setq dh (- h2 h1) dm (- m2 m1))
16580 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16581 (concat t1 "+" (number-to-string dh)
16582 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
16584 (defun org-time-stamp-inactive (&optional arg)
16585 "Insert an inactive time stamp.
16586 An inactive time stamp is enclosed in square brackets instead of angle
16587 brackets. It is inactive in the sense that it does not trigger agenda entries,
16588 does not link to the calendar and cannot be changed with the S-cursor keys.
16589 So these are more for recording a certain time/date."
16590 (interactive "P")
16591 (let (org-time-was-given org-end-time-was-given time)
16592 (setq time (org-read-date arg 'totime))
16593 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
16594 nil nil (list org-end-time-was-given))))
16596 (defvar org-date-ovl (org-make-overlay 1 1))
16597 (org-overlay-put org-date-ovl 'face 'org-warning)
16598 (org-detach-overlay org-date-ovl)
16600 (defvar org-ans1) ; dynamically scoped parameter
16601 (defvar org-ans2) ; dynamically scoped parameter
16603 (defvar org-plain-time-of-day-regexp) ; defined below
16605 (defvar org-read-date-overlay nil)
16606 (defvar org-dcst nil) ; dynamically scoped
16608 (defun org-read-date (&optional with-time to-time from-string prompt
16609 default-time default-input)
16610 "Read a date, possibly a time, and make things smooth for the user.
16611 The prompt will suggest to enter an ISO date, but you can also enter anything
16612 which will at least partially be understood by `parse-time-string'.
16613 Unrecognized parts of the date will default to the current day, month, year,
16614 hour and minute. If this command is called to replace a timestamp at point,
16615 of to enter the second timestamp of a range, the default time is taken from the
16616 existing stamp. For example,
16617 3-2-5 --> 2003-02-05
16618 feb 15 --> currentyear-02-15
16619 sep 12 9 --> 2009-09-12
16620 12:45 --> today 12:45
16621 22 sept 0:34 --> currentyear-09-22 0:34
16622 12 --> currentyear-currentmonth-12
16623 Fri --> nearest Friday (today or later)
16624 etc.
16626 Furthermore you can specify a relative date by giving, as the *first* thing
16627 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
16628 change in days weeks, months, years.
16629 With a single plus or minus, the date is relative to today. With a double
16630 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16631 +4d --> four days from today
16632 +4 --> same as above
16633 +2w --> two weeks from today
16634 ++5 --> five days from default date
16636 The function understands only English month and weekday abbreviations,
16637 but this can be configured with the variables `parse-time-months' and
16638 `parse-time-weekdays'.
16640 While prompting, a calendar is popped up - you can also select the
16641 date with the mouse (button 1). The calendar shows a period of three
16642 months. To scroll it to other months, use the keys `>' and `<'.
16643 If you don't like the calendar, turn it off with
16644 \(setq org-read-date-popup-calendar nil)
16646 With optional argument TO-TIME, the date will immediately be converted
16647 to an internal time.
16648 With an optional argument WITH-TIME, the prompt will suggest to also
16649 insert a time. Note that when WITH-TIME is not set, you can still
16650 enter a time, and this function will inform the calling routine about
16651 this change. The calling routine may then choose to change the format
16652 used to insert the time stamp into the buffer to include the time.
16653 With optional argument FROM-STRING, read from this string instead from
16654 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16655 the time/date that is used for everything that is not specified by the
16656 user."
16657 (require 'parse-time)
16658 (let* ((org-time-stamp-rounding-minutes
16659 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
16660 (org-dcst org-display-custom-times)
16661 (ct (org-current-time))
16662 (def (or default-time ct))
16663 (defdecode (decode-time def))
16664 (dummy (progn
16665 (when (< (nth 2 defdecode) org-extend-today-until)
16666 (setcar (nthcdr 2 defdecode) -1)
16667 (setcar (nthcdr 1 defdecode) 59)
16668 (setq def (apply 'encode-time defdecode)
16669 defdecode (decode-time def)))))
16670 (calendar-move-hook nil)
16671 (view-diary-entries-initially nil)
16672 (view-calendar-holidays-initially nil)
16673 (timestr (format-time-string
16674 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
16675 (prompt (concat (if prompt (concat prompt " ") "")
16676 (format "Date+time [%s]: " timestr)))
16677 ans (org-ans0 "") org-ans1 org-ans2 final)
16679 (cond
16680 (from-string (setq ans from-string))
16681 (org-read-date-popup-calendar
16682 (save-excursion
16683 (save-window-excursion
16684 (calendar)
16685 (calendar-forward-day (- (time-to-days def)
16686 (calendar-absolute-from-gregorian
16687 (calendar-current-date))))
16688 (org-eval-in-calendar nil t)
16689 (let* ((old-map (current-local-map))
16690 (map (copy-keymap calendar-mode-map))
16691 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
16692 (org-defkey map (kbd "RET") 'org-calendar-select)
16693 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
16694 'org-calendar-select-mouse)
16695 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
16696 'org-calendar-select-mouse)
16697 (org-defkey minibuffer-local-map [(meta shift left)]
16698 (lambda () (interactive)
16699 (org-eval-in-calendar '(calendar-backward-month 1))))
16700 (org-defkey minibuffer-local-map [(meta shift right)]
16701 (lambda () (interactive)
16702 (org-eval-in-calendar '(calendar-forward-month 1))))
16703 (org-defkey minibuffer-local-map [(meta shift up)]
16704 (lambda () (interactive)
16705 (org-eval-in-calendar '(calendar-backward-year 1))))
16706 (org-defkey minibuffer-local-map [(meta shift down)]
16707 (lambda () (interactive)
16708 (org-eval-in-calendar '(calendar-forward-year 1))))
16709 (org-defkey minibuffer-local-map [(shift up)]
16710 (lambda () (interactive)
16711 (org-eval-in-calendar '(calendar-backward-week 1))))
16712 (org-defkey minibuffer-local-map [(shift down)]
16713 (lambda () (interactive)
16714 (org-eval-in-calendar '(calendar-forward-week 1))))
16715 (org-defkey minibuffer-local-map [(shift left)]
16716 (lambda () (interactive)
16717 (org-eval-in-calendar '(calendar-backward-day 1))))
16718 (org-defkey minibuffer-local-map [(shift right)]
16719 (lambda () (interactive)
16720 (org-eval-in-calendar '(calendar-forward-day 1))))
16721 (org-defkey minibuffer-local-map ">"
16722 (lambda () (interactive)
16723 (org-eval-in-calendar '(scroll-calendar-left 1))))
16724 (org-defkey minibuffer-local-map "<"
16725 (lambda () (interactive)
16726 (org-eval-in-calendar '(scroll-calendar-right 1))))
16727 (unwind-protect
16728 (progn
16729 (use-local-map map)
16730 (add-hook 'post-command-hook 'org-read-date-display)
16731 (setq org-ans0 (read-string prompt default-input nil nil))
16732 ;; org-ans0: from prompt
16733 ;; org-ans1: from mouse click
16734 ;; org-ans2: from calendar motion
16735 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
16736 (remove-hook 'post-command-hook 'org-read-date-display)
16737 (use-local-map old-map)
16738 (when org-read-date-overlay
16739 (org-delete-overlay org-read-date-overlay)
16740 (setq org-read-date-overlay nil)))))))
16742 (t ; Naked prompt only
16743 (unwind-protect
16744 (setq ans (read-string prompt default-input nil timestr))
16745 (when org-read-date-overlay
16746 (org-delete-overlay org-read-date-overlay)
16747 (setq org-read-date-overlay nil)))))
16749 (setq final (org-read-date-analyze ans def defdecode))
16751 (if to-time
16752 (apply 'encode-time final)
16753 (if (and (boundp 'org-time-was-given) org-time-was-given)
16754 (format "%04d-%02d-%02d %02d:%02d"
16755 (nth 5 final) (nth 4 final) (nth 3 final)
16756 (nth 2 final) (nth 1 final))
16757 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16758 (defvar def)
16759 (defvar defdecode)
16760 (defvar with-time)
16761 (defun org-read-date-display ()
16762 "Display the currrent date prompt interpretation in the minibuffer."
16763 (when org-read-date-display-live
16764 (when org-read-date-overlay
16765 (org-delete-overlay org-read-date-overlay))
16766 (let ((p (point)))
16767 (end-of-line 1)
16768 (while (not (equal (buffer-substring
16769 (max (point-min) (- (point) 4)) (point))
16770 " "))
16771 (insert " "))
16772 (goto-char p))
16773 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16774 " " (or org-ans1 org-ans2)))
16775 (org-end-time-was-given nil)
16776 (f (org-read-date-analyze ans def defdecode))
16777 (fmts (if org-dcst
16778 org-time-stamp-custom-formats
16779 org-time-stamp-formats))
16780 (fmt (if (or with-time
16781 (and (boundp 'org-time-was-given) org-time-was-given))
16782 (cdr fmts)
16783 (car fmts)))
16784 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
16785 (when (and org-end-time-was-given
16786 (string-match org-plain-time-of-day-regexp txt))
16787 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16788 org-end-time-was-given
16789 (substring txt (match-end 0)))))
16790 (setq org-read-date-overlay
16791 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16792 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
16794 (defun org-read-date-analyze (ans def defdecode)
16795 "Analyze the combined answer of the date prompt."
16796 ;; FIXME: cleanup and comment
16797 (let (delta deltan deltaw deltadef year month day
16798 hour minute second wday pm h2 m2 tl wday1)
16800 (when (setq delta (org-read-date-get-relative ans (current-time) def))
16801 (setq ans (replace-match "" t t ans)
16802 deltan (car delta)
16803 deltaw (nth 1 delta)
16804 deltadef (nth 2 delta)))
16806 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
16807 (when (string-match
16808 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
16809 (setq year (if (match-end 2)
16810 (string-to-number (match-string 2 ans))
16811 (string-to-number (format-time-string "%Y")))
16812 month (string-to-number (match-string 3 ans))
16813 day (string-to-number (match-string 4 ans)))
16814 (if (< year 100) (setq year (+ 2000 year)))
16815 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
16816 t nil ans)))
16817 ;; Help matching am/pm times, because `parse-time-string' does not do that.
16818 ;; If there is a time with am/pm, and *no* time without it, we convert
16819 ;; so that matching will be successful.
16820 (loop for i from 1 to 2 do ; twice, for end time as well
16821 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
16822 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
16823 (setq hour (string-to-number (match-string 1 ans))
16824 minute (if (match-end 3)
16825 (string-to-number (match-string 3 ans))
16827 pm (equal ?p
16828 (string-to-char (downcase (match-string 4 ans)))))
16829 (if (and (= hour 12) (not pm))
16830 (setq hour 0)
16831 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
16832 (setq ans (replace-match (format "%02d:%02d" hour minute)
16833 t t ans))))
16835 ;; Check if a time range is given as a duration
16836 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
16837 (setq hour (string-to-number (match-string 1 ans))
16838 h2 (+ hour (string-to-number (match-string 3 ans)))
16839 minute (string-to-number (match-string 2 ans))
16840 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
16841 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
16842 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
16844 ;; Check if there is a time range
16845 (when (boundp 'org-end-time-was-given)
16846 (setq org-time-was-given nil)
16847 (when (and (string-match org-plain-time-of-day-regexp ans)
16848 (match-end 8))
16849 (setq org-end-time-was-given (match-string 8 ans))
16850 (setq ans (concat (substring ans 0 (match-beginning 7))
16851 (substring ans (match-end 7))))))
16853 (setq tl (parse-time-string ans)
16854 day (or (nth 3 tl) (nth 3 defdecode))
16855 month (or (nth 4 tl)
16856 (if (and org-read-date-prefer-future
16857 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
16858 (1+ (nth 4 defdecode))
16859 (nth 4 defdecode)))
16860 year (or (nth 5 tl)
16861 (if (and org-read-date-prefer-future
16862 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
16863 (1+ (nth 5 defdecode))
16864 (nth 5 defdecode)))
16865 hour (or (nth 2 tl) (nth 2 defdecode))
16866 minute (or (nth 1 tl) (nth 1 defdecode))
16867 second (or (nth 0 tl) 0)
16868 wday (nth 6 tl))
16869 (when deltan
16870 (unless deltadef
16871 (let ((now (decode-time (current-time))))
16872 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
16873 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
16874 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
16875 ((equal deltaw "m") (setq month (+ month deltan)))
16876 ((equal deltaw "y") (setq year (+ year deltan)))))
16877 (when (and wday (not (nth 3 tl)))
16878 ;; Weekday was given, but no day, so pick that day in the week
16879 ;; on or after the derived date.
16880 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
16881 (unless (equal wday wday1)
16882 (setq day (+ day (% (- wday wday1 -7) 7)))))
16883 (if (and (boundp 'org-time-was-given)
16884 (nth 2 tl))
16885 (setq org-time-was-given t))
16886 (if (< year 100) (setq year (+ 2000 year)))
16887 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
16888 (list second minute hour day month year)))
16890 (defvar parse-time-weekdays)
16892 (defun org-read-date-get-relative (s today default)
16893 "Check string S for special relative date string.
16894 TODAY and DEFAULT are internal times, for today and for a default.
16895 Return shift list (N what def-flag)
16896 WHAT is \"d\", \"w\", \"m\", or \"y\" for day. week, month, year.
16897 N is the number if WHATs to shift
16898 DEF-FLAG is t when a double ++ or -- indicates shift relative to
16899 the DEFAULT date rather than TODAY."
16900 (when (string-match
16901 (concat
16902 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
16903 "\\([0-9]+\\)?"
16904 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
16905 "\\([ \t]\\|$\\)") s)
16906 (let* ((dir (if (match-end 1)
16907 (string-to-char (substring (match-string 1 s) -1))
16908 ?+))
16909 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
16910 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
16911 (what (if (match-end 3) (match-string 3 s) "d"))
16912 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
16913 (date (if rel default today))
16914 (wday (nth 6 (decode-time date)))
16915 delta)
16916 (if wday1
16917 (progn
16918 (setq delta (mod (+ 7 (- wday1 wday)) 7))
16919 (if (= dir ?-) (setq delta (- delta 7)))
16920 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
16921 (list delta "d" rel))
16922 (list (* n (if (= dir ?-) -1 1)) what rel)))))
16924 (defun org-eval-in-calendar (form &optional keepdate)
16925 "Eval FORM in the calendar window and return to current window.
16926 Also, store the cursor date in variable org-ans2."
16927 (let ((sw (selected-window)))
16928 (select-window (get-buffer-window "*Calendar*"))
16929 (eval form)
16930 (when (and (not keepdate) (calendar-cursor-to-date))
16931 (let* ((date (calendar-cursor-to-date))
16932 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16933 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
16934 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
16935 (select-window sw)))
16937 ; ;; Update the prompt to show new default date
16938 ; (save-excursion
16939 ; (goto-char (point-min))
16940 ; (when (and org-ans2
16941 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
16942 ; (get-text-property (match-end 0) 'field))
16943 ; (let ((inhibit-read-only t))
16944 ; (replace-match (concat "[" org-ans2 "]") t t)
16945 ; (add-text-properties (point-min) (1+ (match-end 0))
16946 ; (text-properties-at (1+ (point-min)))))))))
16948 (defun org-calendar-select ()
16949 "Return to `org-read-date' with the date currently selected.
16950 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
16951 (interactive)
16952 (when (calendar-cursor-to-date)
16953 (let* ((date (calendar-cursor-to-date))
16954 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16955 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
16956 (if (active-minibuffer-window) (exit-minibuffer))))
16958 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
16959 "Insert a date stamp for the date given by the internal TIME.
16960 WITH-HM means, use the stamp format that includes the time of the day.
16961 INACTIVE means use square brackets instead of angular ones, so that the
16962 stamp will not contribute to the agenda.
16963 PRE and POST are optional strings to be inserted before and after the
16964 stamp.
16965 The command returns the inserted time stamp."
16966 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
16967 stamp)
16968 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
16969 (insert-before-markers (or pre ""))
16970 (insert-before-markers (setq stamp (format-time-string fmt time)))
16971 (when (listp extra)
16972 (setq extra (car extra))
16973 (if (and (stringp extra)
16974 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
16975 (setq extra (format "-%02d:%02d"
16976 (string-to-number (match-string 1 extra))
16977 (string-to-number (match-string 2 extra))))
16978 (setq extra nil)))
16979 (when extra
16980 (backward-char 1)
16981 (insert-before-markers extra)
16982 (forward-char 1))
16983 (insert-before-markers (or post ""))
16984 stamp))
16986 (defun org-toggle-time-stamp-overlays ()
16987 "Toggle the use of custom time stamp formats."
16988 (interactive)
16989 (setq org-display-custom-times (not org-display-custom-times))
16990 (unless org-display-custom-times
16991 (let ((p (point-min)) (bmp (buffer-modified-p)))
16992 (while (setq p (next-single-property-change p 'display))
16993 (if (and (get-text-property p 'display)
16994 (eq (get-text-property p 'face) 'org-date))
16995 (remove-text-properties
16996 p (setq p (next-single-property-change p 'display))
16997 '(display t))))
16998 (set-buffer-modified-p bmp)))
16999 (if (featurep 'xemacs)
17000 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17001 (org-restart-font-lock)
17002 (setq org-table-may-need-update t)
17003 (if org-display-custom-times
17004 (message "Time stamps are overlayed with custom format")
17005 (message "Time stamp overlays removed")))
17007 (defun org-display-custom-time (beg end)
17008 "Overlay modified time stamp format over timestamp between BED and END."
17009 (let* ((ts (buffer-substring beg end))
17010 t1 w1 with-hm tf time str w2 (off 0))
17011 (save-match-data
17012 (setq t1 (org-parse-time-string ts t))
17013 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
17014 (setq off (- (match-end 0) (match-beginning 0)))))
17015 (setq end (- end off))
17016 (setq w1 (- end beg)
17017 with-hm (and (nth 1 t1) (nth 2 t1))
17018 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17019 time (org-fix-decoded-time t1)
17020 str (org-add-props
17021 (format-time-string
17022 (substring tf 1 -1) (apply 'encode-time time))
17023 nil 'mouse-face 'highlight)
17024 w2 (length str))
17025 (if (not (= w2 w1))
17026 (add-text-properties (1+ beg) (+ 2 beg)
17027 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17028 (if (featurep 'xemacs)
17029 (progn
17030 (put-text-property beg end 'invisible t)
17031 (put-text-property beg end 'end-glyph (make-glyph str)))
17032 (put-text-property beg end 'display str))))
17034 (defun org-translate-time (string)
17035 "Translate all timestamps in STRING to custom format.
17036 But do this only if the variable `org-display-custom-times' is set."
17037 (when org-display-custom-times
17038 (save-match-data
17039 (let* ((start 0)
17040 (re org-ts-regexp-both)
17041 t1 with-hm inactive tf time str beg end)
17042 (while (setq start (string-match re string start))
17043 (setq beg (match-beginning 0)
17044 end (match-end 0)
17045 t1 (save-match-data
17046 (org-parse-time-string (substring string beg end) t))
17047 with-hm (and (nth 1 t1) (nth 2 t1))
17048 inactive (equal (substring string beg (1+ beg)) "[")
17049 tf (funcall (if with-hm 'cdr 'car)
17050 org-time-stamp-custom-formats)
17051 time (org-fix-decoded-time t1)
17052 str (format-time-string
17053 (concat
17054 (if inactive "[" "<") (substring tf 1 -1)
17055 (if inactive "]" ">"))
17056 (apply 'encode-time time))
17057 string (replace-match str t t string)
17058 start (+ start (length str)))))))
17059 string)
17061 (defun org-fix-decoded-time (time)
17062 "Set 0 instead of nil for the first 6 elements of time.
17063 Don't touch the rest."
17064 (let ((n 0))
17065 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17067 (defun org-days-to-time (timestamp-string)
17068 "Difference between TIMESTAMP-STRING and now in days."
17069 (- (time-to-days (org-time-string-to-time timestamp-string))
17070 (time-to-days (current-time))))
17072 (defun org-deadline-close (timestamp-string &optional ndays)
17073 "Is the time in TIMESTAMP-STRING close to the current date?"
17074 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17075 (and (< (org-days-to-time timestamp-string) ndays)
17076 (not (org-entry-is-done-p))))
17078 (defun org-get-wdays (ts)
17079 "Get the deadline lead time appropriate for timestring TS."
17080 (cond
17081 ((<= org-deadline-warning-days 0)
17082 ;; 0 or negative, enforce this value no matter what
17083 (- org-deadline-warning-days))
17084 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
17085 ;; lead time is specified.
17086 (floor (* (string-to-number (match-string 1 ts))
17087 (cdr (assoc (match-string 2 ts)
17088 '(("d" . 1) ("w" . 7)
17089 ("m" . 30.4) ("y" . 365.25)))))))
17090 ;; go for the default.
17091 (t org-deadline-warning-days)))
17093 (defun org-calendar-select-mouse (ev)
17094 "Return to `org-read-date' with the date currently selected.
17095 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17096 (interactive "e")
17097 (mouse-set-point ev)
17098 (when (calendar-cursor-to-date)
17099 (let* ((date (calendar-cursor-to-date))
17100 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17101 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17102 (if (active-minibuffer-window) (exit-minibuffer))))
17104 (defun org-check-deadlines (ndays)
17105 "Check if there are any deadlines due or past due.
17106 A deadline is considered due if it happens within `org-deadline-warning-days'
17107 days from today's date. If the deadline appears in an entry marked DONE,
17108 it is not shown. The prefix arg NDAYS can be used to test that many
17109 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17110 (interactive "P")
17111 (let* ((org-warn-days
17112 (cond
17113 ((equal ndays '(4)) 100000)
17114 (ndays (prefix-numeric-value ndays))
17115 (t (abs org-deadline-warning-days))))
17116 (case-fold-search nil)
17117 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17118 (callback
17119 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17121 (message "%d deadlines past-due or due within %d days"
17122 (org-occur regexp nil callback)
17123 org-warn-days)))
17125 (defun org-evaluate-time-range (&optional to-buffer)
17126 "Evaluate a time range by computing the difference between start and end.
17127 Normally the result is just printed in the echo area, but with prefix arg
17128 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17129 If the time range is actually in a table, the result is inserted into the
17130 next column.
17131 For time difference computation, a year is assumed to be exactly 365
17132 days in order to avoid rounding problems."
17133 (interactive "P")
17135 (org-clock-update-time-maybe)
17136 (save-excursion
17137 (unless (org-at-date-range-p t)
17138 (goto-char (point-at-bol))
17139 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17140 (if (not (org-at-date-range-p t))
17141 (error "Not at a time-stamp range, and none found in current line")))
17142 (let* ((ts1 (match-string 1))
17143 (ts2 (match-string 2))
17144 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17145 (match-end (match-end 0))
17146 (time1 (org-time-string-to-time ts1))
17147 (time2 (org-time-string-to-time ts2))
17148 (t1 (time-to-seconds time1))
17149 (t2 (time-to-seconds time2))
17150 (diff (abs (- t2 t1)))
17151 (negative (< (- t2 t1) 0))
17152 ;; (ys (floor (* 365 24 60 60)))
17153 (ds (* 24 60 60))
17154 (hs (* 60 60))
17155 (fy "%dy %dd %02d:%02d")
17156 (fy1 "%dy %dd")
17157 (fd "%dd %02d:%02d")
17158 (fd1 "%dd")
17159 (fh "%02d:%02d")
17160 y d h m align)
17161 (if havetime
17162 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17164 d (floor (/ diff ds)) diff (mod diff ds)
17165 h (floor (/ diff hs)) diff (mod diff hs)
17166 m (floor (/ diff 60)))
17167 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17169 d (floor (+ (/ diff ds) 0.5))
17170 h 0 m 0))
17171 (if (not to-buffer)
17172 (message (org-make-tdiff-string y d h m))
17173 (if (org-at-table-p)
17174 (progn
17175 (goto-char match-end)
17176 (setq align t)
17177 (and (looking-at " *|") (goto-char (match-end 0))))
17178 (goto-char match-end))
17179 (if (looking-at
17180 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17181 (replace-match ""))
17182 (if negative (insert " -"))
17183 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17184 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17185 (insert " " (format fh h m))))
17186 (if align (org-table-align))
17187 (message "Time difference inserted")))))
17189 (defun org-make-tdiff-string (y d h m)
17190 (let ((fmt "")
17191 (l nil))
17192 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
17193 l (push y l)))
17194 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
17195 l (push d l)))
17196 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
17197 l (push h l)))
17198 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
17199 l (push m l)))
17200 (apply 'format fmt (nreverse l))))
17202 (defun org-time-string-to-time (s)
17203 (apply 'encode-time (org-parse-time-string s)))
17205 (defun org-time-string-to-absolute (s &optional daynr)
17206 "Convert a time stamp to an absolute day number.
17207 If there is a specifyer for a cyclic time stamp, get the closest date to
17208 DAYNR."
17209 (cond
17210 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
17211 (if (org-diary-sexp-entry (match-string 1 s) "" date)
17212 daynr
17213 (+ daynr 1000)))
17214 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
17215 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
17216 (time-to-days (current-time))) (match-string 0 s)))
17217 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
17219 (defun org-time-from-absolute (d)
17220 "Return the time corresponding to date D.
17221 D may be an absolute day number, or a calendar-type list (month day year)."
17222 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17223 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17225 (defun org-calendar-holiday ()
17226 "List of holidays, for Diary display in Org-mode."
17227 (require 'holidays)
17228 (let ((hl (funcall
17229 (if (fboundp 'calendar-check-holidays)
17230 'calendar-check-holidays 'check-calendar-holidays) date)))
17231 (if hl (mapconcat 'identity hl "; "))))
17233 (defun org-diary-sexp-entry (sexp entry date)
17234 "Process a SEXP diary ENTRY for DATE."
17235 (require 'diary-lib)
17236 (let ((result (if calendar-debug-sexp
17237 (let ((stack-trace-on-error t))
17238 (eval (car (read-from-string sexp))))
17239 (condition-case nil
17240 (eval (car (read-from-string sexp)))
17241 (error
17242 (beep)
17243 (message "Bad sexp at line %d in %s: %s"
17244 (org-current-line)
17245 (buffer-file-name) sexp)
17246 (sleep-for 2))))))
17247 (cond ((stringp result) result)
17248 ((and (consp result)
17249 (stringp (cdr result))) (cdr result))
17250 (result entry)
17251 (t nil))))
17253 (defun org-diary-to-ical-string (frombuf)
17254 "Get iCalendar entries from diary entries in buffer FROMBUF.
17255 This uses the icalendar.el library."
17256 (let* ((tmpdir (if (featurep 'xemacs)
17257 (temp-directory)
17258 temporary-file-directory))
17259 (tmpfile (make-temp-name
17260 (expand-file-name "orgics" tmpdir)))
17261 buf rtn b e)
17262 (save-excursion
17263 (set-buffer frombuf)
17264 (icalendar-export-region (point-min) (point-max) tmpfile)
17265 (setq buf (find-buffer-visiting tmpfile))
17266 (set-buffer buf)
17267 (goto-char (point-min))
17268 (if (re-search-forward "^BEGIN:VEVENT" nil t)
17269 (setq b (match-beginning 0)))
17270 (goto-char (point-max))
17271 (if (re-search-backward "^END:VEVENT" nil t)
17272 (setq e (match-end 0)))
17273 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17274 (kill-buffer buf)
17275 (kill-buffer frombuf)
17276 (delete-file tmpfile)
17277 rtn))
17279 (defun org-closest-date (start current change)
17280 "Find the date closest to CURRENT that is consistent with START and CHANGE."
17281 ;; Make the proper lists from the dates
17282 (catch 'exit
17283 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
17284 dn dw sday cday n1 n2
17285 d m y y1 y2 date1 date2 nmonths nm ny m2)
17287 (setq start (org-date-to-gregorian start)
17288 current (org-date-to-gregorian
17289 (if org-agenda-repeating-timestamp-show-all
17290 current
17291 (time-to-days (current-time))))
17292 sday (calendar-absolute-from-gregorian start)
17293 cday (calendar-absolute-from-gregorian current))
17295 (if (<= cday sday) (throw 'exit sday))
17297 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
17298 (setq dn (string-to-number (match-string 1 change))
17299 dw (cdr (assoc (match-string 2 change) a1)))
17300 (error "Invalid change specifyer: %s" change))
17301 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
17302 (cond
17303 ((eq dw 'day)
17304 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
17305 n2 (+ n1 dn)))
17306 ((eq dw 'year)
17307 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
17308 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
17309 (setq date1 (list m d y1)
17310 n1 (calendar-absolute-from-gregorian date1)
17311 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
17312 n2 (calendar-absolute-from-gregorian date2)))
17313 ((eq dw 'month)
17314 ;; approx number of month between the tow dates
17315 (setq nmonths (floor (/ (- cday sday) 30.436875)))
17316 ;; How often does dn fit in there?
17317 (setq d (nth 1 start) m (car start) y (nth 2 start)
17318 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
17319 m (+ m nm)
17320 ny (floor (/ m 12))
17321 y (+ y ny)
17322 m (- m (* ny 12)))
17323 (while (> m 12) (setq m (- m 12) y (1+ y)))
17324 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
17325 (setq m2 (+ m dn) y2 y)
17326 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17327 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
17328 (while (< n2 cday)
17329 (setq n1 n2 m m2 y y2)
17330 (setq m2 (+ m dn) y2 y)
17331 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
17332 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
17334 (if org-agenda-repeating-timestamp-show-all
17335 (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)
17336 (if (= cday n1) n1 n2)))))
17338 (defun org-date-to-gregorian (date)
17339 "Turn any specification of DATE into a gregorian date for the calendar."
17340 (cond ((integerp date) (calendar-gregorian-from-absolute date))
17341 ((and (listp date) (= (length date) 3)) date)
17342 ((stringp date)
17343 (setq date (org-parse-time-string date))
17344 (list (nth 4 date) (nth 3 date) (nth 5 date)))
17345 ((listp date)
17346 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
17348 (defun org-parse-time-string (s &optional nodefault)
17349 "Parse the standard Org-mode time string.
17350 This should be a lot faster than the normal `parse-time-string'.
17351 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17352 hour and minute fields will be nil if not given."
17353 (if (string-match org-ts-regexp0 s)
17354 (list 0
17355 (if (or (match-beginning 8) (not nodefault))
17356 (string-to-number (or (match-string 8 s) "0")))
17357 (if (or (match-beginning 7) (not nodefault))
17358 (string-to-number (or (match-string 7 s) "0")))
17359 (string-to-number (match-string 4 s))
17360 (string-to-number (match-string 3 s))
17361 (string-to-number (match-string 2 s))
17362 nil nil nil)
17363 (make-list 9 0)))
17365 (defun org-timestamp-up (&optional arg)
17366 "Increase the date item at the cursor by one.
17367 If the cursor is on the year, change the year. If it is on the month or
17368 the day, change that.
17369 With prefix ARG, change by that many units."
17370 (interactive "p")
17371 (org-timestamp-change (prefix-numeric-value arg)))
17373 (defun org-timestamp-down (&optional arg)
17374 "Decrease the date item at the cursor by one.
17375 If the cursor is on the year, change the year. If it is on the month or
17376 the day, change that.
17377 With prefix ARG, change by that many units."
17378 (interactive "p")
17379 (org-timestamp-change (- (prefix-numeric-value arg))))
17381 (defun org-timestamp-up-day (&optional arg)
17382 "Increase the date in the time stamp by one day.
17383 With prefix ARG, change that many days."
17384 (interactive "p")
17385 (if (and (not (org-at-timestamp-p t))
17386 (org-on-heading-p))
17387 (org-todo 'up)
17388 (org-timestamp-change (prefix-numeric-value arg) 'day)))
17390 (defun org-timestamp-down-day (&optional arg)
17391 "Decrease the date in the time stamp by one day.
17392 With prefix ARG, change that many days."
17393 (interactive "p")
17394 (if (and (not (org-at-timestamp-p t))
17395 (org-on-heading-p))
17396 (org-todo 'down)
17397 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
17399 (defsubst org-pos-in-match-range (pos n)
17400 (and (match-beginning n)
17401 (<= (match-beginning n) pos)
17402 (>= (match-end n) pos)))
17404 (defun org-at-timestamp-p (&optional inactive-ok)
17405 "Determine if the cursor is in or at a timestamp."
17406 (interactive)
17407 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17408 (pos (point))
17409 (ans (or (looking-at tsr)
17410 (save-excursion
17411 (skip-chars-backward "^[<\n\r\t")
17412 (if (> (point) (point-min)) (backward-char 1))
17413 (and (looking-at tsr)
17414 (> (- (match-end 0) pos) -1))))))
17415 (and ans
17416 (boundp 'org-ts-what)
17417 (setq org-ts-what
17418 (cond
17419 ((= pos (match-beginning 0)) 'bracket)
17420 ((= pos (1- (match-end 0))) 'bracket)
17421 ((org-pos-in-match-range pos 2) 'year)
17422 ((org-pos-in-match-range pos 3) 'month)
17423 ((org-pos-in-match-range pos 7) 'hour)
17424 ((org-pos-in-match-range pos 8) 'minute)
17425 ((or (org-pos-in-match-range pos 4)
17426 (org-pos-in-match-range pos 5)) 'day)
17427 ((and (> pos (or (match-end 8) (match-end 5)))
17428 (< pos (match-end 0)))
17429 (- pos (or (match-end 8) (match-end 5))))
17430 (t 'day))))
17431 ans))
17433 (defun org-toggle-timestamp-type ()
17435 (interactive)
17436 (when (org-at-timestamp-p t)
17437 (save-excursion
17438 (goto-char (match-beginning 0))
17439 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
17440 (goto-char (1- (match-end 0)))
17441 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
17442 (message "Timestamp is now %sactive"
17443 (if (equal (char-before) ?>) "in" ""))))
17445 (defun org-timestamp-change (n &optional what)
17446 "Change the date in the time stamp at point.
17447 The date will be changed by N times WHAT. WHAT can be `day', `month',
17448 `year', `minute', `second'. If WHAT is not given, the cursor position
17449 in the timestamp determines what will be changed."
17450 (let ((pos (point))
17451 with-hm inactive
17452 org-ts-what
17453 extra
17454 ts time time0)
17455 (if (not (org-at-timestamp-p t))
17456 (error "Not at a timestamp"))
17457 (if (and (not what) (eq org-ts-what 'bracket))
17458 (org-toggle-timestamp-type)
17459 (if (and (not what) (not (eq org-ts-what 'day))
17460 org-display-custom-times
17461 (get-text-property (point) 'display)
17462 (not (get-text-property (1- (point)) 'display)))
17463 (setq org-ts-what 'day))
17464 (setq org-ts-what (or what org-ts-what)
17465 inactive (= (char-after (match-beginning 0)) ?\[)
17466 ts (match-string 0))
17467 (replace-match "")
17468 (if (string-match
17469 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
17471 (setq extra (match-string 1 ts)))
17472 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17473 (setq with-hm t))
17474 (setq time0 (org-parse-time-string ts))
17475 (setq time
17476 (encode-time (or (car time0) 0)
17477 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17478 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17479 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17480 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17481 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17482 (nthcdr 6 time0)))
17483 (when (integerp org-ts-what)
17484 (setq extra (org-modify-ts-extra extra org-ts-what n)))
17485 (if (eq what 'calendar)
17486 (let ((cal-date (org-get-date-from-calendar)))
17487 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17488 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
17489 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
17490 (setcar time0 (or (car time0) 0))
17491 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
17492 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
17493 (setq time (apply 'encode-time time0))))
17494 (setq org-last-changed-timestamp
17495 (org-insert-time-stamp time with-hm inactive nil nil extra))
17496 (org-clock-update-time-maybe)
17497 (goto-char pos)
17498 ;; Try to recenter the calendar window, if any
17499 (if (and org-calendar-follow-timestamp-change
17500 (get-buffer-window "*Calendar*" t)
17501 (memq org-ts-what '(day month year)))
17502 (org-recenter-calendar (time-to-days time))))))
17504 ;; FIXME: does not yet work for lead times
17505 (defun org-modify-ts-extra (s pos n)
17506 "Change the different parts of the lead-time and repeat fields in timestamp."
17507 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
17508 ng h m new)
17509 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
17510 (cond
17511 ((or (org-pos-in-match-range pos 2)
17512 (org-pos-in-match-range pos 3))
17513 (setq m (string-to-number (match-string 3 s))
17514 h (string-to-number (match-string 2 s)))
17515 (if (org-pos-in-match-range pos 2)
17516 (setq h (+ h n))
17517 (setq m (+ m n)))
17518 (if (< m 0) (setq m (+ m 60) h (1- h)))
17519 (if (> m 59) (setq m (- m 60) h (1+ h)))
17520 (setq h (min 24 (max 0 h)))
17521 (setq ng 1 new (format "-%02d:%02d" h m)))
17522 ((org-pos-in-match-range pos 6)
17523 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
17524 ((org-pos-in-match-range pos 5)
17525 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
17527 (when ng
17528 (setq s (concat
17529 (substring s 0 (match-beginning ng))
17531 (substring s (match-end ng))))))
17534 (defun org-recenter-calendar (date)
17535 "If the calendar is visible, recenter it to DATE."
17536 (let* ((win (selected-window))
17537 (cwin (get-buffer-window "*Calendar*" t))
17538 (calendar-move-hook nil))
17539 (when cwin
17540 (select-window cwin)
17541 (calendar-goto-date (if (listp date) date
17542 (calendar-gregorian-from-absolute date)))
17543 (select-window win))))
17545 (defun org-goto-calendar (&optional arg)
17546 "Go to the Emacs calendar at the current date.
17547 If there is a time stamp in the current line, go to that date.
17548 A prefix ARG can be used to force the current date."
17549 (interactive "P")
17550 (let ((tsr org-ts-regexp) diff
17551 (calendar-move-hook nil)
17552 (view-calendar-holidays-initially nil)
17553 (view-diary-entries-initially nil))
17554 (if (or (org-at-timestamp-p)
17555 (save-excursion
17556 (beginning-of-line 1)
17557 (looking-at (concat ".*" tsr))))
17558 (let ((d1 (time-to-days (current-time)))
17559 (d2 (time-to-days
17560 (org-time-string-to-time (match-string 1)))))
17561 (setq diff (- d2 d1))))
17562 (calendar)
17563 (calendar-goto-today)
17564 (if (and diff (not arg)) (calendar-forward-day diff))))
17566 (defun org-get-date-from-calendar ()
17567 "Return a list (month day year) of date at point in calendar."
17568 (with-current-buffer "*Calendar*"
17569 (save-match-data
17570 (calendar-cursor-to-date))))
17572 (defun org-date-from-calendar ()
17573 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
17574 If there is already a time stamp at the cursor position, update it."
17575 (interactive)
17576 (if (org-at-timestamp-p t)
17577 (org-timestamp-change 0 'calendar)
17578 (let ((cal-date (org-get-date-from-calendar)))
17579 (org-insert-time-stamp
17580 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
17582 ;; Make appt aware of appointments from the agenda
17583 ;;;###autoload
17584 (defun org-agenda-to-appt (&optional filter)
17585 "Activate appointments found in `org-agenda-files'.
17586 When prefixed, prompt for a regular expression and use it as a
17587 filter: only add entries if they match this regular expression.
17589 FILTER can be a string. In this case, use this string as a
17590 regular expression to filter results.
17592 FILTER can also be an alist, with the car of each cell being
17593 either 'headline or 'category. For example:
17595 '((headline \"IMPORTANT\")
17596 (category \"Work\"))
17598 will only add headlines containing IMPORTANT or headlines
17599 belonging to the category \"Work\"."
17600 (interactive "P")
17601 (require 'calendar)
17602 (if (equal filter '(4))
17603 (setq filter (read-from-minibuffer "Regexp filter: ")))
17604 (let* ((cnt 0) ; count added events
17605 (today (org-date-to-gregorian
17606 (time-to-days (current-time))))
17607 (files (org-agenda-files)) entries file)
17608 ;; Get all entries which may contain an appt
17609 (while (setq file (pop files))
17610 (setq entries
17611 (append entries
17612 (org-agenda-get-day-entries
17613 file today
17614 :timestamp :scheduled :deadline))))
17615 (setq entries (delq nil entries))
17616 ;; Map thru entries and find if they pass thru the filter
17617 (mapc
17618 (lambda(x)
17619 (let* ((evt (org-trim (get-text-property 1 'txt x)))
17620 (cat (get-text-property 1 'org-category x))
17621 (tod (get-text-property 1 'time-of-day x))
17622 (ok (or (null filter)
17623 (and (stringp filter) (string-match filter evt))
17624 (and (listp filter)
17625 (or (string-match
17626 (cadr (assoc 'category filter)) cat)
17627 (string-match
17628 (cadr (assoc 'headline filter)) evt))))))
17629 ;; FIXME Shall we remove text-properties for the appt text?
17630 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
17631 (when (and ok tod)
17632 (setq tod (number-to-string tod)
17633 tod (when (string-match
17634 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
17635 (concat (match-string 1 tod) ":"
17636 (match-string 2 tod))))
17637 (appt-add tod evt)
17638 (setq cnt (1+ cnt))))) entries)
17639 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" ""))))
17641 ;;; The clock for measuring work time.
17643 (defvar org-mode-line-string "")
17644 (put 'org-mode-line-string 'risky-local-variable t)
17646 (defvar org-mode-line-timer nil)
17647 (defvar org-clock-heading "")
17648 (defvar org-clock-start-time "")
17650 (defun org-update-mode-line ()
17651 (let* ((delta (- (time-to-seconds (current-time))
17652 (time-to-seconds org-clock-start-time)))
17653 (h (floor delta 3600))
17654 (m (floor (- delta (* 3600 h)) 60)))
17655 (setq org-mode-line-string
17656 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
17657 'help-echo "Org-mode clock is running"))
17658 (force-mode-line-update)))
17660 (defvar org-clock-marker (make-marker)
17661 "Marker recording the last clock-in.")
17662 (defvar org-clock-mode-line-entry nil
17663 "Information for the modeline about the running clock.")
17665 (defun org-clock-in ()
17666 "Start the clock on the current item.
17667 If necessary, clock-out of the currently active clock."
17668 (interactive)
17669 (org-clock-out t)
17670 (let (ts)
17671 (save-excursion
17672 (org-back-to-heading t)
17673 (if (and org-clock-heading-function
17674 (functionp org-clock-heading-function))
17675 (setq org-clock-heading (funcall org-clock-heading-function))
17676 (if (looking-at org-todo-line-regexp)
17677 (setq org-clock-heading (match-string 3))
17678 (setq org-clock-heading "???")))
17679 (setq org-clock-heading (propertize org-clock-heading 'face nil))
17680 (org-clock-find-position)
17682 (insert "\n") (backward-char 1)
17683 (indent-relative)
17684 (insert org-clock-string " ")
17685 (setq org-clock-start-time (current-time))
17686 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17687 (move-marker org-clock-marker (point) (buffer-base-buffer))
17688 (or global-mode-string (setq global-mode-string '("")))
17689 (or (memq 'org-mode-line-string global-mode-string)
17690 (setq global-mode-string
17691 (append global-mode-string '(org-mode-line-string))))
17692 (org-update-mode-line)
17693 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
17694 (message "Clock started at %s" ts))))
17696 (defun org-clock-find-position ()
17697 "Find the location where the next clock line should be inserted."
17698 (org-back-to-heading t)
17699 (catch 'exit
17700 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
17701 (re (concat "^[ \t]*" org-clock-string))
17702 (cnt 0)
17703 first last)
17704 (goto-char beg)
17705 (when (eobp) (newline) (setq end (max (point) end)))
17706 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
17707 ;; we seem to have a CLOCK drawer, so go there.
17708 (beginning-of-line 2)
17709 (throw 'exit t))
17710 ;; Lets count the CLOCK lines
17711 (goto-char beg)
17712 (while (re-search-forward re end t)
17713 (setq first (or first (match-beginning 0))
17714 last (match-beginning 0)
17715 cnt (1+ cnt)))
17716 (when (and (integerp org-clock-into-drawer)
17717 (>= (1+ cnt) org-clock-into-drawer))
17718 ;; Wrap current entries into a new drawer
17719 (goto-char last)
17720 (beginning-of-line 2)
17721 (if (org-at-item-p) (org-end-of-item))
17722 (insert ":END:\n")
17723 (beginning-of-line 0)
17724 (org-indent-line-function)
17725 (goto-char first)
17726 (insert ":CLOCK:\n")
17727 (beginning-of-line 0)
17728 (org-indent-line-function)
17729 (org-flag-drawer t)
17730 (beginning-of-line 2)
17731 (throw 'exit nil))
17733 (goto-char beg)
17734 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17735 (not (equal (match-string 1) org-clock-string)))
17736 ;; Planning info, skip to after it
17737 (beginning-of-line 2)
17738 (or (bolp) (newline)))
17739 (when (eq t org-clock-into-drawer)
17740 (insert ":CLOCK:\n:END:\n")
17741 (beginning-of-line -1)
17742 (org-indent-line-function)
17743 (org-flag-drawer t)
17744 (beginning-of-line 2)
17745 (org-indent-line-function)))))
17747 (defun org-clock-out (&optional fail-quietly)
17748 "Stop the currently running clock.
17749 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
17750 (interactive)
17751 (catch 'exit
17752 (if (not (marker-buffer org-clock-marker))
17753 (if fail-quietly (throw 'exit t) (error "No active clock")))
17754 (let (ts te s h m)
17755 (save-excursion
17756 (set-buffer (marker-buffer org-clock-marker))
17757 (goto-char org-clock-marker)
17758 (beginning-of-line 1)
17759 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
17760 (equal (match-string 1) org-clock-string))
17761 (setq ts (match-string 2))
17762 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
17763 (goto-char (match-end 0))
17764 (delete-region (point) (point-at-eol))
17765 (insert "--")
17766 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
17767 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
17768 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
17769 h (floor (/ s 3600))
17770 s (- s (* 3600 h))
17771 m (floor (/ s 60))
17772 s (- s (* 60 s)))
17773 (insert " => " (format "%2d:%02d" h m))
17774 (move-marker org-clock-marker nil)
17775 (let* ((logging (save-match-data (org-entry-get nil "LOGGING" t)))
17776 (org-log-done (org-parse-local-options logging 'org-log-done))
17777 (org-log-repeat (org-parse-local-options logging 'org-log-repeat)))
17778 (org-add-log-maybe 'clock-out))
17779 (when org-mode-line-timer
17780 (cancel-timer org-mode-line-timer)
17781 (setq org-mode-line-timer nil))
17782 (setq global-mode-string
17783 (delq 'org-mode-line-string global-mode-string))
17784 (force-mode-line-update)
17785 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
17787 (defun org-clock-cancel ()
17788 "Cancel the running clock be removing the start timestamp."
17789 (interactive)
17790 (if (not (marker-buffer org-clock-marker))
17791 (error "No active clock"))
17792 (save-excursion
17793 (set-buffer (marker-buffer org-clock-marker))
17794 (goto-char org-clock-marker)
17795 (delete-region (1- (point-at-bol)) (point-at-eol)))
17796 (message "Clock canceled"))
17798 (defun org-clock-goto (&optional delete-windows)
17799 "Go to the currently clocked-in entry."
17800 (interactive "P")
17801 (if (not (marker-buffer org-clock-marker))
17802 (error "No active clock"))
17803 (switch-to-buffer-other-window
17804 (marker-buffer org-clock-marker))
17805 (if delete-windows (delete-other-windows))
17806 (goto-char org-clock-marker)
17807 (org-show-entry)
17808 (org-back-to-heading)
17809 (recenter))
17811 (defvar org-clock-file-total-minutes nil
17812 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
17813 (make-variable-buffer-local 'org-clock-file-total-minutes)
17815 (defun org-clock-sum (&optional tstart tend)
17816 "Sum the times for each subtree.
17817 Puts the resulting times in minutes as a text property on each headline."
17818 (interactive)
17819 (let* ((bmp (buffer-modified-p))
17820 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
17821 org-clock-string
17822 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
17823 (lmax 30)
17824 (ltimes (make-vector lmax 0))
17825 (t1 0)
17826 (level 0)
17827 ts te dt
17828 time)
17829 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
17830 (save-excursion
17831 (goto-char (point-max))
17832 (while (re-search-backward re nil t)
17833 (cond
17834 ((match-end 2)
17835 ;; Two time stamps
17836 (setq ts (match-string 2)
17837 te (match-string 3)
17838 ts (time-to-seconds
17839 (apply 'encode-time (org-parse-time-string ts)))
17840 te (time-to-seconds
17841 (apply 'encode-time (org-parse-time-string te)))
17842 ts (if tstart (max ts tstart) ts)
17843 te (if tend (min te tend) te)
17844 dt (- te ts)
17845 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
17846 ((match-end 4)
17847 ;; A naket time
17848 (setq t1 (+ t1 (string-to-number (match-string 5))
17849 (* 60 (string-to-number (match-string 4))))))
17850 (t ;; A headline
17851 (setq level (- (match-end 1) (match-beginning 1)))
17852 (when (or (> t1 0) (> (aref ltimes level) 0))
17853 (loop for l from 0 to level do
17854 (aset ltimes l (+ (aref ltimes l) t1)))
17855 (setq t1 0 time (aref ltimes level))
17856 (loop for l from level to (1- lmax) do
17857 (aset ltimes l 0))
17858 (goto-char (match-beginning 0))
17859 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
17860 (setq org-clock-file-total-minutes (aref ltimes 0)))
17861 (set-buffer-modified-p bmp)))
17863 (defun org-clock-display (&optional total-only)
17864 "Show subtree times in the entire buffer.
17865 If TOTAL-ONLY is non-nil, only show the total time for the entire file
17866 in the echo area."
17867 (interactive)
17868 (org-remove-clock-overlays)
17869 (let (time h m p)
17870 (org-clock-sum)
17871 (unless total-only
17872 (save-excursion
17873 (goto-char (point-min))
17874 (while (or (and (equal (setq p (point)) (point-min))
17875 (get-text-property p :org-clock-minutes))
17876 (setq p (next-single-property-change
17877 (point) :org-clock-minutes)))
17878 (goto-char p)
17879 (when (setq time (get-text-property p :org-clock-minutes))
17880 (org-put-clock-overlay time (funcall outline-level))))
17881 (setq h (/ org-clock-file-total-minutes 60)
17882 m (- org-clock-file-total-minutes (* 60 h)))
17883 ;; Arrange to remove the overlays upon next change.
17884 (when org-remove-highlights-with-change
17885 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
17886 nil 'local))))
17887 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
17889 (defvar org-clock-overlays nil)
17890 (make-variable-buffer-local 'org-clock-overlays)
17892 (defun org-put-clock-overlay (time &optional level)
17893 "Put an overlays on the current line, displaying TIME.
17894 If LEVEL is given, prefix time with a corresponding number of stars.
17895 This creates a new overlay and stores it in `org-clock-overlays', so that it
17896 will be easy to remove."
17897 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
17898 (l (if level (org-get-legal-level level 0) 0))
17899 (off 0)
17900 ov tx)
17901 (move-to-column c)
17902 (unless (eolp) (skip-chars-backward "^ \t"))
17903 (skip-chars-backward " \t")
17904 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
17905 tx (concat (buffer-substring (1- (point)) (point))
17906 (make-string (+ off (max 0 (- c (current-column)))) ?.)
17907 (org-add-props (format "%s %2d:%02d%s"
17908 (make-string l ?*) h m
17909 (make-string (- 10 l) ?\ ))
17910 '(face secondary-selection))
17911 ""))
17912 (if (not (featurep 'xemacs))
17913 (org-overlay-put ov 'display tx)
17914 (org-overlay-put ov 'invisible t)
17915 (org-overlay-put ov 'end-glyph (make-glyph tx)))
17916 (push ov org-clock-overlays)))
17918 (defun org-remove-clock-overlays (&optional beg end noremove)
17919 "Remove the occur highlights from the buffer.
17920 BEG and END are ignored. If NOREMOVE is nil, remove this function
17921 from the `before-change-functions' in the current buffer."
17922 (interactive)
17923 (unless org-inhibit-highlight-removal
17924 (mapc 'org-delete-overlay org-clock-overlays)
17925 (setq org-clock-overlays nil)
17926 (unless noremove
17927 (remove-hook 'before-change-functions
17928 'org-remove-clock-overlays 'local))))
17930 (defun org-clock-out-if-current ()
17931 "Clock out if the current entry contains the running clock.
17932 This is used to stop the clock after a TODO entry is marked DONE,
17933 and is only done if the variable `org-clock-out-when-done' is not nil."
17934 (when (and org-clock-out-when-done
17935 (member state org-done-keywords)
17936 (equal (marker-buffer org-clock-marker) (current-buffer))
17937 (< (point) org-clock-marker)
17938 (> (save-excursion (outline-next-heading) (point))
17939 org-clock-marker))
17940 ;; Clock out, but don't accept a logging message for this.
17941 (let ((org-log-done (if (and (listp org-log-done)
17942 (member 'clock-out org-log-done))
17943 '(done)
17944 org-log-done)))
17945 (org-clock-out))))
17947 (add-hook 'org-after-todo-state-change-hook
17948 'org-clock-out-if-current)
17950 (defun org-check-running-clock ()
17951 "Check if the current buffer contains the running clock.
17952 If yes, offer to stop it and to save the buffer with the changes."
17953 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
17954 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
17955 (buffer-name))))
17956 (org-clock-out)
17957 (when (y-or-n-p "Save changed buffer?")
17958 (save-buffer))))
17960 (defun org-clock-report (&optional arg)
17961 "Create a table containing a report about clocked time.
17962 If the cursor is inside an existing clocktable block, then the table
17963 will be updated. If not, a new clocktable will be inserted.
17964 When called with a prefix argument, move to the first clock table in the
17965 buffer and update it."
17966 (interactive "P")
17967 (org-remove-clock-overlays)
17968 (when arg (org-find-dblock "clocktable"))
17969 (if (org-in-clocktable-p)
17970 (goto-char (org-in-clocktable-p))
17971 (org-create-dblock (list :name "clocktable"
17972 :maxlevel 2 :scope 'file)))
17973 (org-update-dblock))
17975 (defun org-in-clocktable-p ()
17976 "Check if the cursor is in a clocktable."
17977 (let ((pos (point)) start)
17978 (save-excursion
17979 (end-of-line 1)
17980 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
17981 (setq start (match-beginning 0))
17982 (re-search-forward "^#\\+END:.*" nil t)
17983 (>= (match-end 0) pos)
17984 start))))
17986 (defun org-clock-update-time-maybe ()
17987 "If this is a CLOCK line, update it and return t.
17988 Otherwise, return nil."
17989 (interactive)
17990 (save-excursion
17991 (beginning-of-line 1)
17992 (skip-chars-forward " \t")
17993 (when (looking-at org-clock-string)
17994 (let ((re (concat "[ \t]*" org-clock-string
17995 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
17996 "\\([ \t]*=>.*\\)?"))
17997 ts te h m s)
17998 (if (not (looking-at re))
18000 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
18001 (end-of-line 1)
18002 (setq ts (match-string 1)
18003 te (match-string 2))
18004 (setq s (- (time-to-seconds
18005 (apply 'encode-time (org-parse-time-string te)))
18006 (time-to-seconds
18007 (apply 'encode-time (org-parse-time-string ts))))
18008 h (floor (/ s 3600))
18009 s (- s (* 3600 h))
18010 m (floor (/ s 60))
18011 s (- s (* 60 s)))
18012 (insert " => " (format "%2d:%02d" h m))
18013 t)))))
18015 (defun org-clock-special-range (key &optional time as-strings)
18016 "Return two times bordering a special time range.
18017 Key is a symbol specifying the range and can be one of `today', `yesterday',
18018 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
18019 A week starts Monday 0:00 and ends Sunday 24:00.
18020 The range is determined relative to TIME. TIME defaults to the current time.
18021 The return value is a cons cell with two internal times like the ones
18022 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
18023 the returned times will be formatted strings."
18024 (let* ((tm (decode-time (or time (current-time))))
18025 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
18026 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
18027 (dow (nth 6 tm))
18028 s1 m1 h1 d1 month1 y1 diff ts te fm)
18029 (cond
18030 ((eq key 'today)
18031 (setq h 0 m 0 h1 24 m1 0))
18032 ((eq key 'yesterday)
18033 (setq d (1- d) h 0 m 0 h1 24 m1 0))
18034 ((eq key 'thisweek)
18035 (setq diff (if (= dow 0) 6 (1- dow))
18036 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18037 ((eq key 'lastweek)
18038 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
18039 m 0 h 0 d (- d diff) d1 (+ 7 d)))
18040 ((eq key 'thismonth)
18041 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
18042 ((eq key 'lastmonth)
18043 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
18044 ((eq key 'thisyear)
18045 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
18046 ((eq key 'lastyear)
18047 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
18048 (t (error "No such time block %s" key)))
18049 (setq ts (encode-time s m h d month y)
18050 te (encode-time (or s1 s) (or m1 m) (or h1 h)
18051 (or d1 d) (or month1 month) (or y1 y)))
18052 (setq fm (cdr org-time-stamp-formats))
18053 (if as-strings
18054 (cons (format-time-string fm ts) (format-time-string fm te))
18055 (cons ts te))))
18057 (defun org-dblock-write:clocktable (params)
18058 "Write the standard clocktable."
18059 (let ((hlchars '((1 . "*") (2 . "/")))
18060 (emph nil)
18061 (ins (make-marker))
18062 (total-time nil)
18063 ipos time h m p level hlc hdl maxlevel
18064 ts te cc block beg end pos scope tbl tostring multifile)
18065 (setq scope (plist-get params :scope)
18066 tostring (plist-get params :tostring)
18067 multifile (plist-get params :multifile)
18068 maxlevel (or (plist-get params :maxlevel) 3)
18069 emph (plist-get params :emphasize)
18070 ts (plist-get params :tstart)
18071 te (plist-get params :tend)
18072 block (plist-get params :block))
18073 (when block
18074 (setq cc (org-clock-special-range block nil t)
18075 ts (car cc) te (cdr cc)))
18076 (if ts (setq ts (time-to-seconds
18077 (apply 'encode-time (org-parse-time-string ts)))))
18078 (if te (setq te (time-to-seconds
18079 (apply 'encode-time (org-parse-time-string te)))))
18080 (move-marker ins (point))
18081 (setq ipos (point))
18083 ;; Get the right scope
18084 (setq pos (point))
18085 (save-restriction
18086 (cond
18087 ((not scope))
18088 ((eq scope 'file) (widen))
18089 ((eq scope 'subtree) (org-narrow-to-subtree))
18090 ((eq scope 'tree)
18091 (while (org-up-heading-safe))
18092 (org-narrow-to-subtree))
18093 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
18094 (symbol-name scope)))
18095 (setq level (string-to-number (match-string 1 (symbol-name scope))))
18096 (catch 'exit
18097 (while (org-up-heading-safe)
18098 (looking-at outline-regexp)
18099 (if (<= (org-reduced-level (funcall outline-level)) level)
18100 (throw 'exit nil))))
18101 (org-narrow-to-subtree))
18102 ((or (listp scope) (eq scope 'agenda))
18103 (let* ((files (if (listp scope) scope (org-agenda-files)))
18104 (scope 'agenda)
18105 (p1 (copy-sequence params))
18106 file)
18107 (plist-put p1 :tostring t)
18108 (plist-put p1 :multifile t)
18109 (plist-put p1 :scope 'file)
18110 (org-prepare-agenda-buffers files)
18111 (while (setq file (pop files))
18112 (with-current-buffer (find-buffer-visiting file)
18113 (push (org-clocktable-add-file
18114 file (org-dblock-write:clocktable p1)) tbl)
18115 (setq total-time (+ (or total-time 0)
18116 org-clock-file-total-minutes)))))))
18117 (goto-char pos)
18119 (unless (eq scope 'agenda)
18120 (org-clock-sum ts te)
18121 (goto-char (point-min))
18122 (while (setq p (next-single-property-change (point) :org-clock-minutes))
18123 (goto-char p)
18124 (when (setq time (get-text-property p :org-clock-minutes))
18125 (save-excursion
18126 (beginning-of-line 1)
18127 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
18128 (setq level (org-reduced-level
18129 (- (match-end 1) (match-beginning 1))))
18130 (<= level maxlevel))
18131 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
18132 hdl (match-string 2)
18133 h (/ time 60)
18134 m (- time (* 60 h)))
18135 (if (and (not multifile) (= level 1)) (push "|-" tbl))
18136 (push (concat
18137 "| " (int-to-string level) "|" hlc hdl hlc " |"
18138 (make-string (1- level) ?|)
18139 hlc (format "%d:%02d" h m) hlc
18140 " |") tbl))))))
18141 (setq tbl (nreverse tbl))
18142 (if tostring
18143 (if tbl (mapconcat 'identity tbl "\n") nil)
18144 (goto-char ins)
18145 (insert-before-markers
18146 "Clock summary at ["
18147 (substring
18148 (format-time-string (cdr org-time-stamp-formats))
18149 1 -1)
18150 "]."
18151 (if block
18152 (format " Considered range is /%s/." block)
18154 "\n\n"
18155 (if (eq scope 'agenda) "|File" "")
18156 "|L|Headline|Time|\n")
18157 (setq total-time (or total-time org-clock-file-total-minutes)
18158 h (/ total-time 60)
18159 m (- total-time (* 60 h)))
18160 (insert-before-markers
18161 "|-\n|"
18162 (if (eq scope 'agenda) "|" "")
18164 "*Total time*| "
18165 (format "*%d:%02d*" h m)
18166 "|\n|-\n")
18167 (setq tbl (delq nil tbl))
18168 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
18169 (equal (substring (car tbl) 0 2) "|-"))
18170 (pop tbl))
18171 (insert-before-markers (mapconcat
18172 'identity (delq nil tbl)
18173 (if (eq scope 'agenda) "\n|-\n" "\n")))
18174 (backward-delete-char 1)
18175 (goto-char ipos)
18176 (skip-chars-forward "^|")
18177 (org-table-align)))))
18179 (defun org-clocktable-add-file (file table)
18180 (if table
18181 (let ((lines (org-split-string table "\n"))
18182 (ff (file-name-nondirectory file)))
18183 (mapconcat 'identity
18184 (mapcar (lambda (x)
18185 (if (string-match org-table-dataline-regexp x)
18186 (concat "|" ff x)
18188 lines)
18189 "\n"))))
18191 ;; FIXME: I don't think anybody uses this, ask David
18192 (defun org-collect-clock-time-entries ()
18193 "Return an internal list with clocking information.
18194 This list has one entry for each CLOCK interval.
18195 FIXME: describe the elements."
18196 (interactive)
18197 (let ((re (concat "^[ \t]*" org-clock-string
18198 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
18199 rtn beg end next cont level title total closedp leafp
18200 clockpos titlepos h m donep)
18201 (save-excursion
18202 (org-clock-sum)
18203 (goto-char (point-min))
18204 (while (re-search-forward re nil t)
18205 (setq clockpos (match-beginning 0)
18206 beg (match-string 1) end (match-string 2)
18207 cont (match-end 0))
18208 (setq beg (apply 'encode-time (org-parse-time-string beg))
18209 end (apply 'encode-time (org-parse-time-string end)))
18210 (org-back-to-heading t)
18211 (setq donep (org-entry-is-done-p))
18212 (setq titlepos (point)
18213 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
18214 h (/ total 60) m (- total (* 60 h))
18215 total (cons h m))
18216 (looking-at "\\(\\*+\\) +\\(.*\\)")
18217 (setq level (- (match-end 1) (match-beginning 1))
18218 title (org-match-string-no-properties 2))
18219 (save-excursion (outline-next-heading) (setq next (point)))
18220 (setq closedp (re-search-forward org-closed-time-regexp next t))
18221 (goto-char next)
18222 (setq leafp (and (looking-at "^\\*+ ")
18223 (<= (- (match-end 0) (point)) level)))
18224 (push (list beg end clockpos closedp donep
18225 total title titlepos level leafp)
18226 rtn)
18227 (goto-char cont)))
18228 (nreverse rtn)))
18230 ;;;; Agenda, and Diary Integration
18232 ;;; Define the Org-agenda-mode
18234 (defvar org-agenda-mode-map (make-sparse-keymap)
18235 "Keymap for `org-agenda-mode'.")
18237 (defvar org-agenda-menu) ; defined later in this file.
18238 (defvar org-agenda-follow-mode nil)
18239 (defvar org-agenda-show-log nil)
18240 (defvar org-agenda-redo-command nil)
18241 (defvar org-agenda-mode-hook nil)
18242 (defvar org-agenda-type nil)
18243 (defvar org-agenda-force-single-file nil)
18245 (defun org-agenda-mode ()
18246 "Mode for time-sorted view on action items in Org-mode files.
18248 The following commands are available:
18250 \\{org-agenda-mode-map}"
18251 (interactive)
18252 (kill-all-local-variables)
18253 (setq org-agenda-undo-list nil
18254 org-agenda-pending-undo-list nil)
18255 (setq major-mode 'org-agenda-mode)
18256 ;; Keep global-font-lock-mode from turning on font-lock-mode
18257 (org-set-local 'font-lock-global-modes (list 'not major-mode))
18258 (setq mode-name "Org-Agenda")
18259 (use-local-map org-agenda-mode-map)
18260 (easy-menu-add org-agenda-menu)
18261 (if org-startup-truncated (setq truncate-lines t))
18262 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
18263 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
18264 ;; Make sure properties are removed when copying text
18265 (when (boundp 'buffer-substring-filters)
18266 (org-set-local 'buffer-substring-filters
18267 (cons (lambda (x)
18268 (set-text-properties 0 (length x) nil x) x)
18269 buffer-substring-filters)))
18270 (unless org-agenda-keep-modes
18271 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
18272 org-agenda-show-log nil))
18273 (easy-menu-change
18274 '("Agenda") "Agenda Files"
18275 (append
18276 (list
18277 (vector
18278 (if (get 'org-agenda-files 'org-restrict)
18279 "Restricted to single file"
18280 "Edit File List")
18281 '(org-edit-agenda-file-list)
18282 (not (get 'org-agenda-files 'org-restrict)))
18283 "--")
18284 (mapcar 'org-file-menu-entry (org-agenda-files))))
18285 (org-agenda-set-mode-name)
18286 (apply
18287 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
18288 (list 'org-agenda-mode-hook)))
18290 (substitute-key-definition 'undo 'org-agenda-undo
18291 org-agenda-mode-map global-map)
18292 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
18293 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
18294 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
18295 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
18296 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
18297 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
18298 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
18299 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
18300 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
18301 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
18302 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
18303 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
18304 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
18305 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
18306 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
18307 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
18308 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
18309 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
18310 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
18311 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
18312 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
18313 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
18314 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
18315 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
18316 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
18317 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
18318 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
18319 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
18320 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
18322 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
18323 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
18324 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
18325 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
18326 (while l (org-defkey org-agenda-mode-map
18327 (int-to-string (pop l)) 'digit-argument)))
18329 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
18330 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
18331 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
18332 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
18333 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
18334 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
18335 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
18336 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
18337 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
18338 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
18339 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
18340 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
18341 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
18342 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
18343 (org-defkey org-agenda-mode-map "n" 'next-line)
18344 (org-defkey org-agenda-mode-map "p" 'previous-line)
18345 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
18346 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
18347 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
18348 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
18349 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
18350 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
18351 (eval-after-load "calendar"
18352 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
18353 'org-calendar-goto-agenda))
18354 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
18355 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
18356 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
18357 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
18358 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
18359 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
18360 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
18361 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
18362 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
18363 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
18364 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
18365 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
18366 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
18367 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
18368 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
18369 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
18370 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
18371 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
18372 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
18373 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
18374 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
18375 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
18377 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
18378 "Local keymap for agenda entries from Org-mode.")
18380 (org-defkey org-agenda-keymap
18381 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
18382 (org-defkey org-agenda-keymap
18383 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
18384 (when org-agenda-mouse-1-follows-link
18385 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
18386 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
18387 '("Agenda"
18388 ("Agenda Files")
18389 "--"
18390 ["Show" org-agenda-show t]
18391 ["Go To (other window)" org-agenda-goto t]
18392 ["Go To (this window)" org-agenda-switch-to t]
18393 ["Follow Mode" org-agenda-follow-mode
18394 :style toggle :selected org-agenda-follow-mode :active t]
18395 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
18396 "--"
18397 ["Cycle TODO" org-agenda-todo t]
18398 ["Archive subtree" org-agenda-archive t]
18399 ["Delete subtree" org-agenda-kill t]
18400 "--"
18401 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
18402 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
18403 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
18404 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
18405 "--"
18406 ("Tags and Properties"
18407 ["Show all Tags" org-agenda-show-tags t]
18408 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
18409 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
18410 "--"
18411 ["Column View" org-columns t])
18412 ("Date/Schedule"
18413 ["Schedule" org-agenda-schedule t]
18414 ["Set Deadline" org-agenda-deadline t]
18415 "--"
18416 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
18417 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
18418 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
18419 ("Clock"
18420 ["Clock in" org-agenda-clock-in t]
18421 ["Clock out" org-agenda-clock-out t]
18422 ["Clock cancel" org-agenda-clock-cancel t]
18423 ["Goto running clock" org-clock-goto t])
18424 ("Priority"
18425 ["Set Priority" org-agenda-priority t]
18426 ["Increase Priority" org-agenda-priority-up t]
18427 ["Decrease Priority" org-agenda-priority-down t]
18428 ["Show Priority" org-agenda-show-priority t])
18429 ("Calendar/Diary"
18430 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
18431 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
18432 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
18433 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
18434 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
18435 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
18436 "--"
18437 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
18438 "--"
18439 ("View"
18440 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
18441 :style radio :selected (equal org-agenda-ndays 1)]
18442 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
18443 :style radio :selected (equal org-agenda-ndays 7)]
18444 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
18445 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
18446 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
18447 :style radio :selected (member org-agenda-ndays '(365 366))]
18448 "--"
18449 ["Show Logbook entries" org-agenda-log-mode
18450 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
18451 ["Include Diary" org-agenda-toggle-diary
18452 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
18453 ["Use Time Grid" org-agenda-toggle-time-grid
18454 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
18455 ["Write view to file" org-write-agenda t]
18456 ["Rebuild buffer" org-agenda-redo t]
18457 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
18458 "--"
18459 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
18460 "--"
18461 ["Quit" org-agenda-quit t]
18462 ["Exit and Release Buffers" org-agenda-exit t]
18465 ;;; Agenda undo
18467 (defvar org-agenda-allow-remote-undo t
18468 "Non-nil means, allow remote undo from the agenda buffer.")
18469 (defvar org-agenda-undo-list nil
18470 "List of undoable operations in the agenda since last refresh.")
18471 (defvar org-agenda-undo-has-started-in nil
18472 "Buffers that have already seen `undo-start' in the current undo sequence.")
18473 (defvar org-agenda-pending-undo-list nil
18474 "In a series of undo commands, this is the list of remaning undo items.")
18476 (defmacro org-if-unprotected (&rest body)
18477 "Execute BODY if there is no `org-protected' text property at point."
18478 (declare (debug t))
18479 `(unless (get-text-property (point) 'org-protected)
18480 ,@body))
18482 (defmacro org-with-remote-undo (_buffer &rest _body)
18483 "Execute BODY while recording undo information in two buffers."
18484 (declare (indent 1) (debug t))
18485 `(let ((_cline (org-current-line))
18486 (_cmd this-command)
18487 (_buf1 (current-buffer))
18488 (_buf2 ,_buffer)
18489 (_undo1 buffer-undo-list)
18490 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
18491 _c1 _c2)
18492 ,@_body
18493 (when org-agenda-allow-remote-undo
18494 (setq _c1 (org-verify-change-for-undo
18495 _undo1 (with-current-buffer _buf1 buffer-undo-list))
18496 _c2 (org-verify-change-for-undo
18497 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
18498 (when (or _c1 _c2)
18499 ;; make sure there are undo boundaries
18500 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
18501 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
18502 ;; remember which buffer to undo
18503 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
18504 org-agenda-undo-list)))))
18506 (defun org-agenda-undo ()
18507 "Undo a remote editing step in the agenda.
18508 This undoes changes both in the agenda buffer and in the remote buffer
18509 that have been changed along."
18510 (interactive)
18511 (or org-agenda-allow-remote-undo
18512 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
18513 (if (not (eq this-command last-command))
18514 (setq org-agenda-undo-has-started-in nil
18515 org-agenda-pending-undo-list org-agenda-undo-list))
18516 (if (not org-agenda-pending-undo-list)
18517 (error "No further undo information"))
18518 (let* ((entry (pop org-agenda-pending-undo-list))
18519 buf line cmd rembuf)
18520 (setq cmd (pop entry) line (pop entry))
18521 (setq rembuf (nth 2 entry))
18522 (org-with-remote-undo rembuf
18523 (while (bufferp (setq buf (pop entry)))
18524 (if (pop entry)
18525 (with-current-buffer buf
18526 (let ((last-undo-buffer buf)
18527 (inhibit-read-only t))
18528 (unless (memq buf org-agenda-undo-has-started-in)
18529 (push buf org-agenda-undo-has-started-in)
18530 (make-local-variable 'pending-undo-list)
18531 (undo-start))
18532 (while (and pending-undo-list
18533 (listp pending-undo-list)
18534 (not (car pending-undo-list)))
18535 (pop pending-undo-list))
18536 (undo-more 1))))))
18537 (goto-line line)
18538 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
18540 (defun org-verify-change-for-undo (l1 l2)
18541 "Verify that a real change occurred between the undo lists L1 and L2."
18542 (while (and l1 (listp l1) (null (car l1))) (pop l1))
18543 (while (and l2 (listp l2) (null (car l2))) (pop l2))
18544 (not (eq l1 l2)))
18546 ;;; Agenda dispatch
18548 (defvar org-agenda-restrict nil)
18549 (defvar org-agenda-restrict-begin (make-marker))
18550 (defvar org-agenda-restrict-end (make-marker))
18551 (defvar org-agenda-last-dispatch-buffer nil)
18553 ;;;###autoload
18554 (defun org-agenda (arg &optional keys restriction)
18555 "Dispatch agenda commands to collect entries to the agenda buffer.
18556 Prompts for a command to execute. Any prefix arg will be passed
18557 on to the selected command. The default selections are:
18559 a Call `org-agenda-list' to display the agenda for current day or week.
18560 t Call `org-todo-list' to display the global todo list.
18561 T Call `org-todo-list' to display the global todo list, select only
18562 entries with a specific TODO keyword (the user gets a prompt).
18563 m Call `org-tags-view' to display headlines with tags matching
18564 a condition (the user is prompted for the condition).
18565 M Like `m', but select only TODO entries, no ordinary headlines.
18566 L Create a timeline for the current buffer.
18567 e Export views to associated files.
18569 More commands can be added by configuring the variable
18570 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
18571 searches can be pre-defined in this way.
18573 If the current buffer is in Org-mode and visiting a file, you can also
18574 first press `<' once to indicate that the agenda should be temporarily
18575 \(until the next use of \\[org-agenda]) restricted to the current file.
18576 Pressing `<' twice means to restrict to the current subtree or region
18577 \(if active)."
18578 (interactive "P")
18579 (catch 'exit
18580 (let* ((prefix-descriptions nil)
18581 (org-agenda-custom-commands
18582 ;; normalize different versions
18583 (delq nil
18584 (mapcar
18585 (lambda (x)
18586 (cond ((stringp (cdr x))
18587 (push x prefix-descriptions)
18588 nil)
18589 ((stringp (nth 1 x)) x)
18590 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
18591 (t (cons (car x) (cons "" (cdr x))))))
18592 org-agenda-custom-commands)))
18593 (buf (current-buffer))
18594 (bfn (buffer-file-name (buffer-base-buffer)))
18595 entry key type match lprops ans)
18596 ;; Turn off restriction
18597 (put 'org-agenda-files 'org-restrict nil)
18598 (setq org-agenda-restrict nil)
18599 (move-marker org-agenda-restrict-begin nil)
18600 (move-marker org-agenda-restrict-end nil)
18601 ;; Delete old local properties
18602 (put 'org-agenda-redo-command 'org-lprops nil)
18603 ;; Remember where this call originated
18604 (setq org-agenda-last-dispatch-buffer (current-buffer))
18605 (unless keys
18606 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
18607 keys (car ans)
18608 restriction (cdr ans)))
18609 ;; Estabish the restriction, if any
18610 (when restriction
18611 (put 'org-agenda-files 'org-restrict (list bfn))
18612 (cond
18613 ((eq restriction 'region)
18614 (setq org-agenda-restrict t)
18615 (move-marker org-agenda-restrict-begin (region-beginning))
18616 (move-marker org-agenda-restrict-end (region-end)))
18617 ((eq restriction 'subtree)
18618 (save-excursion
18619 (setq org-agenda-restrict t)
18620 (org-back-to-heading t)
18621 (move-marker org-agenda-restrict-begin (point))
18622 (move-marker org-agenda-restrict-end
18623 (progn (org-end-of-subtree t)))))))
18625 (require 'calendar) ; FIXME: can we avoid this for some commands?
18626 ;; For example the todo list should not need it (but does...)
18627 (cond
18628 ((setq entry (assoc keys org-agenda-custom-commands))
18629 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
18630 (progn
18631 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
18632 (put 'org-agenda-redo-command 'org-lprops lprops)
18633 (cond
18634 ((eq type 'agenda)
18635 (org-let lprops '(org-agenda-list current-prefix-arg)))
18636 ((eq type 'alltodo)
18637 (org-let lprops '(org-todo-list current-prefix-arg)))
18638 ((eq type 'stuck)
18639 (org-let lprops '(org-agenda-list-stuck-projects
18640 current-prefix-arg)))
18641 ((eq type 'tags)
18642 (org-let lprops '(org-tags-view current-prefix-arg match)))
18643 ((eq type 'tags-todo)
18644 (org-let lprops '(org-tags-view '(4) match)))
18645 ((eq type 'todo)
18646 (org-let lprops '(org-todo-list match)))
18647 ((eq type 'tags-tree)
18648 (org-check-for-org-mode)
18649 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
18650 ((eq type 'todo-tree)
18651 (org-check-for-org-mode)
18652 (org-let lprops
18653 '(org-occur (concat "^" outline-regexp "[ \t]*"
18654 (regexp-quote match) "\\>"))))
18655 ((eq type 'occur-tree)
18656 (org-check-for-org-mode)
18657 (org-let lprops '(org-occur match)))
18658 ((functionp type)
18659 (org-let lprops '(funcall type match)))
18660 ((fboundp type)
18661 (org-let lprops '(funcall type match)))
18662 (t (error "Invalid custom agenda command type %s" type))))
18663 (org-run-agenda-series (nth 1 entry) (cddr entry))))
18664 ((equal keys "C") (customize-variable 'org-agenda-custom-commands))
18665 ((equal keys "a") (call-interactively 'org-agenda-list))
18666 ((equal keys "t") (call-interactively 'org-todo-list))
18667 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
18668 ((equal keys "m") (call-interactively 'org-tags-view))
18669 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
18670 ((equal keys "e") (call-interactively 'org-store-agenda-views))
18671 ((equal keys "L")
18672 (unless (org-mode-p)
18673 (error "This is not an Org-mode file"))
18674 (unless restriction
18675 (put 'org-agenda-files 'org-restrict (list bfn))
18676 (org-call-with-arg 'org-timeline arg)))
18677 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
18678 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
18679 ((equal keys "!") (customize-variable 'org-stuck-projects))
18680 (t (error "Invalid agenda key"))))))
18682 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
18683 "The user interface for selecting an agenda command."
18684 (catch 'exit
18685 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
18686 (restrict-ok (and bfn (org-mode-p)))
18687 (region-p (org-region-active-p))
18688 (custom org-agenda-custom-commands)
18689 (selstring "")
18690 restriction second-time
18691 c entry key type match prefixes rmheader header-end custom1 desc)
18692 (save-window-excursion
18693 (delete-other-windows)
18694 (org-switch-to-buffer-other-window " *Agenda Commands*")
18695 (erase-buffer)
18696 (insert (eval-when-compile
18697 (let ((header
18698 "Press key for an agenda command: < Buffer,subtree/region restriction
18699 -------------------------------- C Configure custom agenda commands
18700 a Agenda for current week or day e Export agenda views
18701 t List of all TODO entries T Entries with special TODO kwd
18702 m Match a TAGS query M Like m, but only TODO entries
18703 L Timeline for current buffer # List stuck projects (!=configure)
18704 / Multi-occur
18706 (start 0))
18707 (while (string-match
18708 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
18709 header start)
18710 (setq start (match-end 0))
18711 (add-text-properties (match-beginning 2) (match-end 2)
18712 '(face bold) header))
18713 header)))
18714 (setq header-end (move-marker (make-marker) (point)))
18715 (while t
18716 (setq custom1 custom)
18717 (when (eq rmheader t)
18718 (goto-line 1)
18719 (re-search-forward ":" nil t)
18720 (delete-region (match-end 0) (point-at-eol))
18721 (forward-char 1)
18722 (looking-at "-+")
18723 (delete-region (match-end 0) (point-at-eol))
18724 (move-marker header-end (match-end 0)))
18725 (goto-char header-end)
18726 (delete-region (point) (point-max))
18727 (while (setq entry (pop custom1))
18728 (setq key (car entry) desc (nth 1 entry)
18729 type (nth 2 entry) match (nth 3 entry))
18730 (if (> (length key) 1)
18731 (add-to-list 'prefixes (string-to-char key))
18732 (insert
18733 (format
18734 "\n%-4s%-14s: %s"
18735 (org-add-props (copy-sequence key)
18736 '(face bold))
18737 (cond
18738 ((string-match "\\S-" desc) desc)
18739 ((eq type 'agenda) "Agenda for current week or day")
18740 ((eq type 'alltodo) "List of all TODO entries")
18741 ((eq type 'stuck) "List of stuck projects")
18742 ((eq type 'todo) "TODO keyword")
18743 ((eq type 'tags) "Tags query")
18744 ((eq type 'tags-todo) "Tags (TODO)")
18745 ((eq type 'tags-tree) "Tags tree")
18746 ((eq type 'todo-tree) "TODO kwd tree")
18747 ((eq type 'occur-tree) "Occur tree")
18748 ((functionp type) (if (symbolp type)
18749 (symbol-name type)
18750 "Lambda expression"))
18751 (t "???"))
18752 (cond
18753 ((stringp match)
18754 (org-add-props match nil 'face 'org-warning))
18755 (match
18756 (format "set of %d commands" (length match)))
18757 (t ""))))))
18758 (when prefixes
18759 (mapc (lambda (x)
18760 (insert
18761 (format "\n%s %s"
18762 (org-add-props (char-to-string x)
18763 nil 'face 'bold)
18764 (or (cdr (assoc (concat selstring (char-to-string x))
18765 prefix-descriptions))
18766 "Prefix key"))))
18767 prefixes))
18768 (goto-char (point-min))
18769 (when (fboundp 'fit-window-to-buffer)
18770 (if second-time
18771 (if (not (pos-visible-in-window-p (point-max)))
18772 (fit-window-to-buffer))
18773 (setq second-time t)
18774 (fit-window-to-buffer)))
18775 (message "Press key for agenda command%s:"
18776 (if restrict-ok
18777 (if restriction
18778 (format " (restricted to %s)" restriction)
18779 " (unrestricted)")
18780 ""))
18781 (setq c (read-char-exclusive))
18782 (message "")
18783 (cond
18784 ((assoc (char-to-string c) custom)
18785 (setq selstring (concat selstring (char-to-string c)))
18786 (throw 'exit (cons selstring restriction)))
18787 ((memq c prefixes)
18788 (setq selstring (concat selstring (char-to-string c))
18789 prefixes nil
18790 rmheader (or rmheader t)
18791 custom (delq nil (mapcar
18792 (lambda (x)
18793 (if (or (= (length (car x)) 1)
18794 (/= (string-to-char (car x)) c))
18796 (cons (substring (car x) 1) (cdr x))))
18797 custom))))
18798 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
18799 (message "Restriction is only possible in Org-mode buffers")
18800 (ding) (sit-for 1))
18801 ((eq c ?1)
18802 (setq restriction 'buffer))
18803 ((eq c ?0)
18804 (setq restriction (if region-p 'region 'subtree)))
18805 ((eq c ?<)
18806 (setq restriction
18807 (cond
18808 ((eq restriction 'buffer)
18809 (if region-p 'region 'subtree))
18810 ((memq restriction '(subtree region))
18811 nil)
18812 (t 'buffer))))
18813 ((and (equal selstring "") (memq c '(?a ?t ?m ?L ?C ?e ?T ?M ?# ?/)))
18814 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
18815 ((equal c ?q) (error "Abort"))
18816 (t (error "Invalid key %c" c))))))))
18818 (defun org-run-agenda-series (name series)
18819 (org-prepare-agenda name)
18820 (let* ((org-agenda-multi t)
18821 (redo (list 'org-run-agenda-series name (list 'quote series)))
18822 (cmds (car series))
18823 (gprops (nth 1 series))
18824 match ;; The byte compiler incorrectly complains about this. Keep it!
18825 cmd type lprops)
18826 (while (setq cmd (pop cmds))
18827 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
18828 (cond
18829 ((eq type 'agenda)
18830 (org-let2 gprops lprops
18831 '(call-interactively 'org-agenda-list)))
18832 ((eq type 'alltodo)
18833 (org-let2 gprops lprops
18834 '(call-interactively 'org-todo-list)))
18835 ((eq type 'stuck)
18836 (org-let2 gprops lprops
18837 '(call-interactively 'org-agenda-list-stuck-projects)))
18838 ((eq type 'tags)
18839 (org-let2 gprops lprops
18840 '(org-tags-view current-prefix-arg match)))
18841 ((eq type 'tags-todo)
18842 (org-let2 gprops lprops
18843 '(org-tags-view '(4) match)))
18844 ((eq type 'todo)
18845 (org-let2 gprops lprops
18846 '(org-todo-list match)))
18847 ((fboundp type)
18848 (org-let2 gprops lprops
18849 '(funcall type match)))
18850 (t (error "Invalid type in command series"))))
18851 (widen)
18852 (setq org-agenda-redo-command redo)
18853 (goto-char (point-min)))
18854 (org-finalize-agenda))
18856 ;;;###autoload
18857 (defmacro org-batch-agenda (cmd-key &rest parameters)
18858 "Run an agenda command in batch mode and send the result to STDOUT.
18859 If CMD-KEY is a string of length 1, it is used as a key in
18860 `org-agenda-custom-commands' and triggers this command. If it is a
18861 longer string is is used as a tags/todo match string.
18862 Paramters are alternating variable names and values that will be bound
18863 before running the agenda command."
18864 (let (pars)
18865 (while parameters
18866 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18867 (if (> (length cmd-key) 2)
18868 (eval (list 'let (nreverse pars)
18869 (list 'org-tags-view nil cmd-key)))
18870 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18871 (set-buffer org-agenda-buffer-name)
18872 (princ (org-encode-for-stdout (buffer-string)))))
18874 (defun org-encode-for-stdout (string)
18875 (if (fboundp 'encode-coding-string)
18876 (encode-coding-string string buffer-file-coding-system)
18877 string))
18879 (defvar org-agenda-info nil)
18881 ;;;###autoload
18882 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
18883 "Run an agenda command in batch mode and send the result to STDOUT.
18884 If CMD-KEY is a string of length 1, it is used as a key in
18885 `org-agenda-custom-commands' and triggers this command. If it is a
18886 longer string is is used as a tags/todo match string.
18887 Paramters are alternating variable names and values that will be bound
18888 before running the agenda command.
18890 The output gives a line for each selected agenda item. Each
18891 item is a list of comma-separated values, like this:
18893 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
18895 category The category of the item
18896 head The headline, without TODO kwd, TAGS and PRIORITY
18897 type The type of the agenda entry, can be
18898 todo selected in TODO match
18899 tagsmatch selected in tags match
18900 diary imported from diary
18901 deadline a deadline on given date
18902 scheduled scheduled on given date
18903 timestamp entry has timestamp on given date
18904 closed entry was closed on given date
18905 upcoming-deadline warning about deadline
18906 past-scheduled forwarded scheduled item
18907 block entry has date block including g. date
18908 todo The todo keyword, if any
18909 tags All tags including inherited ones, separated by colons
18910 date The relevant date, like 2007-2-14
18911 time The time, like 15:00-16:50
18912 extra Sting with extra planning info
18913 priority-l The priority letter if any was given
18914 priority-n The computed numerical priority
18915 agenda-day The day in the agenda where this is listed"
18917 (let (pars)
18918 (while parameters
18919 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18920 (push (list 'org-agenda-remove-tags t) pars)
18921 (if (> (length cmd-key) 2)
18922 (eval (list 'let (nreverse pars)
18923 (list 'org-tags-view nil cmd-key)))
18924 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
18925 (set-buffer org-agenda-buffer-name)
18926 (let* ((lines (org-split-string (buffer-string) "\n"))
18927 line)
18928 (while (setq line (pop lines))
18929 (catch 'next
18930 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
18931 (setq org-agenda-info
18932 (org-fix-agenda-info (text-properties-at 0 line)))
18933 (princ
18934 (org-encode-for-stdout
18935 (mapconcat 'org-agenda-export-csv-mapper
18936 '(org-category txt type todo tags date time-of-day extra
18937 priority-letter priority agenda-day)
18938 ",")))
18939 (princ "\n"))))))
18941 (defun org-fix-agenda-info (props)
18942 "Make sure all properties on an agenda item have a canonical form,
18943 so the the export commands caneasily use it."
18944 (let (tmp re)
18945 (when (setq tmp (plist-get props 'tags))
18946 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
18947 (when (setq tmp (plist-get props 'date))
18948 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18949 (let ((calendar-date-display-form '(year "-" month "-" day)))
18950 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
18952 (setq tmp (calendar-date-string tmp)))
18953 (setq props (plist-put props 'date tmp)))
18954 (when (setq tmp (plist-get props 'day))
18955 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
18956 (let ((calendar-date-display-form '(year "-" month "-" day)))
18957 (setq tmp (calendar-date-string tmp)))
18958 (setq props (plist-put props 'day tmp))
18959 (setq props (plist-put props 'agenda-day tmp)))
18960 (when (setq tmp (plist-get props 'txt))
18961 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
18962 (plist-put props 'priority-letter (match-string 1 tmp))
18963 (setq tmp (replace-match "" t t tmp)))
18964 (when (and (setq re (plist-get props 'org-todo-regexp))
18965 (setq re (concat "\\`\\.*" re " ?"))
18966 (string-match re tmp))
18967 (plist-put props 'todo (match-string 1 tmp))
18968 (setq tmp (replace-match "" t t tmp)))
18969 (plist-put props 'txt tmp)))
18970 props)
18972 (defun org-agenda-export-csv-mapper (prop)
18973 (let ((res (plist-get org-agenda-info prop)))
18974 (setq res
18975 (cond
18976 ((not res) "")
18977 ((stringp res) res)
18978 (t (prin1-to-string res))))
18979 (while (string-match "," res)
18980 (setq res (replace-match ";" t t res)))
18981 (org-trim res)))
18984 ;;;###autoload
18985 (defun org-store-agenda-views (&rest parameters)
18986 (interactive)
18987 (eval (list 'org-batch-store-agenda-views)))
18989 ;; FIXME, why is this a macro?????
18990 ;;;###autoload
18991 (defmacro org-batch-store-agenda-views (&rest parameters)
18992 "Run all custom agenda commands that have a file argument."
18993 (let ((cmds org-agenda-custom-commands)
18994 (pop-up-frames nil)
18995 (dir default-directory)
18996 pars cmd thiscmdkey files opts)
18997 (while parameters
18998 (push (list (pop parameters) (if parameters (pop parameters))) pars))
18999 (setq pars (reverse pars))
19000 (save-window-excursion
19001 (while cmds
19002 (setq cmd (pop cmds)
19003 thiscmdkey (car cmd)
19004 opts (nth 3 cmd)
19005 files (nth 4 cmd))
19006 (if (stringp files) (setq files (list files)))
19007 (when files
19008 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19009 (list 'org-agenda nil thiscmdkey)))
19010 (set-buffer org-agenda-buffer-name)
19011 (while files
19012 (eval (list 'let (append org-agenda-exporter-settings opts pars)
19013 (list 'org-write-agenda
19014 (expand-file-name (pop files) dir) t))))
19015 (and (get-buffer org-agenda-buffer-name)
19016 (kill-buffer org-agenda-buffer-name)))))))
19018 (defun org-write-agenda (file &optional nosettings)
19019 "Write the current buffer (an agenda view) as a file.
19020 Depending on the extension of the file name, plain text (.txt),
19021 HTML (.html or .htm) or Postscript (.ps) is produced.
19022 If NOSETTINGS is given, do not scope the settings of
19023 `org-agenda-exporter-settings' into the export commands. This is used when
19024 the settings have already been scoped and we do not wish to overrule other,
19025 higher priority settings."
19026 (interactive "FWrite agenda to file: ")
19027 (if (not (file-writable-p file))
19028 (error "Cannot write agenda to file %s" file))
19029 (cond
19030 ((string-match "\\.html?\\'" file) (require 'htmlize))
19031 ((string-match "\\.ps\\'" file) (require 'ps-print)))
19032 (org-let (if nosettings nil org-agenda-exporter-settings)
19033 '(save-excursion
19034 (save-window-excursion
19035 (cond
19036 ((string-match "\\.html?\\'" file)
19037 (set-buffer (htmlize-buffer (current-buffer)))
19039 (when (and org-agenda-export-html-style
19040 (string-match "<style>" org-agenda-export-html-style))
19041 ;; replace <style> section with org-agenda-export-html-style
19042 (goto-char (point-min))
19043 (kill-region (- (search-forward "<style") 6)
19044 (search-forward "</style>"))
19045 (insert org-agenda-export-html-style))
19046 (write-file file)
19047 (kill-buffer (current-buffer))
19048 (message "HTML written to %s" file))
19049 ((string-match "\\.ps\\'" file)
19050 (ps-print-buffer-with-faces file)
19051 (message "Postscript written to %s" file))
19053 (let ((bs (buffer-string)))
19054 (find-file file)
19055 (insert bs)
19056 (save-buffer 0)
19057 (kill-buffer (current-buffer))
19058 (message "Plain text written to %s" file))))))
19059 (set-buffer org-agenda-buffer-name)))
19061 (defmacro org-no-read-only (&rest body)
19062 "Inhibit read-only for BODY."
19063 `(let ((inhibit-read-only t)) ,@body))
19065 (defun org-check-for-org-mode ()
19066 "Make sure current buffer is in org-mode. Error if not."
19067 (or (org-mode-p)
19068 (error "Cannot execute org-mode agenda command on buffer in %s."
19069 major-mode)))
19071 (defun org-fit-agenda-window ()
19072 "Fit the window to the buffer size."
19073 (and (memq org-agenda-window-setup '(reorganize-frame))
19074 (fboundp 'fit-window-to-buffer)
19075 (fit-window-to-buffer
19077 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
19078 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
19080 ;;; Agenda file list
19082 (defun org-agenda-files (&optional unrestricted)
19083 "Get the list of agenda files.
19084 Optional UNRESTRICTED means return the full list even if a restriction
19085 is currently in place."
19086 (let ((files
19087 (cond
19088 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
19089 ((stringp org-agenda-files) (org-read-agenda-file-list))
19090 ((listp org-agenda-files) org-agenda-files)
19091 (t (error "Invalid value of `org-agenda-files'")))))
19092 (setq files (apply 'append
19093 (mapcar (lambda (f)
19094 (if (file-directory-p f)
19095 (directory-files f t "\\.org\\'")
19096 (list f)))
19097 files)))
19098 (if org-agenda-skip-unavailable-files
19099 (delq nil
19100 (mapcar (function
19101 (lambda (file)
19102 (and (file-readable-p file) file)))
19103 files))
19104 files))) ; `org-check-agenda-file' will remove them from the list
19106 (defun org-edit-agenda-file-list ()
19107 "Edit the list of agenda files.
19108 Depending on setup, this either uses customize to edit the variable
19109 `org-agenda-files', or it visits the file that is holding the list. In the
19110 latter case, the buffer is set up in a way that saving it automatically kills
19111 the buffer and restores the previous window configuration."
19112 (interactive)
19113 (if (stringp org-agenda-files)
19114 (let ((cw (current-window-configuration)))
19115 (find-file org-agenda-files)
19116 (org-set-local 'org-window-configuration cw)
19117 (org-add-hook 'after-save-hook
19118 (lambda ()
19119 (set-window-configuration
19120 (prog1 org-window-configuration
19121 (kill-buffer (current-buffer))))
19122 (org-install-agenda-files-menu)
19123 (message "New agenda file list installed"))
19124 nil 'local)
19125 (message (substitute-command-keys
19126 "Edit list and finish with \\[save-buffer]")))
19127 (customize-variable 'org-agenda-files)))
19129 (defun org-store-new-agenda-file-list (list)
19130 "Set new value for the agenda file list and save it correcly."
19131 (if (stringp org-agenda-files)
19132 (let ((f org-agenda-files) b)
19133 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
19134 (with-temp-file f
19135 (insert (mapconcat 'identity list "\n") "\n")))
19136 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
19137 (setq org-agenda-files list)
19138 (customize-save-variable 'org-agenda-files org-agenda-files))))
19140 (defun org-read-agenda-file-list ()
19141 "Read the list of agenda files from a file."
19142 (when (stringp org-agenda-files)
19143 (with-temp-buffer
19144 (insert-file-contents org-agenda-files)
19145 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
19148 ;;;###autoload
19149 (defun org-cycle-agenda-files ()
19150 "Cycle through the files in `org-agenda-files'.
19151 If the current buffer visits an agenda file, find the next one in the list.
19152 If the current buffer does not, find the first agenda file."
19153 (interactive)
19154 (let* ((fs (org-agenda-files t))
19155 (files (append fs (list (car fs))))
19156 (tcf (if buffer-file-name (file-truename buffer-file-name)))
19157 file)
19158 (unless files (error "No agenda files"))
19159 (catch 'exit
19160 (while (setq file (pop files))
19161 (if (equal (file-truename file) tcf)
19162 (when (car files)
19163 (find-file (car files))
19164 (throw 'exit t))))
19165 (find-file (car fs)))
19166 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
19168 (defun org-agenda-file-to-front (&optional to-end)
19169 "Move/add the current file to the top of the agenda file list.
19170 If the file is not present in the list, it is added to the front. If it is
19171 present, it is moved there. With optional argument TO-END, add/move to the
19172 end of the list."
19173 (interactive "P")
19174 (let ((org-agenda-skip-unavailable-files nil)
19175 (file-alist (mapcar (lambda (x)
19176 (cons (file-truename x) x))
19177 (org-agenda-files t)))
19178 (ctf (file-truename buffer-file-name))
19179 x had)
19180 (setq x (assoc ctf file-alist) had x)
19182 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
19183 (if to-end
19184 (setq file-alist (append (delq x file-alist) (list x)))
19185 (setq file-alist (cons x (delq x file-alist))))
19186 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
19187 (org-install-agenda-files-menu)
19188 (message "File %s to %s of agenda file list"
19189 (if had "moved" "added") (if to-end "end" "front"))))
19191 (defun org-remove-file (&optional file)
19192 "Remove current file from the list of files in variable `org-agenda-files'.
19193 These are the files which are being checked for agenda entries.
19194 Optional argument FILE means, use this file instead of the current."
19195 (interactive)
19196 (let* ((org-agenda-skip-unavailable-files nil)
19197 (file (or file buffer-file-name))
19198 (true-file (file-truename file))
19199 (afile (abbreviate-file-name file))
19200 (files (delq nil (mapcar
19201 (lambda (x)
19202 (if (equal true-file
19203 (file-truename x))
19204 nil x))
19205 (org-agenda-files t)))))
19206 (if (not (= (length files) (length (org-agenda-files t))))
19207 (progn
19208 (org-store-new-agenda-file-list files)
19209 (org-install-agenda-files-menu)
19210 (message "Removed file: %s" afile))
19211 (message "File was not in list: %s" afile))))
19213 (defun org-file-menu-entry (file)
19214 (vector file (list 'find-file file) t))
19216 (defun org-check-agenda-file (file)
19217 "Make sure FILE exists. If not, ask user what to do."
19218 (when (not (file-exists-p file))
19219 (message "non-existent file %s. [R]emove from list or [A]bort?"
19220 (abbreviate-file-name file))
19221 (let ((r (downcase (read-char-exclusive))))
19222 (cond
19223 ((equal r ?r)
19224 (org-remove-file file)
19225 (throw 'nextfile t))
19226 (t (error "Abort"))))))
19228 ;;; Agenda prepare and finalize
19230 (defvar org-agenda-multi nil) ; dynammically scoped
19231 (defvar org-agenda-buffer-name "*Org Agenda*")
19232 (defvar org-pre-agenda-window-conf nil)
19233 (defvar org-agenda-name nil)
19234 (defun org-prepare-agenda (&optional name)
19235 (setq org-todo-keywords-for-agenda nil)
19236 (setq org-done-keywords-for-agenda nil)
19237 (if org-agenda-multi
19238 (progn
19239 (setq buffer-read-only nil)
19240 (goto-char (point-max))
19241 (unless (or (bobp) org-agenda-compact-blocks)
19242 (insert "\n" (make-string (window-width) ?=) "\n"))
19243 (narrow-to-region (point) (point-max)))
19244 (org-agenda-maybe-reset-markers 'force)
19245 (org-prepare-agenda-buffers (org-agenda-files))
19246 (setq org-todo-keywords-for-agenda
19247 (org-uniquify org-todo-keywords-for-agenda))
19248 (setq org-done-keywords-for-agenda
19249 (org-uniquify org-done-keywords-for-agenda))
19250 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
19251 (awin (get-buffer-window abuf)))
19252 (cond
19253 ((equal (current-buffer) abuf) nil)
19254 (awin (select-window awin))
19255 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
19256 ((equal org-agenda-window-setup 'current-window)
19257 (switch-to-buffer abuf))
19258 ((equal org-agenda-window-setup 'other-window)
19259 (org-switch-to-buffer-other-window abuf))
19260 ((equal org-agenda-window-setup 'other-frame)
19261 (switch-to-buffer-other-frame abuf))
19262 ((equal org-agenda-window-setup 'reorganize-frame)
19263 (delete-other-windows)
19264 (org-switch-to-buffer-other-window abuf))))
19265 (setq buffer-read-only nil)
19266 (erase-buffer)
19267 (org-agenda-mode)
19268 (and name (not org-agenda-name)
19269 (org-set-local 'org-agenda-name name)))
19270 (setq buffer-read-only nil))
19272 (defun org-finalize-agenda ()
19273 "Finishing touch for the agenda buffer, called just before displaying it."
19274 (unless org-agenda-multi
19275 (save-excursion
19276 (let ((inhibit-read-only t))
19277 (goto-char (point-min))
19278 (while (org-activate-bracket-links (point-max))
19279 (add-text-properties (match-beginning 0) (match-end 0)
19280 '(face org-link)))
19281 (org-agenda-align-tags)
19282 (unless org-agenda-with-colors
19283 (remove-text-properties (point-min) (point-max) '(face nil))))
19284 (if (and (boundp 'org-overriding-columns-format)
19285 org-overriding-columns-format)
19286 (org-set-local 'org-overriding-columns-format
19287 org-overriding-columns-format))
19288 (if (and (boundp 'org-agenda-view-columns-initially)
19289 org-agenda-view-columns-initially)
19290 (org-agenda-columns))
19291 (when org-agenda-fontify-priorities
19292 (org-fontify-priorities))
19293 (run-hooks 'org-finalize-agenda-hook))))
19295 (defun org-fontify-priorities ()
19296 "Make highest priority lines bold, and lowest italic."
19297 (interactive)
19298 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
19299 (org-delete-overlay o)))
19300 (org-overlays-in (point-min) (point-max)))
19301 (save-excursion
19302 (let ((inhibit-read-only t)
19303 b e p ov h l)
19304 (goto-char (point-min))
19305 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
19306 (setq h (or (get-char-property (point) 'org-highest-priority)
19307 org-highest-priority)
19308 l (or (get-char-property (point) 'org-lowest-priority)
19309 org-lowest-priority)
19310 p (string-to-char (match-string 1))
19311 b (match-beginning 0) e (point-at-eol)
19312 ov (org-make-overlay b e))
19313 (org-overlay-put
19314 ov 'face
19315 (cond ((listp org-agenda-fontify-priorities)
19316 (cdr (assoc p org-agenda-fontify-priorities)))
19317 ((equal p l) 'italic)
19318 ((equal p h) 'bold)))
19319 (org-overlay-put ov 'org-type 'org-priority)))))
19321 (defun org-prepare-agenda-buffers (files)
19322 "Create buffers for all agenda files, protect archived trees and comments."
19323 (interactive)
19324 (let ((pa '(:org-archived t))
19325 (pc '(:org-comment t))
19326 (pall '(:org-archived t :org-comment t))
19327 (inhibit-read-only t)
19328 (rea (concat ":" org-archive-tag ":"))
19329 bmp file re)
19330 (save-excursion
19331 (save-restriction
19332 (while (setq file (pop files))
19333 (if (bufferp file)
19334 (set-buffer file)
19335 (org-check-agenda-file file)
19336 (set-buffer (org-get-agenda-file-buffer file)))
19337 (widen)
19338 (setq bmp (buffer-modified-p))
19339 (org-refresh-category-properties)
19340 (setq org-todo-keywords-for-agenda
19341 (append org-todo-keywords-for-agenda org-todo-keywords-1))
19342 (setq org-done-keywords-for-agenda
19343 (append org-done-keywords-for-agenda org-done-keywords))
19344 (save-excursion
19345 (remove-text-properties (point-min) (point-max) pall)
19346 (when org-agenda-skip-archived-trees
19347 (goto-char (point-min))
19348 (while (re-search-forward rea nil t)
19349 (if (org-on-heading-p t)
19350 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
19351 (goto-char (point-min))
19352 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
19353 (while (re-search-forward re nil t)
19354 (add-text-properties
19355 (match-beginning 0) (org-end-of-subtree t) pc)))
19356 (set-buffer-modified-p bmp))))))
19358 (defvar org-agenda-skip-function nil
19359 "Function to be called at each match during agenda construction.
19360 If this function returns nil, the current match should not be skipped.
19361 Otherwise, the function must return a position from where the search
19362 should be continued.
19363 This may also be a Lisp form, it will be evaluated.
19364 Never set this variable using `setq' or so, because then it will apply
19365 to all future agenda commands. Instead, bind it with `let' to scope
19366 it dynamically into the agenda-constructing command. A good way to set
19367 it is through options in org-agenda-custom-commands.")
19369 (defun org-agenda-skip ()
19370 "Throw to `:skip' in places that should be skipped.
19371 Also moves point to the end of the skipped region, so that search can
19372 continue from there."
19373 (let ((p (point-at-bol)) to fp)
19374 (and org-agenda-skip-archived-trees
19375 (get-text-property p :org-archived)
19376 (org-end-of-subtree t)
19377 (throw :skip t))
19378 (and (get-text-property p :org-comment)
19379 (org-end-of-subtree t)
19380 (throw :skip t))
19381 (if (equal (char-after p) ?#) (throw :skip t))
19382 (when (and (or (setq fp (functionp org-agenda-skip-function))
19383 (consp org-agenda-skip-function))
19384 (setq to (save-excursion
19385 (save-match-data
19386 (if fp
19387 (funcall org-agenda-skip-function)
19388 (eval org-agenda-skip-function))))))
19389 (goto-char to)
19390 (throw :skip t))))
19392 (defvar org-agenda-markers nil
19393 "List of all currently active markers created by `org-agenda'.")
19394 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
19395 "Creation time of the last agenda marker.")
19397 (defun org-agenda-new-marker (&optional pos)
19398 "Return a new agenda marker.
19399 Org-mode keeps a list of these markers and resets them when they are
19400 no longer in use."
19401 (let ((m (copy-marker (or pos (point)))))
19402 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
19403 (push m org-agenda-markers)
19406 (defun org-agenda-maybe-reset-markers (&optional force)
19407 "Reset markers created by `org-agenda'. But only if they are old enough."
19408 (if (or (and force (not org-agenda-multi))
19409 (> (- (time-to-seconds (current-time))
19410 org-agenda-last-marker-time)
19412 (while org-agenda-markers
19413 (move-marker (pop org-agenda-markers) nil))))
19415 (defvar org-agenda-new-buffers nil
19416 "Buffers created to visit agenda files.")
19418 (defun org-get-agenda-file-buffer (file)
19419 "Get a buffer visiting FILE. If the buffer needs to be created, add
19420 it to the list of buffers which might be released later."
19421 (let ((buf (org-find-base-buffer-visiting file)))
19422 (if buf
19423 buf ; just return it
19424 ;; Make a new buffer and remember it
19425 (setq buf (find-file-noselect file))
19426 (if buf (push buf org-agenda-new-buffers))
19427 buf)))
19429 (defun org-release-buffers (blist)
19430 "Release all buffers in list, asking the user for confirmation when needed.
19431 When a buffer is unmodified, it is just killed. When modified, it is saved
19432 \(if the user agrees) and then killed."
19433 (let (buf file)
19434 (while (setq buf (pop blist))
19435 (setq file (buffer-file-name buf))
19436 (when (and (buffer-modified-p buf)
19437 file
19438 (y-or-n-p (format "Save file %s? " file)))
19439 (with-current-buffer buf (save-buffer)))
19440 (kill-buffer buf))))
19442 (defun org-get-category (&optional pos)
19443 "Get the category applying to position POS."
19444 (get-text-property (or pos (point)) 'org-category))
19446 ;;; Agenda timeline
19448 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
19450 (defun org-timeline (&optional include-all)
19451 "Show a time-sorted view of the entries in the current org file.
19452 Only entries with a time stamp of today or later will be listed. With
19453 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
19454 under the current date.
19455 If the buffer contains an active region, only check the region for
19456 dates."
19457 (interactive "P")
19458 (require 'calendar)
19459 (org-compile-prefix-format 'timeline)
19460 (org-set-sorting-strategy 'timeline)
19461 (let* ((dopast t)
19462 (dotodo include-all)
19463 (doclosed org-agenda-show-log)
19464 (entry buffer-file-name)
19465 (date (calendar-current-date))
19466 (beg (if (org-region-active-p) (region-beginning) (point-min)))
19467 (end (if (org-region-active-p) (region-end) (point-max)))
19468 (day-numbers (org-get-all-dates beg end 'no-ranges
19469 t doclosed ; always include today
19470 org-timeline-show-empty-dates))
19471 (org-deadline-warning-days 0)
19472 (org-agenda-only-exact-dates t)
19473 (today (time-to-days (current-time)))
19474 (past t)
19475 args
19476 s e rtn d emptyp)
19477 (setq org-agenda-redo-command
19478 (list 'progn
19479 (list 'org-switch-to-buffer-other-window (current-buffer))
19480 (list 'org-timeline (list 'quote include-all))))
19481 (if (not dopast)
19482 ;; Remove past dates from the list of dates.
19483 (setq day-numbers (delq nil (mapcar (lambda(x)
19484 (if (>= x today) x nil))
19485 day-numbers))))
19486 (org-prepare-agenda (concat "Timeline "
19487 (file-name-nondirectory buffer-file-name)))
19488 (if doclosed (push :closed args))
19489 (push :timestamp args)
19490 (push :deadline args)
19491 (push :scheduled args)
19492 (push :sexp args)
19493 (if dotodo (push :todo args))
19494 (while (setq d (pop day-numbers))
19495 (if (and (listp d) (eq (car d) :omitted))
19496 (progn
19497 (setq s (point))
19498 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
19499 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
19500 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
19501 (if (and (>= d today)
19502 dopast
19503 past)
19504 (progn
19505 (setq past nil)
19506 (insert (make-string 79 ?-) "\n")))
19507 (setq date (calendar-gregorian-from-absolute d))
19508 (setq s (point))
19509 (setq rtn (and (not emptyp)
19510 (apply 'org-agenda-get-day-entries entry
19511 date args)))
19512 (if (or rtn (equal d today) org-timeline-show-empty-dates)
19513 (progn
19514 (insert
19515 (if (stringp org-agenda-format-date)
19516 (format-time-string org-agenda-format-date
19517 (org-time-from-absolute date))
19518 (funcall org-agenda-format-date date))
19519 "\n")
19520 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19521 (put-text-property s (1- (point)) 'org-date-line t)
19522 (if (equal d today)
19523 (put-text-property s (1- (point)) 'org-today t))
19524 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
19525 (put-text-property s (1- (point)) 'day d)))))
19526 (goto-char (point-min))
19527 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
19528 (point-min)))
19529 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
19530 (org-finalize-agenda)
19531 (setq buffer-read-only t)))
19533 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
19534 "Return a list of all relevant day numbers from BEG to END buffer positions.
19535 If NO-RANGES is non-nil, include only the start and end dates of a range,
19536 not every single day in the range. If FORCE-TODAY is non-nil, make
19537 sure that TODAY is included in the list. If INACTIVE is non-nil, also
19538 inactive time stamps (those in square brackets) are included.
19539 When EMPTY is non-nil, also include days without any entries."
19540 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
19541 dates dates1 date day day1 day2 ts1 ts2)
19542 (if force-today
19543 (setq dates (list (time-to-days (current-time)))))
19544 (save-excursion
19545 (goto-char beg)
19546 (while (re-search-forward re end t)
19547 (setq day (time-to-days (org-time-string-to-time
19548 (substring (match-string 1) 0 10))))
19549 (or (memq day dates) (push day dates)))
19550 (unless no-ranges
19551 (goto-char beg)
19552 (while (re-search-forward org-tr-regexp end t)
19553 (setq ts1 (substring (match-string 1) 0 10)
19554 ts2 (substring (match-string 2) 0 10)
19555 day1 (time-to-days (org-time-string-to-time ts1))
19556 day2 (time-to-days (org-time-string-to-time ts2)))
19557 (while (< (setq day1 (1+ day1)) day2)
19558 (or (memq day1 dates) (push day1 dates)))))
19559 (setq dates (sort dates '<))
19560 (when empty
19561 (while (setq day (pop dates))
19562 (setq day2 (car dates))
19563 (push day dates1)
19564 (when (and day2 empty)
19565 (if (or (eq empty t)
19566 (and (numberp empty) (<= (- day2 day) empty)))
19567 (while (< (setq day (1+ day)) day2)
19568 (push (list day) dates1))
19569 (push (cons :omitted (- day2 day)) dates1))))
19570 (setq dates (nreverse dates1)))
19571 dates)))
19573 ;;; Agenda Daily/Weekly
19575 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
19576 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
19577 (defvar org-agenda-last-arguments nil
19578 "The arguments of the previous call to org-agenda")
19579 (defvar org-starting-day nil) ; local variable in the agenda buffer
19580 (defvar org-agenda-span nil) ; local variable in the agenda buffer
19581 (defvar org-include-all-loc nil) ; local variable
19582 (defvar org-agenda-remove-date nil) ; dynamically scoped
19584 ;;;###autoload
19585 (defun org-agenda-list (&optional include-all start-day ndays)
19586 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
19587 The view will be for the current day or week, but from the overview buffer
19588 you will be able to go to other days/weeks.
19590 With one \\[universal-argument] prefix argument INCLUDE-ALL,
19591 all unfinished TODO items will also be shown, before the agenda.
19592 This feature is considered obsolete, please use the TODO list or a block
19593 agenda instead.
19595 With a numeric prefix argument in an interactive call, the agenda will
19596 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
19597 the number of days. NDAYS defaults to `org-agenda-ndays'.
19599 START-DAY defaults to TODAY, or to the most recent match for the weekday
19600 given in `org-agenda-start-on-weekday'."
19601 (interactive "P")
19602 (if (and (integerp include-all) (> include-all 0))
19603 (setq ndays include-all include-all nil))
19604 (setq ndays (or ndays org-agenda-ndays)
19605 start-day (or start-day org-agenda-start-day))
19606 (if org-agenda-overriding-arguments
19607 (setq include-all (car org-agenda-overriding-arguments)
19608 start-day (nth 1 org-agenda-overriding-arguments)
19609 ndays (nth 2 org-agenda-overriding-arguments)))
19610 (if (stringp start-day)
19611 ;; Convert to an absolute day number
19612 (setq start-day (time-to-days (org-read-date nil t start-day))))
19613 (setq org-agenda-last-arguments (list include-all start-day ndays))
19614 (org-compile-prefix-format 'agenda)
19615 (org-set-sorting-strategy 'agenda)
19616 (require 'calendar)
19617 (let* ((org-agenda-start-on-weekday
19618 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
19619 org-agenda-start-on-weekday nil))
19620 (thefiles (org-agenda-files))
19621 (files thefiles)
19622 (today (time-to-days
19623 (time-subtract (current-time)
19624 (list 0 (* 3600 org-extend-today-until) 0))))
19625 (sd (or start-day today))
19626 (start (if (or (null org-agenda-start-on-weekday)
19627 (< org-agenda-ndays 7))
19629 (let* ((nt (calendar-day-of-week
19630 (calendar-gregorian-from-absolute sd)))
19631 (n1 org-agenda-start-on-weekday)
19632 (d (- nt n1)))
19633 (- sd (+ (if (< d 0) 7 0) d)))))
19634 (day-numbers (list start))
19635 (day-cnt 0)
19636 (inhibit-redisplay (not debug-on-error))
19637 s e rtn rtnall file date d start-pos end-pos todayp nd)
19638 (setq org-agenda-redo-command
19639 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
19640 ;; Make the list of days
19641 (setq ndays (or ndays org-agenda-ndays)
19642 nd ndays)
19643 (while (> ndays 1)
19644 (push (1+ (car day-numbers)) day-numbers)
19645 (setq ndays (1- ndays)))
19646 (setq day-numbers (nreverse day-numbers))
19647 (org-prepare-agenda "Day/Week")
19648 (org-set-local 'org-starting-day (car day-numbers))
19649 (org-set-local 'org-include-all-loc include-all)
19650 (org-set-local 'org-agenda-span
19651 (org-agenda-ndays-to-span nd))
19652 (when (and (or include-all org-agenda-include-all-todo)
19653 (member today day-numbers))
19654 (setq files thefiles
19655 rtnall nil)
19656 (while (setq file (pop files))
19657 (catch 'nextfile
19658 (org-check-agenda-file file)
19659 (setq date (calendar-gregorian-from-absolute today)
19660 rtn (org-agenda-get-day-entries
19661 file date :todo))
19662 (setq rtnall (append rtnall rtn))))
19663 (when rtnall
19664 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
19665 (add-text-properties (point-min) (1- (point))
19666 (list 'face 'org-agenda-structure))
19667 (insert (org-finalize-agenda-entries rtnall) "\n")))
19668 (unless org-agenda-compact-blocks
19669 (setq s (point))
19670 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
19671 "-agenda:\n")
19672 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
19673 'org-date-line t)))
19674 (while (setq d (pop day-numbers))
19675 (setq date (calendar-gregorian-from-absolute d)
19676 s (point))
19677 (if (or (setq todayp (= d today))
19678 (and (not start-pos) (= d sd)))
19679 (setq start-pos (point))
19680 (if (and start-pos (not end-pos))
19681 (setq end-pos (point))))
19682 (setq files thefiles
19683 rtnall nil)
19684 (while (setq file (pop files))
19685 (catch 'nextfile
19686 (org-check-agenda-file file)
19687 (if org-agenda-show-log
19688 (setq rtn (org-agenda-get-day-entries
19689 file date
19690 :deadline :scheduled :timestamp :sexp :closed))
19691 (setq rtn (org-agenda-get-day-entries
19692 file date
19693 :deadline :scheduled :sexp :timestamp)))
19694 (setq rtnall (append rtnall rtn))))
19695 (if org-agenda-include-diary
19696 (progn
19697 (require 'diary-lib)
19698 (setq rtn (org-get-entries-from-diary date))
19699 (setq rtnall (append rtnall rtn))))
19700 (if (or rtnall org-agenda-show-all-dates)
19701 (progn
19702 (setq day-cnt (1+ day-cnt))
19703 (insert
19704 (if (stringp org-agenda-format-date)
19705 (format-time-string org-agenda-format-date
19706 (org-time-from-absolute date))
19707 (funcall org-agenda-format-date date))
19708 "\n")
19709 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
19710 (put-text-property s (1- (point)) 'org-date-line t)
19711 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
19712 (if todayp (put-text-property s (1- (point)) 'org-today t))
19713 (if rtnall (insert
19714 (org-finalize-agenda-entries
19715 (org-agenda-add-time-grid-maybe
19716 rtnall nd todayp))
19717 "\n"))
19718 (put-text-property s (1- (point)) 'day d)
19719 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
19720 (goto-char (point-min))
19721 (org-fit-agenda-window)
19722 (unless (and (pos-visible-in-window-p (point-min))
19723 (pos-visible-in-window-p (point-max)))
19724 (goto-char (1- (point-max)))
19725 (recenter -1)
19726 (if (not (pos-visible-in-window-p (or start-pos 1)))
19727 (progn
19728 (goto-char (or start-pos 1))
19729 (recenter 1))))
19730 (goto-char (or start-pos 1))
19731 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
19732 (org-finalize-agenda)
19733 (setq buffer-read-only t)
19734 (message "")))
19736 (defun org-agenda-ndays-to-span (n)
19737 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
19739 ;;; Agenda TODO list
19741 (defvar org-select-this-todo-keyword nil)
19742 (defvar org-last-arg nil)
19744 ;;;###autoload
19745 (defun org-todo-list (arg)
19746 "Show all TODO entries from all agenda file in a single list.
19747 The prefix arg can be used to select a specific TODO keyword and limit
19748 the list to these. When using \\[universal-argument], you will be prompted
19749 for a keyword. A numeric prefix directly selects the Nth keyword in
19750 `org-todo-keywords-1'."
19751 (interactive "P")
19752 (require 'calendar)
19753 (org-compile-prefix-format 'todo)
19754 (org-set-sorting-strategy 'todo)
19755 (org-prepare-agenda "TODO")
19756 (let* ((today (time-to-days (current-time)))
19757 (date (calendar-gregorian-from-absolute today))
19758 (kwds org-todo-keywords-for-agenda)
19759 (completion-ignore-case t)
19760 (org-select-this-todo-keyword
19761 (if (stringp arg) arg
19762 (and arg (integerp arg) (> arg 0)
19763 (nth (1- arg) kwds))))
19764 rtn rtnall files file pos)
19765 (when (equal arg '(4))
19766 (setq org-select-this-todo-keyword
19767 (completing-read "Keyword (or KWD1|K2D2|...): "
19768 (mapcar 'list kwds) nil nil)))
19769 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
19770 (org-set-local 'org-last-arg arg)
19771 (setq org-agenda-redo-command
19772 '(org-todo-list (or current-prefix-arg org-last-arg)))
19773 (setq files (org-agenda-files)
19774 rtnall nil)
19775 (while (setq file (pop files))
19776 (catch 'nextfile
19777 (org-check-agenda-file file)
19778 (setq rtn (org-agenda-get-day-entries file date :todo))
19779 (setq rtnall (append rtnall rtn))))
19780 (if org-agenda-overriding-header
19781 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19782 nil 'face 'org-agenda-structure) "\n")
19783 (insert "Global list of TODO items of type: ")
19784 (add-text-properties (point-min) (1- (point))
19785 (list 'face 'org-agenda-structure))
19786 (setq pos (point))
19787 (insert (or org-select-this-todo-keyword "ALL") "\n")
19788 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19789 (setq pos (point))
19790 (unless org-agenda-multi
19791 (insert "Available with `N r': (0)ALL")
19792 (let ((n 0) s)
19793 (mapc (lambda (x)
19794 (setq s (format "(%d)%s" (setq n (1+ n)) x))
19795 (if (> (+ (current-column) (string-width s) 1) (frame-width))
19796 (insert "\n "))
19797 (insert " " s))
19798 kwds))
19799 (insert "\n"))
19800 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19801 (when rtnall
19802 (insert (org-finalize-agenda-entries rtnall) "\n"))
19803 (goto-char (point-min))
19804 (org-fit-agenda-window)
19805 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
19806 (org-finalize-agenda)
19807 (setq buffer-read-only t)))
19809 ;;; Agenda tags match
19811 ;;;###autoload
19812 (defun org-tags-view (&optional todo-only match)
19813 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
19814 The prefix arg TODO-ONLY limits the search to TODO entries."
19815 (interactive "P")
19816 (org-compile-prefix-format 'tags)
19817 (org-set-sorting-strategy 'tags)
19818 (let* ((org-tags-match-list-sublevels
19819 (if todo-only t org-tags-match-list-sublevels))
19820 (completion-ignore-case t)
19821 rtn rtnall files file pos matcher
19822 buffer)
19823 (setq matcher (org-make-tags-matcher match)
19824 match (car matcher) matcher (cdr matcher))
19825 (org-prepare-agenda (concat "TAGS " match))
19826 (setq org-agenda-redo-command
19827 (list 'org-tags-view (list 'quote todo-only)
19828 (list 'if 'current-prefix-arg nil match)))
19829 (setq files (org-agenda-files)
19830 rtnall nil)
19831 (while (setq file (pop files))
19832 (catch 'nextfile
19833 (org-check-agenda-file file)
19834 (setq buffer (if (file-exists-p file)
19835 (org-get-agenda-file-buffer file)
19836 (error "No such file %s" file)))
19837 (if (not buffer)
19838 ;; If file does not exist, merror message to agenda
19839 (setq rtn (list
19840 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
19841 rtnall (append rtnall rtn))
19842 (with-current-buffer buffer
19843 (unless (org-mode-p)
19844 (error "Agenda file %s is not in `org-mode'" file))
19845 (save-excursion
19846 (save-restriction
19847 (if org-agenda-restrict
19848 (narrow-to-region org-agenda-restrict-begin
19849 org-agenda-restrict-end)
19850 (widen))
19851 (setq rtn (org-scan-tags 'agenda matcher todo-only))
19852 (setq rtnall (append rtnall rtn))))))))
19853 (if org-agenda-overriding-header
19854 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
19855 nil 'face 'org-agenda-structure) "\n")
19856 (insert "Headlines with TAGS match: ")
19857 (add-text-properties (point-min) (1- (point))
19858 (list 'face 'org-agenda-structure))
19859 (setq pos (point))
19860 (insert match "\n")
19861 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
19862 (setq pos (point))
19863 (unless org-agenda-multi
19864 (insert "Press `C-u r' to search again with new search string\n"))
19865 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
19866 (when rtnall
19867 (insert (org-finalize-agenda-entries rtnall) "\n"))
19868 (goto-char (point-min))
19869 (org-fit-agenda-window)
19870 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
19871 (org-finalize-agenda)
19872 (setq buffer-read-only t)))
19874 ;;; Agenda Finding stuck projects
19876 (defvar org-agenda-skip-regexp nil
19877 "Regular expression used in skipping subtrees for the agenda.
19878 This is basically a temporary global variable that can be set and then
19879 used by user-defined selections using `org-agenda-skip-function'.")
19881 (defvar org-agenda-overriding-header nil
19882 "When this is set during todo and tags searches, will replace header.")
19884 (defun org-agenda-skip-subtree-when-regexp-matches ()
19885 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
19886 If yes, it returns the end position of this tree, causing agenda commands
19887 to skip this subtree. This is a function that can be put into
19888 `org-agenda-skip-function' for the duration of a command."
19889 (let ((end (save-excursion (org-end-of-subtree t)))
19890 skip)
19891 (save-excursion
19892 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
19893 (and skip end)))
19895 (defun org-agenda-skip-entry-if (&rest conditions)
19896 "Skip entry if any of CONDITIONS is true.
19897 See `org-agenda-skip-if for details."
19898 (org-agenda-skip-if nil conditions))
19900 (defun org-agenda-skip-subtree-if (&rest conditions)
19901 "Skip entry if any of CONDITIONS is true.
19902 See `org-agenda-skip-if for details."
19903 (org-agenda-skip-if t conditions))
19905 (defun org-agenda-skip-if (subtree conditions)
19906 "Checks current entity for CONDITIONS.
19907 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
19908 the entry, i.e. the text before the next heading is checked.
19910 CONDITIONS is a list of symbols, boolean OR is used to combine the results
19911 from different tests. Valid conditions are:
19913 scheduled Check if there is a scheduled cookie
19914 notscheduled Check if there is no scheduled cookie
19915 deadline Check if there is a deadline
19916 notdeadline Check if there is no deadline
19917 regexp Check if regexp matches
19918 notregexp Check if regexp does not match.
19920 The regexp is taken from the conditions list, it must com right after the
19921 `regexp' of `notregexp' element.
19923 If any of these conditions is met, this function returns the end point of
19924 the entity, causing the search to continue from there. This is a function
19925 that can be put into `org-agenda-skip-function' for the duration of a command."
19926 (let (beg end m)
19927 (org-back-to-heading t)
19928 (setq beg (point)
19929 end (if subtree
19930 (progn (org-end-of-subtree t) (point))
19931 (progn (outline-next-heading) (1- (point)))))
19932 (goto-char beg)
19933 (and
19935 (and (memq 'scheduled conditions)
19936 (re-search-forward org-scheduled-time-regexp end t))
19937 (and (memq 'notscheduled conditions)
19938 (not (re-search-forward org-scheduled-time-regexp end t)))
19939 (and (memq 'deadline conditions)
19940 (re-search-forward org-deadline-time-regexp end t))
19941 (and (memq 'notdeadline conditions)
19942 (not (re-search-forward org-deadline-time-regexp end t)))
19943 (and (setq m (memq 'regexp conditions))
19944 (stringp (nth 1 m))
19945 (re-search-forward (nth 1 m) end t))
19946 (and (setq m (memq 'notregexp conditions))
19947 (stringp (nth 1 m))
19948 (not (re-search-forward (nth 1 m) end t))))
19949 end)))
19951 ;;;###autoload
19952 (defun org-agenda-list-stuck-projects (&rest ignore)
19953 "Create agenda view for projects that are stuck.
19954 Stuck projects are project that have no next actions. For the definitions
19955 of what a project is and how to check if it stuck, customize the variable
19956 `org-stuck-projects'.
19957 MATCH is being ignored."
19958 (interactive)
19959 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
19960 ;; FIXME: we could have used org-agenda-skip-if here.
19961 (org-agenda-overriding-header "List of stuck projects: ")
19962 (matcher (nth 0 org-stuck-projects))
19963 (todo (nth 1 org-stuck-projects))
19964 (todo-wds (if (member "*" todo)
19965 (progn
19966 (org-prepare-agenda-buffers (org-agenda-files))
19967 (org-delete-all
19968 org-done-keywords-for-agenda
19969 (copy-sequence org-todo-keywords-for-agenda)))
19970 todo))
19971 (todo-re (concat "^\\*+[ \t]+\\("
19972 (mapconcat 'identity todo-wds "\\|")
19973 "\\)\\>"))
19974 (tags (nth 2 org-stuck-projects))
19975 (tags-re (if (member "*" tags)
19976 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
19977 (concat "^\\*+ .*:\\("
19978 (mapconcat 'identity tags "\\|")
19979 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
19980 (gen-re (nth 3 org-stuck-projects))
19981 (re-list
19982 (delq nil
19983 (list
19984 (if todo todo-re)
19985 (if tags tags-re)
19986 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
19987 gen-re)))))
19988 (setq org-agenda-skip-regexp
19989 (if re-list
19990 (mapconcat 'identity re-list "\\|")
19991 (error "No information how to identify unstuck projects")))
19992 (org-tags-view nil matcher)
19993 (with-current-buffer org-agenda-buffer-name
19994 (setq org-agenda-redo-command
19995 '(org-agenda-list-stuck-projects
19996 (or current-prefix-arg org-last-arg))))))
19998 ;;; Diary integration
20000 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
20002 (defun org-get-entries-from-diary (date)
20003 "Get the (Emacs Calendar) diary entries for DATE."
20004 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
20005 (diary-display-hook '(fancy-diary-display))
20006 (pop-up-frames nil)
20007 (list-diary-entries-hook
20008 (cons 'org-diary-default-entry list-diary-entries-hook))
20009 (diary-file-name-prefix-function nil) ; turn this feature off
20010 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
20011 entries
20012 (org-disable-agenda-to-diary t))
20013 (save-excursion
20014 (save-window-excursion
20015 (funcall (if (fboundp 'diary-list-entries)
20016 'diary-list-entries 'list-diary-entries)
20017 date 1)))
20018 (if (not (get-buffer fancy-diary-buffer))
20019 (setq entries nil)
20020 (with-current-buffer fancy-diary-buffer
20021 (setq buffer-read-only nil)
20022 (if (zerop (buffer-size))
20023 ;; No entries
20024 (setq entries nil)
20025 ;; Omit the date and other unnecessary stuff
20026 (org-agenda-cleanup-fancy-diary)
20027 ;; Add prefix to each line and extend the text properties
20028 (if (zerop (buffer-size))
20029 (setq entries nil)
20030 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
20031 (set-buffer-modified-p nil)
20032 (kill-buffer fancy-diary-buffer)))
20033 (when entries
20034 (setq entries (org-split-string entries "\n"))
20035 (setq entries
20036 (mapcar
20037 (lambda (x)
20038 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
20039 ;; Extend the text properties to the beginning of the line
20040 (org-add-props x (text-properties-at (1- (length x)) x)
20041 'type "diary" 'date date))
20042 entries)))))
20044 (defun org-agenda-cleanup-fancy-diary ()
20045 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
20046 This gets rid of the date, the underline under the date, and
20047 the dummy entry installed by `org-mode' to ensure non-empty diary for each
20048 date. It also removes lines that contain only whitespace."
20049 (goto-char (point-min))
20050 (if (looking-at ".*?:[ \t]*")
20051 (progn
20052 (replace-match "")
20053 (re-search-forward "\n=+$" nil t)
20054 (replace-match "")
20055 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
20056 (re-search-forward "\n=+$" nil t)
20057 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
20058 (goto-char (point-min))
20059 (while (re-search-forward "^ +\n" nil t)
20060 (replace-match ""))
20061 (goto-char (point-min))
20062 (if (re-search-forward "^Org-mode dummy\n?" nil t)
20063 (replace-match "")))
20065 ;; Make sure entries from the diary have the right text properties.
20066 (eval-after-load "diary-lib"
20067 '(if (boundp 'diary-modify-entry-list-string-function)
20068 ;; We can rely on the hook, nothing to do
20070 ;; Hook not avaiable, must use advice to make this work
20071 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
20072 "Make the position visible."
20073 (if (and org-disable-agenda-to-diary ;; called from org-agenda
20074 (stringp string)
20075 buffer-file-name)
20076 (setq string (org-modify-diary-entry-string string))))))
20078 (defun org-modify-diary-entry-string (string)
20079 "Add text properties to string, allowing org-mode to act on it."
20080 (org-add-props string nil
20081 'mouse-face 'highlight
20082 'keymap org-agenda-keymap
20083 'help-echo (if buffer-file-name
20084 (format "mouse-2 or RET jump to diary file %s"
20085 (abbreviate-file-name buffer-file-name))
20087 'org-agenda-diary-link t
20088 'org-marker (org-agenda-new-marker (point-at-bol))))
20090 (defun org-diary-default-entry ()
20091 "Add a dummy entry to the diary.
20092 Needed to avoid empty dates which mess up holiday display."
20093 ;; Catch the error if dealing with the new add-to-diary-alist
20094 (when org-disable-agenda-to-diary
20095 (condition-case nil
20096 (add-to-diary-list original-date "Org-mode dummy" "")
20097 (error
20098 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
20100 ;;;###autoload
20101 (defun org-diary (&rest args)
20102 "Return diary information from org-files.
20103 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
20104 It accesses org files and extracts information from those files to be
20105 listed in the diary. The function accepts arguments specifying what
20106 items should be listed. The following arguments are allowed:
20108 :timestamp List the headlines of items containing a date stamp or
20109 date range matching the selected date. Deadlines will
20110 also be listed, on the expiration day.
20112 :sexp List entries resulting from diary-like sexps.
20114 :deadline List any deadlines past due, or due within
20115 `org-deadline-warning-days'. The listing occurs only
20116 in the diary for *today*, not at any other date. If
20117 an entry is marked DONE, it is no longer listed.
20119 :scheduled List all items which are scheduled for the given date.
20120 The diary for *today* also contains items which were
20121 scheduled earlier and are not yet marked DONE.
20123 :todo List all TODO items from the org-file. This may be a
20124 long list - so this is not turned on by default.
20125 Like deadlines, these entries only show up in the
20126 diary for *today*, not at any other date.
20128 The call in the diary file should look like this:
20130 &%%(org-diary) ~/path/to/some/orgfile.org
20132 Use a separate line for each org file to check. Or, if you omit the file name,
20133 all files listed in `org-agenda-files' will be checked automatically:
20135 &%%(org-diary)
20137 If you don't give any arguments (as in the example above), the default
20138 arguments (:deadline :scheduled :timestamp :sexp) are used.
20139 So the example above may also be written as
20141 &%%(org-diary :deadline :timestamp :sexp :scheduled)
20143 The function expects the lisp variables `entry' and `date' to be provided
20144 by the caller, because this is how the calendar works. Don't use this
20145 function from a program - use `org-agenda-get-day-entries' instead."
20146 (org-agenda-maybe-reset-markers)
20147 (org-compile-prefix-format 'agenda)
20148 (org-set-sorting-strategy 'agenda)
20149 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20150 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
20151 (list entry)
20152 (org-agenda-files t)))
20153 file rtn results)
20154 (org-prepare-agenda-buffers files)
20155 ;; If this is called during org-agenda, don't return any entries to
20156 ;; the calendar. Org Agenda will list these entries itself.
20157 (if org-disable-agenda-to-diary (setq files nil))
20158 (while (setq file (pop files))
20159 (setq rtn (apply 'org-agenda-get-day-entries file date args))
20160 (setq results (append results rtn)))
20161 (if results
20162 (concat (org-finalize-agenda-entries results) "\n"))))
20164 ;;; Agenda entry finders
20166 (defun org-agenda-get-day-entries (file date &rest args)
20167 "Does the work for `org-diary' and `org-agenda'.
20168 FILE is the path to a file to be checked for entries. DATE is date like
20169 the one returned by `calendar-current-date'. ARGS are symbols indicating
20170 which kind of entries should be extracted. For details about these, see
20171 the documentation of `org-diary'."
20172 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
20173 (let* ((org-startup-folded nil)
20174 (org-startup-align-all-tables nil)
20175 (buffer (if (file-exists-p file)
20176 (org-get-agenda-file-buffer file)
20177 (error "No such file %s" file)))
20178 arg results rtn)
20179 (if (not buffer)
20180 ;; If file does not exist, make sure an error message ends up in diary
20181 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
20182 (with-current-buffer buffer
20183 (unless (org-mode-p)
20184 (error "Agenda file %s is not in `org-mode'" file))
20185 (let ((case-fold-search nil))
20186 (save-excursion
20187 (save-restriction
20188 (if org-agenda-restrict
20189 (narrow-to-region org-agenda-restrict-begin
20190 org-agenda-restrict-end)
20191 (widen))
20192 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
20193 (while (setq arg (pop args))
20194 (cond
20195 ((and (eq arg :todo)
20196 (equal date (calendar-current-date)))
20197 (setq rtn (org-agenda-get-todos))
20198 (setq results (append results rtn)))
20199 ((eq arg :timestamp)
20200 (setq rtn (org-agenda-get-blocks))
20201 (setq results (append results rtn))
20202 (setq rtn (org-agenda-get-timestamps))
20203 (setq results (append results rtn)))
20204 ((eq arg :sexp)
20205 (setq rtn (org-agenda-get-sexps))
20206 (setq results (append results rtn)))
20207 ((eq arg :scheduled)
20208 (setq rtn (org-agenda-get-scheduled))
20209 (setq results (append results rtn)))
20210 ((eq arg :closed)
20211 (setq rtn (org-agenda-get-closed))
20212 (setq results (append results rtn)))
20213 ((eq arg :deadline)
20214 (setq rtn (org-agenda-get-deadlines))
20215 (setq results (append results rtn))))))))
20216 results))))
20218 ;; FIXME: this works only if the cursor is *not* at the
20219 ;; beginning of the entry
20220 ;(defun org-entry-is-done-p ()
20221 ; "Is the current entry marked DONE?"
20222 ; (save-excursion
20223 ; (and (re-search-backward "[\r\n]\\*+ " nil t)
20224 ; (looking-at org-nl-done-regexp))))
20226 (defun org-entry-is-todo-p ()
20227 (member (org-get-todo-state) org-not-done-keywords))
20229 (defun org-entry-is-done-p ()
20230 (member (org-get-todo-state) org-done-keywords))
20232 (defun org-get-todo-state ()
20233 (save-excursion
20234 (org-back-to-heading t)
20235 (and (looking-at org-todo-line-regexp)
20236 (match-end 2)
20237 (match-string 2))))
20239 (defun org-at-date-range-p (&optional inactive-ok)
20240 "Is the cursor inside a date range?"
20241 (interactive)
20242 (save-excursion
20243 (catch 'exit
20244 (let ((pos (point)))
20245 (skip-chars-backward "^[<\r\n")
20246 (skip-chars-backward "<[")
20247 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20248 (>= (match-end 0) pos)
20249 (throw 'exit t))
20250 (skip-chars-backward "^<[\r\n")
20251 (skip-chars-backward "<[")
20252 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
20253 (>= (match-end 0) pos)
20254 (throw 'exit t)))
20255 nil)))
20257 (defun org-agenda-get-todos ()
20258 "Return the TODO information for agenda display."
20259 (let* ((props (list 'face nil
20260 'done-face 'org-done
20261 'org-not-done-regexp org-not-done-regexp
20262 'org-todo-regexp org-todo-regexp
20263 'mouse-face 'highlight
20264 'keymap org-agenda-keymap
20265 'help-echo
20266 (format "mouse-2 or RET jump to org file %s"
20267 (abbreviate-file-name buffer-file-name))))
20268 ;; FIXME: get rid of the \n at some point but watch out
20269 (regexp (concat "^\\*+[ \t]+\\("
20270 (if org-select-this-todo-keyword
20271 (if (equal org-select-this-todo-keyword "*")
20272 org-todo-regexp
20273 (concat "\\<\\("
20274 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
20275 "\\)\\>"))
20276 org-not-done-regexp)
20277 "[^\n\r]*\\)"))
20278 marker priority category tags
20279 ee txt beg end)
20280 (goto-char (point-min))
20281 (while (re-search-forward regexp nil t)
20282 (catch :skip
20283 (save-match-data
20284 (beginning-of-line)
20285 (setq beg (point) end (progn (outline-next-heading) (point)))
20286 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
20287 (re-search-forward org-ts-regexp end t))
20288 (and org-agenda-todo-ignore-scheduled (goto-char beg)
20289 (re-search-forward org-scheduled-time-regexp end t))
20290 (and org-agenda-todo-ignore-deadlines (goto-char beg)
20291 (re-search-forward org-deadline-time-regexp end t)
20292 (org-deadline-close (match-string 1))))
20293 (goto-char (1+ beg))
20294 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
20295 (throw :skip nil)))
20296 (goto-char beg)
20297 (org-agenda-skip)
20298 (goto-char (match-beginning 1))
20299 (setq marker (org-agenda-new-marker (match-beginning 0))
20300 category (org-get-category)
20301 tags (org-get-tags-at (point))
20302 txt (org-format-agenda-item "" (match-string 1) category tags)
20303 priority (1+ (org-get-priority txt)))
20304 (org-add-props txt props
20305 'org-marker marker 'org-hd-marker marker
20306 'priority priority 'org-category category
20307 'type "todo")
20308 (push txt ee)
20309 (if org-agenda-todo-list-sublevels
20310 (goto-char (match-end 1))
20311 (org-end-of-subtree 'invisible))))
20312 (nreverse ee)))
20314 (defconst org-agenda-no-heading-message
20315 "No heading for this item in buffer or region.")
20317 (defun org-agenda-get-timestamps ()
20318 "Return the date stamp information for agenda display."
20319 (let* ((props (list 'face nil
20320 'org-not-done-regexp org-not-done-regexp
20321 'org-todo-regexp org-todo-regexp
20322 'mouse-face 'highlight
20323 'keymap org-agenda-keymap
20324 'help-echo
20325 (format "mouse-2 or RET jump to org file %s"
20326 (abbreviate-file-name buffer-file-name))))
20327 (d1 (calendar-absolute-from-gregorian date))
20328 (remove-re
20329 (concat
20330 (regexp-quote
20331 (format-time-string
20332 "<%Y-%m-%d"
20333 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
20334 ".*?>"))
20335 (regexp
20336 (concat
20337 (regexp-quote
20338 (substring
20339 (format-time-string
20340 (car org-time-stamp-formats)
20341 (apply 'encode-time ; DATE bound by calendar
20342 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20343 0 11))
20344 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
20345 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
20346 marker hdmarker deadlinep scheduledp donep tmp priority category
20347 ee txt timestr tags b0 b3 e3 head)
20348 (goto-char (point-min))
20349 (while (re-search-forward regexp nil t)
20350 (setq b0 (match-beginning 0)
20351 b3 (match-beginning 3) e3 (match-end 3))
20352 (catch :skip
20353 (and (org-at-date-range-p) (throw :skip nil))
20354 (org-agenda-skip)
20355 (if (and (match-end 1)
20356 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
20357 (throw :skip nil))
20358 (if (and e3
20359 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
20360 (throw :skip nil))
20361 (setq marker (org-agenda-new-marker b0)
20362 category (org-get-category b0)
20363 tmp (buffer-substring (max (point-min)
20364 (- b0 org-ds-keyword-length))
20366 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
20367 deadlinep (string-match org-deadline-regexp tmp)
20368 scheduledp (string-match org-scheduled-regexp tmp)
20369 donep (org-entry-is-done-p))
20370 (if (or scheduledp deadlinep) (throw :skip t))
20371 (if (string-match ">" timestr)
20372 ;; substring should only run to end of time stamp
20373 (setq timestr (substring timestr 0 (match-end 0))))
20374 (save-excursion
20375 (if (re-search-backward "^\\*+ " nil t)
20376 (progn
20377 (goto-char (match-beginning 0))
20378 (setq hdmarker (org-agenda-new-marker)
20379 tags (org-get-tags-at))
20380 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20381 (setq head (match-string 1))
20382 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
20383 (setq txt (org-format-agenda-item
20384 nil head category tags timestr nil
20385 remove-re)))
20386 (setq txt org-agenda-no-heading-message))
20387 (setq priority (org-get-priority txt))
20388 (org-add-props txt props
20389 'org-marker marker 'org-hd-marker hdmarker)
20390 (org-add-props txt nil 'priority priority
20391 'org-category category 'date date
20392 'type "timestamp")
20393 (push txt ee))
20394 (outline-next-heading)))
20395 (nreverse ee)))
20397 (defun org-agenda-get-sexps ()
20398 "Return the sexp information for agenda display."
20399 (require 'diary-lib)
20400 (let* ((props (list 'face nil
20401 'mouse-face 'highlight
20402 'keymap org-agenda-keymap
20403 'help-echo
20404 (format "mouse-2 or RET jump to org file %s"
20405 (abbreviate-file-name buffer-file-name))))
20406 (regexp "^&?%%(")
20407 marker category ee txt tags entry result beg b sexp sexp-entry)
20408 (goto-char (point-min))
20409 (while (re-search-forward regexp nil t)
20410 (catch :skip
20411 (org-agenda-skip)
20412 (setq beg (match-beginning 0))
20413 (goto-char (1- (match-end 0)))
20414 (setq b (point))
20415 (forward-sexp 1)
20416 (setq sexp (buffer-substring b (point)))
20417 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
20418 (org-trim (match-string 1))
20419 ""))
20420 (setq result (org-diary-sexp-entry sexp sexp-entry date))
20421 (when result
20422 (setq marker (org-agenda-new-marker beg)
20423 category (org-get-category beg))
20425 (if (string-match "\\S-" result)
20426 (setq txt result)
20427 (setq txt "SEXP entry returned empty string"))
20429 (setq txt (org-format-agenda-item
20430 "" txt category tags 'time))
20431 (org-add-props txt props 'org-marker marker)
20432 (org-add-props txt nil
20433 'org-category category 'date date
20434 'type "sexp")
20435 (push txt ee))))
20436 (nreverse ee)))
20438 (defun org-agenda-get-closed ()
20439 "Return the logged TODO entries for agenda display."
20440 (let* ((props (list 'mouse-face 'highlight
20441 'org-not-done-regexp org-not-done-regexp
20442 'org-todo-regexp org-todo-regexp
20443 'keymap org-agenda-keymap
20444 'help-echo
20445 (format "mouse-2 or RET jump to org file %s"
20446 (abbreviate-file-name buffer-file-name))))
20447 (regexp (concat
20448 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
20449 (regexp-quote
20450 (substring
20451 (format-time-string
20452 (car org-time-stamp-formats)
20453 (apply 'encode-time ; DATE bound by calendar
20454 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
20455 1 11))))
20456 marker hdmarker priority category tags closedp
20457 ee txt timestr)
20458 (goto-char (point-min))
20459 (while (re-search-forward regexp nil t)
20460 (catch :skip
20461 (org-agenda-skip)
20462 (setq marker (org-agenda-new-marker (match-beginning 0))
20463 closedp (equal (match-string 1) org-closed-string)
20464 category (org-get-category (match-beginning 0))
20465 timestr (buffer-substring (match-beginning 0) (point-at-eol))
20466 ;; donep (org-entry-is-done-p)
20468 (if (string-match "\\]" timestr)
20469 ;; substring should only run to end of time stamp
20470 (setq timestr (substring timestr 0 (match-end 0))))
20471 (save-excursion
20472 (if (re-search-backward "^\\*+ " nil t)
20473 (progn
20474 (goto-char (match-beginning 0))
20475 (setq hdmarker (org-agenda-new-marker)
20476 tags (org-get-tags-at))
20477 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20478 (setq txt (org-format-agenda-item
20479 (if closedp "Closed: " "Clocked: ")
20480 (match-string 1) category tags timestr)))
20481 (setq txt org-agenda-no-heading-message))
20482 (setq priority 100000)
20483 (org-add-props txt props
20484 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
20485 'priority priority 'org-category category
20486 'type "closed" 'date date
20487 'undone-face 'org-warning 'done-face 'org-done)
20488 (push txt ee))
20489 (outline-next-heading)))
20490 (nreverse ee)))
20492 (defun org-agenda-get-deadlines ()
20493 "Return the deadline information for agenda display."
20494 (let* ((props (list 'mouse-face 'highlight
20495 'org-not-done-regexp org-not-done-regexp
20496 'org-todo-regexp org-todo-regexp
20497 'keymap org-agenda-keymap
20498 'help-echo
20499 (format "mouse-2 or RET jump to org file %s"
20500 (abbreviate-file-name buffer-file-name))))
20501 (regexp org-deadline-time-regexp)
20502 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20503 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20504 d2 diff dfrac wdays pos pos1 category tags
20505 ee txt head face s upcomingp donep timestr)
20506 (goto-char (point-min))
20507 (while (re-search-forward regexp nil t)
20508 (catch :skip
20509 (org-agenda-skip)
20510 (setq s (match-string 1)
20511 pos (1- (match-beginning 1))
20512 d2 (org-time-string-to-absolute (match-string 1) d1)
20513 diff (- d2 d1)
20514 wdays (org-get-wdays s)
20515 dfrac (/ (* 1.0 (- wdays diff)) wdays)
20516 upcomingp (and todayp (> diff 0)))
20517 ;; When to show a deadline in the calendar:
20518 ;; If the expiration is within wdays warning time.
20519 ;; Past-due deadlines are only shown on the current date
20520 (if (or (and (<= diff wdays)
20521 (and todayp (not org-agenda-only-exact-dates)))
20522 (= diff 0))
20523 (save-excursion
20524 (setq category (org-get-category))
20525 (if (re-search-backward "^\\*+[ \t]+" nil t)
20526 (progn
20527 (goto-char (match-end 0))
20528 (setq pos1 (match-beginning 0))
20529 (setq tags (org-get-tags-at pos1))
20530 (setq head (buffer-substring-no-properties
20531 (point)
20532 (progn (skip-chars-forward "^\r\n")
20533 (point))))
20534 (setq donep (string-match org-looking-at-done-regexp head))
20535 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20536 (setq timestr
20537 (concat (substring s (match-beginning 1)) " "))
20538 (setq timestr 'time))
20539 (if (and donep
20540 (or org-agenda-skip-deadline-if-done
20541 (not (= diff 0))))
20542 (setq txt nil)
20543 (setq txt (org-format-agenda-item
20544 (if (= diff 0)
20545 (car org-agenda-deadline-leaders)
20546 (format (nth 1 org-agenda-deadline-leaders)
20547 diff))
20548 head category tags timestr))))
20549 (setq txt org-agenda-no-heading-message))
20550 (when txt
20551 (setq face (org-agenda-deadline-face dfrac))
20552 (org-add-props txt props
20553 'org-marker (org-agenda-new-marker pos)
20554 'org-hd-marker (org-agenda-new-marker pos1)
20555 'priority (+ (if upcomingp (floor (* dfrac 10.)) 100)
20556 (org-get-priority txt))
20557 'org-category category
20558 'type (if upcomingp "upcoming-deadline" "deadline")
20559 'date (if upcomingp date d2)
20560 'face (if donep 'org-done face)
20561 'undone-face face 'done-face 'org-done)
20562 (push txt ee))))))
20563 (nreverse ee)))
20565 (defun org-agenda-deadline-face (fraction)
20566 "Return the face to displaying a deadline item.
20567 FRACTION is what fraction of the head-warning time has passed."
20568 (let ((faces org-agenda-deadline-faces) f)
20569 (catch 'exit
20570 (while (setq f (pop faces))
20571 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
20573 (defun org-agenda-get-scheduled ()
20574 "Return the scheduled information for agenda display."
20575 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
20576 'org-todo-regexp org-todo-regexp
20577 'done-face 'org-done
20578 'mouse-face 'highlight
20579 'keymap org-agenda-keymap
20580 'help-echo
20581 (format "mouse-2 or RET jump to org file %s"
20582 (abbreviate-file-name buffer-file-name))))
20583 (regexp org-scheduled-time-regexp)
20584 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
20585 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
20586 d2 diff pos pos1 category tags
20587 ee txt head pastschedp donep face timestr s)
20588 (goto-char (point-min))
20589 (while (re-search-forward regexp nil t)
20590 (catch :skip
20591 (org-agenda-skip)
20592 (setq s (match-string 1)
20593 pos (1- (match-beginning 1))
20594 d2 (org-time-string-to-absolute (match-string 1) d1)
20595 diff (- d2 d1))
20596 (setq pastschedp (and todayp (< diff 0)))
20597 ;; When to show a scheduled item in the calendar:
20598 ;; If it is on or past the date.
20599 (if (or (and (< diff 0)
20600 (and todayp (not org-agenda-only-exact-dates)))
20601 (= diff 0))
20602 (save-excursion
20603 (setq category (org-get-category))
20604 (if (re-search-backward "^\\*+[ \t]+" nil t)
20605 (progn
20606 (goto-char (match-end 0))
20607 (setq pos1 (match-beginning 0))
20608 (setq tags (org-get-tags-at))
20609 (setq head (buffer-substring-no-properties
20610 (point)
20611 (progn (skip-chars-forward "^\r\n") (point))))
20612 (setq donep (string-match org-looking-at-done-regexp head))
20613 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
20614 (setq timestr
20615 (concat (substring s (match-beginning 1)) " "))
20616 (setq timestr 'time))
20617 (if (and donep
20618 (or org-agenda-skip-scheduled-if-done
20619 (not (= diff 0))))
20620 (setq txt nil)
20621 (setq txt (org-format-agenda-item
20622 (if (= diff 0)
20623 (car org-agenda-scheduled-leaders)
20624 (format (nth 1 org-agenda-scheduled-leaders)
20625 (- 1 diff)))
20626 head category tags timestr))))
20627 (setq txt org-agenda-no-heading-message))
20628 (when txt
20629 (setq face (if pastschedp
20630 'org-scheduled-previously
20631 'org-scheduled-today))
20632 (org-add-props txt props
20633 'undone-face face
20634 'face (if donep 'org-done face)
20635 'org-marker (org-agenda-new-marker pos)
20636 'org-hd-marker (org-agenda-new-marker pos1)
20637 'type (if pastschedp "past-scheduled" "scheduled")
20638 'date (if pastschedp d2 date)
20639 'priority (+ 94 (- 5 diff) (org-get-priority txt))
20640 'org-category category)
20641 (push txt ee))))))
20642 (nreverse ee)))
20644 (defun org-agenda-get-blocks ()
20645 "Return the date-range information for agenda display."
20646 (let* ((props (list 'face nil
20647 'org-not-done-regexp org-not-done-regexp
20648 'org-todo-regexp org-todo-regexp
20649 'mouse-face 'highlight
20650 'keymap org-agenda-keymap
20651 'help-echo
20652 (format "mouse-2 or RET jump to org file %s"
20653 (abbreviate-file-name buffer-file-name))))
20654 (regexp org-tr-regexp)
20655 (d0 (calendar-absolute-from-gregorian date))
20656 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
20657 donep head)
20658 (goto-char (point-min))
20659 (while (re-search-forward regexp nil t)
20660 (catch :skip
20661 (org-agenda-skip)
20662 (setq pos (point))
20663 (setq timestr (match-string 0)
20664 s1 (match-string 1)
20665 s2 (match-string 2)
20666 d1 (time-to-days (org-time-string-to-time s1))
20667 d2 (time-to-days (org-time-string-to-time s2)))
20668 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
20669 ;; Only allow days between the limits, because the normal
20670 ;; date stamps will catch the limits.
20671 (save-excursion
20672 (setq marker (org-agenda-new-marker (point)))
20673 (setq category (org-get-category))
20674 (if (re-search-backward "^\\*+ " nil t)
20675 (progn
20676 (goto-char (match-beginning 0))
20677 (setq hdmarker (org-agenda-new-marker (point)))
20678 (setq tags (org-get-tags-at))
20679 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
20680 (setq head (match-string 1))
20681 (and org-agenda-skip-timestamp-if-done
20682 (org-entry-is-done-p)
20683 (throw :skip t))
20684 (setq txt (org-format-agenda-item
20685 (format (if (= d1 d2) "" "(%d/%d): ")
20686 (1+ (- d0 d1)) (1+ (- d2 d1)))
20687 head category tags
20688 (if (= d0 d1) timestr))))
20689 (setq txt org-agenda-no-heading-message))
20690 (org-add-props txt props
20691 'org-marker marker 'org-hd-marker hdmarker
20692 'type "block" 'date date
20693 'priority (org-get-priority txt) 'org-category category)
20694 (push txt ee)))
20695 (goto-char pos)))
20696 ;; Sort the entries by expiration date.
20697 (nreverse ee)))
20699 ;;; Agenda presentation and sorting
20701 (defconst org-plain-time-of-day-regexp
20702 (concat
20703 "\\(\\<[012]?[0-9]"
20704 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20705 "\\(--?"
20706 "\\(\\<[012]?[0-9]"
20707 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20708 "\\)?")
20709 "Regular expression to match a plain time or time range.
20710 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20711 groups carry important information:
20712 0 the full match
20713 1 the first time, range or not
20714 8 the second time, if it is a range.")
20716 (defconst org-plain-time-extension-regexp
20717 (concat
20718 "\\(\\<[012]?[0-9]"
20719 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
20720 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
20721 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
20722 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
20723 groups carry important information:
20724 0 the full match
20725 7 hours of duration
20726 9 minutes of duration")
20728 (defconst org-stamp-time-of-day-regexp
20729 (concat
20730 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
20731 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
20732 "\\(--?"
20733 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
20734 "Regular expression to match a timestamp time or time range.
20735 After a match, the following groups carry important information:
20736 0 the full match
20737 1 date plus weekday, for backreferencing to make sure both times on same day
20738 2 the first time, range or not
20739 4 the second time, if it is a range.")
20741 (defvar org-prefix-has-time nil
20742 "A flag, set by `org-compile-prefix-format'.
20743 The flag is set if the currently compiled format contains a `%t'.")
20744 (defvar org-prefix-has-tag nil
20745 "A flag, set by `org-compile-prefix-format'.
20746 The flag is set if the currently compiled format contains a `%T'.")
20748 (defun org-format-agenda-item (extra txt &optional category tags dotime
20749 noprefix remove-re)
20750 "Format TXT to be inserted into the agenda buffer.
20751 In particular, it adds the prefix and corresponding text properties. EXTRA
20752 must be a string and replaces the `%s' specifier in the prefix format.
20753 CATEGORY (string, symbol or nil) may be used to overrule the default
20754 category taken from local variable or file name. It will replace the `%c'
20755 specifier in the format. DOTIME, when non-nil, indicates that a
20756 time-of-day should be extracted from TXT for sorting of this entry, and for
20757 the `%t' specifier in the format. When DOTIME is a string, this string is
20758 searched for a time before TXT is. NOPREFIX is a flag and indicates that
20759 only the correctly processes TXT should be returned - this is used by
20760 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
20761 Any match of REMOVE-RE will be removed from TXT."
20762 (save-match-data
20763 ;; Diary entries sometimes have extra whitespace at the beginning
20764 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
20765 (let* ((category (or category
20766 org-category
20767 (if buffer-file-name
20768 (file-name-sans-extension
20769 (file-name-nondirectory buffer-file-name))
20770 "")))
20771 (tag (if tags (nth (1- (length tags)) tags) ""))
20772 time ; time and tag are needed for the eval of the prefix format
20773 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
20774 (time-of-day (and dotime (org-get-time-of-day ts)))
20775 stamp plain s0 s1 s2 rtn srp)
20776 (when (and dotime time-of-day org-prefix-has-time)
20777 ;; Extract starting and ending time and move them to prefix
20778 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
20779 (setq plain (string-match org-plain-time-of-day-regexp ts)))
20780 (setq s0 (match-string 0 ts)
20781 srp (and stamp (match-end 3))
20782 s1 (match-string (if plain 1 2) ts)
20783 s2 (match-string (if plain 8 (if srp 4 6)) ts))
20785 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
20786 ;; them, we might want to remove them there to avoid duplication.
20787 ;; The user can turn this off with a variable.
20788 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
20789 (string-match (concat (regexp-quote s0) " *") txt)
20790 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
20791 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
20792 (= (match-beginning 0) 0)
20794 (setq txt (replace-match "" nil nil txt))))
20795 ;; Normalize the time(s) to 24 hour
20796 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
20797 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
20799 (when (and s1 (not s2) org-agenda-default-appointment-duration
20800 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
20801 (let ((m (+ (string-to-number (match-string 2 s1))
20802 (* 60 (string-to-number (match-string 1 s1)))
20803 org-agenda-default-appointment-duration))
20805 (setq h (/ m 60) m (- m (* h 60)))
20806 (setq s2 (format "%02d:%02d" h m))))
20808 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
20809 txt)
20810 ;; Tags are in the string
20811 (if (or (eq org-agenda-remove-tags t)
20812 (and org-agenda-remove-tags
20813 org-prefix-has-tag))
20814 (setq txt (replace-match "" t t txt))
20815 (setq txt (replace-match
20816 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
20817 (match-string 2 txt))
20818 t t txt))))
20820 (when remove-re
20821 (while (string-match remove-re txt)
20822 (setq txt (replace-match "" t t txt))))
20824 ;; Create the final string
20825 (if noprefix
20826 (setq rtn txt)
20827 ;; Prepare the variables needed in the eval of the compiled format
20828 (setq time (cond (s2 (concat s1 "-" s2))
20829 (s1 (concat s1 "......"))
20830 (t ""))
20831 extra (or extra "")
20832 category (if (symbolp category) (symbol-name category) category))
20833 ;; Evaluate the compiled format
20834 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
20836 ;; And finally add the text properties
20837 (org-add-props rtn nil
20838 'org-category (downcase category) 'tags tags
20839 'org-highest-priority org-highest-priority
20840 'org-lowest-priority org-lowest-priority
20841 'prefix-length (- (length rtn) (length txt))
20842 'time-of-day time-of-day
20843 'txt txt
20844 'time time
20845 'extra extra
20846 'dotime dotime))))
20848 (defvar org-agenda-sorting-strategy) ;; FIXME: can be removed?
20849 (defvar org-agenda-sorting-strategy-selected nil)
20851 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
20852 (catch 'exit
20853 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
20854 ((and todayp (member 'today (car org-agenda-time-grid))))
20855 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
20856 ((member 'weekly (car org-agenda-time-grid)))
20857 (t (throw 'exit list)))
20858 (let* ((have (delq nil (mapcar
20859 (lambda (x) (get-text-property 1 'time-of-day x))
20860 list)))
20861 (string (nth 1 org-agenda-time-grid))
20862 (gridtimes (nth 2 org-agenda-time-grid))
20863 (req (car org-agenda-time-grid))
20864 (remove (member 'remove-match req))
20865 new time)
20866 (if (and (member 'require-timed req) (not have))
20867 ;; don't show empty grid
20868 (throw 'exit list))
20869 (while (setq time (pop gridtimes))
20870 (unless (and remove (member time have))
20871 (setq time (int-to-string time))
20872 (push (org-format-agenda-item
20873 nil string "" nil
20874 (concat (substring time 0 -2) ":" (substring time -2)))
20875 new)
20876 (put-text-property
20877 1 (length (car new)) 'face 'org-time-grid (car new))))
20878 (if (member 'time-up org-agenda-sorting-strategy-selected)
20879 (append new list)
20880 (append list new)))))
20882 (defun org-compile-prefix-format (key)
20883 "Compile the prefix format into a Lisp form that can be evaluated.
20884 The resulting form is returned and stored in the variable
20885 `org-prefix-format-compiled'."
20886 (setq org-prefix-has-time nil org-prefix-has-tag nil)
20887 (let ((s (cond
20888 ((stringp org-agenda-prefix-format)
20889 org-agenda-prefix-format)
20890 ((assq key org-agenda-prefix-format)
20891 (cdr (assq key org-agenda-prefix-format)))
20892 (t " %-12:c%?-12t% s")))
20893 (start 0)
20894 varform vars var e c f opt)
20895 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
20896 s start)
20897 (setq var (cdr (assoc (match-string 4 s)
20898 '(("c" . category) ("t" . time) ("s" . extra)
20899 ("T" . tag))))
20900 c (or (match-string 3 s) "")
20901 opt (match-beginning 1)
20902 start (1+ (match-beginning 0)))
20903 (if (equal var 'time) (setq org-prefix-has-time t))
20904 (if (equal var 'tag) (setq org-prefix-has-tag t))
20905 (setq f (concat "%" (match-string 2 s) "s"))
20906 (if opt
20907 (setq varform
20908 `(if (equal "" ,var)
20910 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
20911 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
20912 (setq s (replace-match "%s" t nil s))
20913 (push varform vars))
20914 (setq vars (nreverse vars))
20915 (setq org-prefix-format-compiled `(format ,s ,@vars))))
20917 (defun org-set-sorting-strategy (key)
20918 (if (symbolp (car org-agenda-sorting-strategy))
20919 ;; the old format
20920 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
20921 (setq org-agenda-sorting-strategy-selected
20922 (or (cdr (assq key org-agenda-sorting-strategy))
20923 (cdr (assq 'agenda org-agenda-sorting-strategy))
20924 '(time-up category-keep priority-down)))))
20926 (defun org-get-time-of-day (s &optional string mod24)
20927 "Check string S for a time of day.
20928 If found, return it as a military time number between 0 and 2400.
20929 If not found, return nil.
20930 The optional STRING argument forces conversion into a 5 character wide string
20931 HH:MM."
20932 (save-match-data
20933 (when
20934 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
20935 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
20936 (let* ((h (string-to-number (match-string 1 s)))
20937 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
20938 (ampm (if (match-end 4) (downcase (match-string 4 s))))
20939 (am-p (equal ampm "am"))
20940 (h1 (cond ((not ampm) h)
20941 ((= h 12) (if am-p 0 12))
20942 (t (+ h (if am-p 0 12)))))
20943 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
20944 (mod h1 24) h1))
20945 (t0 (+ (* 100 h2) m))
20946 (t1 (concat (if (>= h1 24) "+" " ")
20947 (if (< t0 100) "0" "")
20948 (if (< t0 10) "0" "")
20949 (int-to-string t0))))
20950 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
20952 (defun org-finalize-agenda-entries (list &optional nosort)
20953 "Sort and concatenate the agenda items."
20954 (setq list (mapcar 'org-agenda-highlight-todo list))
20955 (if nosort
20956 list
20957 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
20959 (defun org-agenda-highlight-todo (x)
20960 (let (re pl)
20961 (if (eq x 'line)
20962 (save-excursion
20963 (beginning-of-line 1)
20964 (setq re (get-text-property (point) 'org-todo-regexp))
20965 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
20966 (and (looking-at (concat "[ \t]*\\.*" re))
20967 (add-text-properties (match-beginning 0) (match-end 0)
20968 (list 'face (org-get-todo-face 0)))))
20969 (setq re (concat (get-text-property 0 'org-todo-regexp x))
20970 pl (get-text-property 0 'prefix-length x))
20971 (and re (equal (string-match (concat "\\(\\.*\\)" re) x (or pl 0)) pl)
20972 (add-text-properties
20973 (or (match-end 1) (match-end 0)) (match-end 0)
20974 (list 'face (org-get-todo-face (match-string 2 x)))
20976 x)))
20978 (defsubst org-cmp-priority (a b)
20979 "Compare the priorities of string A and B."
20980 (let ((pa (or (get-text-property 1 'priority a) 0))
20981 (pb (or (get-text-property 1 'priority b) 0)))
20982 (cond ((> pa pb) +1)
20983 ((< pa pb) -1)
20984 (t nil))))
20986 (defsubst org-cmp-category (a b)
20987 "Compare the string values of categories of strings A and B."
20988 (let ((ca (or (get-text-property 1 'org-category a) ""))
20989 (cb (or (get-text-property 1 'org-category b) "")))
20990 (cond ((string-lessp ca cb) -1)
20991 ((string-lessp cb ca) +1)
20992 (t nil))))
20994 (defsubst org-cmp-tag (a b)
20995 "Compare the string values of categories of strings A and B."
20996 (let ((ta (car (last (get-text-property 1 'tags a))))
20997 (tb (car (last (get-text-property 1 'tags b)))))
20998 (cond ((not ta) +1)
20999 ((not tb) -1)
21000 ((string-lessp ta tb) -1)
21001 ((string-lessp tb ta) +1)
21002 (t nil))))
21004 (defsubst org-cmp-time (a b)
21005 "Compare the time-of-day values of strings A and B."
21006 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
21007 (ta (or (get-text-property 1 'time-of-day a) def))
21008 (tb (or (get-text-property 1 'time-of-day b) def)))
21009 (cond ((< ta tb) -1)
21010 ((< tb ta) +1)
21011 (t nil))))
21013 (defun org-entries-lessp (a b)
21014 "Predicate for sorting agenda entries."
21015 ;; The following variables will be used when the form is evaluated.
21016 ;; So even though the compiler complains, keep them.
21017 (let* ((time-up (org-cmp-time a b))
21018 (time-down (if time-up (- time-up) nil))
21019 (priority-up (org-cmp-priority a b))
21020 (priority-down (if priority-up (- priority-up) nil))
21021 (category-up (org-cmp-category a b))
21022 (category-down (if category-up (- category-up) nil))
21023 (category-keep (if category-up +1 nil))
21024 (tag-up (org-cmp-tag a b))
21025 (tag-down (if tag-up (- tag-up) nil)))
21026 (cdr (assoc
21027 (eval (cons 'or org-agenda-sorting-strategy-selected))
21028 '((-1 . t) (1 . nil) (nil . nil))))))
21030 ;;; Agenda commands
21032 (defun org-agenda-check-type (error &rest types)
21033 "Check if agenda buffer is of allowed type.
21034 If ERROR is non-nil, throw an error, otherwise just return nil."
21035 (if (memq org-agenda-type types)
21037 (if error
21038 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
21039 nil)))
21041 (defun org-agenda-quit ()
21042 "Exit agenda by removing the window or the buffer."
21043 (interactive)
21044 (let ((buf (current-buffer)))
21045 (if (not (one-window-p)) (delete-window))
21046 (kill-buffer buf)
21047 (org-agenda-maybe-reset-markers 'force)
21048 (org-columns-remove-overlays))
21049 ;; Maybe restore the pre-agenda window configuration.
21050 (and org-agenda-restore-windows-after-quit
21051 (not (eq org-agenda-window-setup 'other-frame))
21052 org-pre-agenda-window-conf
21053 (set-window-configuration org-pre-agenda-window-conf)))
21055 (defun org-agenda-exit ()
21056 "Exit agenda by removing the window or the buffer.
21057 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
21058 Org-mode buffers visited directly by the user will not be touched."
21059 (interactive)
21060 (org-release-buffers org-agenda-new-buffers)
21061 (setq org-agenda-new-buffers nil)
21062 (org-agenda-quit))
21064 (defun org-agenda-execute (arg)
21065 "Execute another agenda command, keeping same window.\\<global-map>
21066 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
21067 (interactive "P")
21068 (let ((org-agenda-window-setup 'current-window))
21069 (org-agenda arg)))
21071 (defun org-save-all-org-buffers ()
21072 "Save all Org-mode buffers without user confirmation."
21073 (interactive)
21074 (message "Saving all Org-mode buffers...")
21075 (save-some-buffers t 'org-mode-p)
21076 (message "Saving all Org-mode buffers... done"))
21078 (defun org-agenda-redo ()
21079 "Rebuild Agenda.
21080 When this is the global TODO list, a prefix argument will be interpreted."
21081 (interactive)
21082 (let* ((org-agenda-keep-modes t)
21083 (line (org-current-line))
21084 (window-line (- line (org-current-line (window-start))))
21085 (lprops (get 'org-agenda-redo-command 'org-lprops)))
21086 (message "Rebuilding agenda buffer...")
21087 (org-let lprops '(eval org-agenda-redo-command))
21088 (setq org-agenda-undo-list nil
21089 org-agenda-pending-undo-list nil)
21090 (message "Rebuilding agenda buffer...done")
21091 (goto-line line)
21092 (recenter window-line)))
21094 (defun org-agenda-goto-date (date)
21095 "Jump to DATE in agenda."
21096 (interactive (list (org-read-date)))
21097 (org-agenda-list nil date))
21099 (defun org-agenda-goto-today ()
21100 "Go to today."
21101 (interactive)
21102 (org-agenda-check-type t 'timeline 'agenda)
21103 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
21104 (cond
21105 (tdpos (goto-char tdpos))
21106 ((eq org-agenda-type 'agenda)
21107 (let* ((sd (time-to-days
21108 (time-subtract (current-time)
21109 (list 0 (* 3600 org-extend-today-until) 0))))
21110 (comp (org-agenda-compute-time-span sd org-agenda-span))
21111 (org-agenda-overriding-arguments org-agenda-last-arguments))
21112 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
21113 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
21114 (org-agenda-redo)
21115 (org-agenda-find-same-or-today-or-agenda)))
21116 (t (error "Cannot find today")))))
21118 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
21119 (goto-char
21120 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
21121 (text-property-any (point-min) (point-max) 'org-today t)
21122 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
21123 (point-min))))
21125 (defun org-agenda-later (arg)
21126 "Go forward in time by thee current span.
21127 With prefix ARG, go forward that many times the current span."
21128 (interactive "p")
21129 (org-agenda-check-type t 'agenda)
21130 (let* ((span org-agenda-span)
21131 (sd org-starting-day)
21132 (greg (calendar-gregorian-from-absolute sd))
21133 (cnt (get-text-property (point) 'org-day-cnt))
21134 greg2 nd)
21135 (cond
21136 ((eq span 'day)
21137 (setq sd (+ arg sd) nd 1))
21138 ((eq span 'week)
21139 (setq sd (+ (* 7 arg) sd) nd 7))
21140 ((eq span 'month)
21141 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
21142 sd (calendar-absolute-from-gregorian greg2))
21143 (setcar greg2 (1+ (car greg2)))
21144 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
21145 ((eq span 'year)
21146 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
21147 sd (calendar-absolute-from-gregorian greg2))
21148 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
21149 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
21150 (let ((org-agenda-overriding-arguments
21151 (list (car org-agenda-last-arguments) sd nd t)))
21152 (org-agenda-redo)
21153 (org-agenda-find-same-or-today-or-agenda cnt))))
21155 (defun org-agenda-earlier (arg)
21156 "Go backward in time by the current span.
21157 With prefix ARG, go backward that many times the current span."
21158 (interactive "p")
21159 (org-agenda-later (- arg)))
21161 (defun org-agenda-day-view ()
21162 "Switch to daily view for agenda."
21163 (interactive)
21164 (setq org-agenda-ndays 1)
21165 (org-agenda-change-time-span 'day))
21166 (defun org-agenda-week-view ()
21167 "Switch to daily view for agenda."
21168 (interactive)
21169 (setq org-agenda-ndays 7)
21170 (org-agenda-change-time-span 'week))
21171 (defun org-agenda-month-view ()
21172 "Switch to daily view for agenda."
21173 (interactive)
21174 (org-agenda-change-time-span 'month))
21175 (defun org-agenda-year-view ()
21176 "Switch to daily view for agenda."
21177 (interactive)
21178 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
21179 (org-agenda-change-time-span 'year)
21180 (error "Abort")))
21182 (defun org-agenda-change-time-span (span)
21183 "Change the agenda view to SPAN.
21184 SPAN may be `day', `week', `month', `year'."
21185 (org-agenda-check-type t 'agenda)
21186 (if (equal org-agenda-span span)
21187 (error "Viewing span is already \"%s\"" span))
21188 (let* ((sd (or (get-text-property (point) 'day)
21189 org-starting-day))
21190 (computed (org-agenda-compute-time-span sd span))
21191 (org-agenda-overriding-arguments
21192 (list (car org-agenda-last-arguments)
21193 (car computed) (cdr computed) t)))
21194 (org-agenda-redo)
21195 (org-agenda-find-same-or-today-or-agenda))
21196 (org-agenda-set-mode-name)
21197 (message "Switched to %s view" span))
21199 (defun org-agenda-compute-time-span (sd span)
21200 "Compute starting date and number of days for agenda.
21201 SPAN may be `day', `week', `month', `year'. The return value
21202 is a cons cell with the starting date and the number of days,
21203 so that the date SD will be in that range."
21204 (let* ((greg (calendar-gregorian-from-absolute sd))
21206 (cond
21207 ((eq span 'day)
21208 (setq nd 1))
21209 ((eq span 'week)
21210 (let* ((nt (calendar-day-of-week
21211 (calendar-gregorian-from-absolute sd)))
21212 (d (if org-agenda-start-on-weekday
21213 (- nt org-agenda-start-on-weekday)
21214 0)))
21215 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
21216 (setq nd 7)))
21217 ((eq span 'month)
21218 (setq sd (calendar-absolute-from-gregorian
21219 (list (car greg) 1 (nth 2 greg)))
21220 nd (- (calendar-absolute-from-gregorian
21221 (list (1+ (car greg)) 1 (nth 2 greg)))
21222 sd)))
21223 ((eq span 'year)
21224 (setq sd (calendar-absolute-from-gregorian
21225 (list 1 1 (nth 2 greg)))
21226 nd (- (calendar-absolute-from-gregorian
21227 (list 1 1 (1+ (nth 2 greg))))
21228 sd))))
21229 (cons sd nd)))
21231 ;; FIXME: does not work if user makes date format that starts with a blank
21232 (defun org-agenda-next-date-line (&optional arg)
21233 "Jump to the next line indicating a date in agenda buffer."
21234 (interactive "p")
21235 (org-agenda-check-type t 'agenda 'timeline)
21236 (beginning-of-line 1)
21237 (if (looking-at "^\\S-") (forward-char 1))
21238 (if (not (re-search-forward "^\\S-" nil t arg))
21239 (progn
21240 (backward-char 1)
21241 (error "No next date after this line in this buffer")))
21242 (goto-char (match-beginning 0)))
21244 (defun org-agenda-previous-date-line (&optional arg)
21245 "Jump to the previous line indicating a date in agenda buffer."
21246 (interactive "p")
21247 (org-agenda-check-type t 'agenda 'timeline)
21248 (beginning-of-line 1)
21249 (if (not (re-search-backward "^\\S-" nil t arg))
21250 (error "No previous date before this line in this buffer")))
21252 ;; Initialize the highlight
21253 (defvar org-hl (org-make-overlay 1 1))
21254 (org-overlay-put org-hl 'face 'highlight)
21256 (defun org-highlight (begin end &optional buffer)
21257 "Highlight a region with overlay."
21258 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
21259 org-hl begin end (or buffer (current-buffer))))
21261 (defun org-unhighlight ()
21262 "Detach overlay INDEX."
21263 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
21265 ;; FIXME this is currently not used.
21266 (defun org-highlight-until-next-command (beg end &optional buffer)
21267 (org-highlight beg end buffer)
21268 (add-hook 'pre-command-hook 'org-unhighlight-once))
21269 (defun org-unhighlight-once ()
21270 (remove-hook 'pre-command-hook 'org-unhighlight-once)
21271 (org-unhighlight))
21273 (defun org-agenda-follow-mode ()
21274 "Toggle follow mode in an agenda buffer."
21275 (interactive)
21276 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
21277 (org-agenda-set-mode-name)
21278 (message "Follow mode is %s"
21279 (if org-agenda-follow-mode "on" "off")))
21281 (defun org-agenda-log-mode ()
21282 "Toggle log mode in an agenda buffer."
21283 (interactive)
21284 (org-agenda-check-type t 'agenda 'timeline)
21285 (setq org-agenda-show-log (not org-agenda-show-log))
21286 (org-agenda-set-mode-name)
21287 (org-agenda-redo)
21288 (message "Log mode is %s"
21289 (if org-agenda-show-log "on" "off")))
21291 (defun org-agenda-toggle-diary ()
21292 "Toggle diary inclusion in an agenda buffer."
21293 (interactive)
21294 (org-agenda-check-type t 'agenda)
21295 (setq org-agenda-include-diary (not org-agenda-include-diary))
21296 (org-agenda-redo)
21297 (org-agenda-set-mode-name)
21298 (message "Diary inclusion turned %s"
21299 (if org-agenda-include-diary "on" "off")))
21301 (defun org-agenda-toggle-time-grid ()
21302 "Toggle time grid in an agenda buffer."
21303 (interactive)
21304 (org-agenda-check-type t 'agenda)
21305 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
21306 (org-agenda-redo)
21307 (org-agenda-set-mode-name)
21308 (message "Time-grid turned %s"
21309 (if org-agenda-use-time-grid "on" "off")))
21311 (defun org-agenda-set-mode-name ()
21312 "Set the mode name to indicate all the small mode settings."
21313 (setq mode-name
21314 (concat "Org-Agenda"
21315 (if (equal org-agenda-ndays 1) " Day" "")
21316 (if (equal org-agenda-ndays 7) " Week" "")
21317 (if org-agenda-follow-mode " Follow" "")
21318 (if org-agenda-include-diary " Diary" "")
21319 (if org-agenda-use-time-grid " Grid" "")
21320 (if org-agenda-show-log " Log" "")))
21321 (force-mode-line-update))
21323 (defun org-agenda-post-command-hook ()
21324 (and (eolp) (not (bolp)) (backward-char 1))
21325 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
21326 (if (and org-agenda-follow-mode
21327 (get-text-property (point) 'org-marker))
21328 (org-agenda-show)))
21330 (defun org-agenda-show-priority ()
21331 "Show the priority of the current item.
21332 This priority is composed of the main priority given with the [#A] cookies,
21333 and by additional input from the age of a schedules or deadline entry."
21334 (interactive)
21335 (let* ((pri (get-text-property (point-at-bol) 'priority)))
21336 (message "Priority is %d" (if pri pri -1000))))
21338 (defun org-agenda-show-tags ()
21339 "Show the tags applicable to the current item."
21340 (interactive)
21341 (let* ((tags (get-text-property (point-at-bol) 'tags)))
21342 (if tags
21343 (message "Tags are :%s:"
21344 (org-no-properties (mapconcat 'identity tags ":")))
21345 (message "No tags associated with this line"))))
21347 (defun org-agenda-goto (&optional highlight)
21348 "Go to the Org-mode file which contains the item at point."
21349 (interactive)
21350 (let* ((marker (or (get-text-property (point) 'org-marker)
21351 (org-agenda-error)))
21352 (buffer (marker-buffer marker))
21353 (pos (marker-position marker)))
21354 (switch-to-buffer-other-window buffer)
21355 (widen)
21356 (goto-char pos)
21357 (when (org-mode-p)
21358 (org-show-context 'agenda)
21359 (save-excursion
21360 (and (outline-next-heading)
21361 (org-flag-heading nil)))) ; show the next heading
21362 (run-hooks 'org-agenda-after-show-hook)
21363 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
21365 (defvar org-agenda-after-show-hook nil
21366 "Normal hook run after an item has been shown from the agenda.
21367 Point is in the buffer where the item originated.")
21369 (defun org-agenda-kill ()
21370 "Kill the entry or subtree belonging to the current agenda entry."
21371 (interactive)
21372 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21373 (let* ((marker (or (get-text-property (point) 'org-marker)
21374 (org-agenda-error)))
21375 (buffer (marker-buffer marker))
21376 (pos (marker-position marker))
21377 (type (get-text-property (point) 'type))
21378 dbeg dend (n 0) conf)
21379 (org-with-remote-undo buffer
21380 (with-current-buffer buffer
21381 (save-excursion
21382 (goto-char pos)
21383 (if (and (org-mode-p) (not (member type '("sexp"))))
21384 (setq dbeg (progn (org-back-to-heading t) (point))
21385 dend (org-end-of-subtree t t))
21386 (setq dbeg (point-at-bol)
21387 dend (min (point-max) (1+ (point-at-eol)))))
21388 (goto-char dbeg)
21389 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
21390 (setq conf (or (eq t org-agenda-confirm-kill)
21391 (and (numberp org-agenda-confirm-kill)
21392 (> n org-agenda-confirm-kill))))
21393 (and conf
21394 (not (y-or-n-p
21395 (format "Delete entry with %d lines in buffer \"%s\"? "
21396 n (buffer-name buffer))))
21397 (error "Abort"))
21398 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
21399 (with-current-buffer buffer (delete-region dbeg dend))
21400 (message "Agenda item and source killed"))))
21402 (defun org-agenda-archive ()
21403 "Kill the entry or subtree belonging to the current agenda entry."
21404 (interactive)
21405 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
21406 (let* ((marker (or (get-text-property (point) 'org-marker)
21407 (org-agenda-error)))
21408 (buffer (marker-buffer marker))
21409 (pos (marker-position marker)))
21410 (org-with-remote-undo buffer
21411 (with-current-buffer buffer
21412 (if (org-mode-p)
21413 (save-excursion
21414 (goto-char pos)
21415 (org-remove-subtree-entries-from-agenda)
21416 (org-back-to-heading t)
21417 (org-archive-subtree))
21418 (error "Archiving works only in Org-mode files"))))))
21420 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
21421 "Remove all lines in the agenda that correspond to a given subtree.
21422 The subtree is the one in buffer BUF, starting at BEG and ending at END.
21423 If this information is not given, the function uses the tree at point."
21424 (let ((buf (or buf (current-buffer))) m p)
21425 (save-excursion
21426 (unless (and beg end)
21427 (org-back-to-heading t)
21428 (setq beg (point))
21429 (org-end-of-subtree t)
21430 (setq end (point)))
21431 (set-buffer (get-buffer org-agenda-buffer-name))
21432 (save-excursion
21433 (goto-char (point-max))
21434 (beginning-of-line 1)
21435 (while (not (bobp))
21436 (when (and (setq m (get-text-property (point) 'org-marker))
21437 (equal buf (marker-buffer m))
21438 (setq p (marker-position m))
21439 (>= p beg)
21440 (<= p end))
21441 (let ((inhibit-read-only t))
21442 (delete-region (point-at-bol) (1+ (point-at-eol)))))
21443 (beginning-of-line 0))))))
21445 (defun org-agenda-open-link ()
21446 "Follow the link in the current line, if any."
21447 (interactive)
21448 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
21449 (save-excursion
21450 (save-restriction
21451 (narrow-to-region (point-at-bol) (point-at-eol))
21452 (org-open-at-point))))
21454 (defun org-agenda-copy-local-variable (var)
21455 "Get a variable from a referenced buffer and install it here."
21456 (let ((m (get-text-property (point) 'org-marker)))
21457 (when (and m (buffer-live-p (marker-buffer m)))
21458 (org-set-local var (with-current-buffer (marker-buffer m)
21459 (symbol-value var))))))
21461 (defun org-agenda-switch-to (&optional delete-other-windows)
21462 "Go to the Org-mode file which contains the item at point."
21463 (interactive)
21464 (let* ((marker (or (get-text-property (point) 'org-marker)
21465 (org-agenda-error)))
21466 (buffer (marker-buffer marker))
21467 (pos (marker-position marker)))
21468 (switch-to-buffer buffer)
21469 (and delete-other-windows (delete-other-windows))
21470 (widen)
21471 (goto-char pos)
21472 (when (org-mode-p)
21473 (org-show-context 'agenda)
21474 (save-excursion
21475 (and (outline-next-heading)
21476 (org-flag-heading nil)))))) ; show the next heading
21478 (defun org-agenda-goto-mouse (ev)
21479 "Go to the Org-mode file which contains the item at the mouse click."
21480 (interactive "e")
21481 (mouse-set-point ev)
21482 (org-agenda-goto))
21484 (defun org-agenda-show ()
21485 "Display the Org-mode file which contains the item at point."
21486 (interactive)
21487 (let ((win (selected-window)))
21488 (org-agenda-goto t)
21489 (select-window win)))
21491 (defun org-agenda-recenter (arg)
21492 "Display the Org-mode file which contains the item at point and recenter."
21493 (interactive "P")
21494 (let ((win (selected-window)))
21495 (org-agenda-goto t)
21496 (recenter arg)
21497 (select-window win)))
21499 (defun org-agenda-show-mouse (ev)
21500 "Display the Org-mode file which contains the item at the mouse click."
21501 (interactive "e")
21502 (mouse-set-point ev)
21503 (org-agenda-show))
21505 (defun org-agenda-check-no-diary ()
21506 "Check if the entry is a diary link and abort if yes."
21507 (if (get-text-property (point) 'org-agenda-diary-link)
21508 (org-agenda-error)))
21510 (defun org-agenda-error ()
21511 (error "Command not allowed in this line"))
21513 (defun org-agenda-tree-to-indirect-buffer ()
21514 "Show the subtree corresponding to the current entry in an indirect buffer.
21515 This calls the command `org-tree-to-indirect-buffer' from the original
21516 Org-mode buffer.
21517 With numerical prefix arg ARG, go up to this level and then take that tree.
21518 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
21519 dedicated frame)."
21520 (interactive)
21521 (org-agenda-check-no-diary)
21522 (let* ((marker (or (get-text-property (point) 'org-marker)
21523 (org-agenda-error)))
21524 (buffer (marker-buffer marker))
21525 (pos (marker-position marker)))
21526 (with-current-buffer buffer
21527 (save-excursion
21528 (goto-char pos)
21529 (call-interactively 'org-tree-to-indirect-buffer)))))
21531 (defvar org-last-heading-marker (make-marker)
21532 "Marker pointing to the headline that last changed its TODO state
21533 by a remote command from the agenda.")
21535 (defun org-agenda-todo-nextset ()
21536 "Switch TODO entry to next sequence."
21537 (interactive)
21538 (org-agenda-todo 'nextset))
21540 (defun org-agenda-todo-previousset ()
21541 "Switch TODO entry to previous sequence."
21542 (interactive)
21543 (org-agenda-todo 'previousset))
21545 (defun org-agenda-todo (&optional arg)
21546 "Cycle TODO state of line at point, also in Org-mode file.
21547 This changes the line at point, all other lines in the agenda referring to
21548 the same tree node, and the headline of the tree node in the Org-mode file."
21549 (interactive "P")
21550 (org-agenda-check-no-diary)
21551 (let* ((col (current-column))
21552 (marker (or (get-text-property (point) 'org-marker)
21553 (org-agenda-error)))
21554 (buffer (marker-buffer marker))
21555 (pos (marker-position marker))
21556 (hdmarker (get-text-property (point) 'org-hd-marker))
21557 (inhibit-read-only t)
21558 newhead)
21559 (org-with-remote-undo buffer
21560 (with-current-buffer buffer
21561 (widen)
21562 (goto-char pos)
21563 (org-show-context 'agenda)
21564 (save-excursion
21565 (and (outline-next-heading)
21566 (org-flag-heading nil))) ; show the next heading
21567 (org-todo arg)
21568 (and (bolp) (forward-char 1))
21569 (setq newhead (org-get-heading))
21570 (save-excursion
21571 (org-back-to-heading)
21572 (move-marker org-last-heading-marker (point))))
21573 (beginning-of-line 1)
21574 (save-excursion
21575 (org-agenda-change-all-lines newhead hdmarker 'fixface))
21576 (move-to-column col))))
21578 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
21579 "Change all lines in the agenda buffer which match HDMARKER.
21580 The new content of the line will be NEWHEAD (as modified by
21581 `org-format-agenda-item'). HDMARKER is checked with
21582 `equal' against all `org-hd-marker' text properties in the file.
21583 If FIXFACE is non-nil, the face of each item is modified acording to
21584 the new TODO state."
21585 (let* ((inhibit-read-only t)
21586 props m pl undone-face done-face finish new dotime cat tags)
21587 (save-excursion
21588 (goto-char (point-max))
21589 (beginning-of-line 1)
21590 (while (not finish)
21591 (setq finish (bobp))
21592 (when (and (setq m (get-text-property (point) 'org-hd-marker))
21593 (equal m hdmarker))
21594 (setq props (text-properties-at (point))
21595 dotime (get-text-property (point) 'dotime)
21596 cat (get-text-property (point) 'org-category)
21597 tags (get-text-property (point) 'tags)
21598 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
21599 pl (get-text-property (point) 'prefix-length)
21600 undone-face (get-text-property (point) 'undone-face)
21601 done-face (get-text-property (point) 'done-face))
21602 (move-to-column pl)
21603 (cond
21604 ((equal new "")
21605 (beginning-of-line 1)
21606 (and (looking-at ".*\n?") (replace-match "")))
21607 ((looking-at ".*")
21608 (replace-match new t t)
21609 (beginning-of-line 1)
21610 (add-text-properties (point-at-bol) (point-at-eol) props)
21611 (when fixface
21612 (add-text-properties
21613 (point-at-bol) (point-at-eol)
21614 (list 'face
21615 (if org-last-todo-state-is-todo
21616 undone-face done-face))))
21617 (org-agenda-highlight-todo 'line)
21618 (beginning-of-line 1))
21619 (t (error "Line update did not work"))))
21620 (beginning-of-line 0)))
21621 (org-finalize-agenda)))
21623 (defun org-agenda-align-tags (&optional line)
21624 "Align all tags in agenda items to `org-agenda-tags-column'."
21625 (let ((inhibit-read-only t) l c)
21626 (save-excursion
21627 (goto-char (if line (point-at-bol) (point-min)))
21628 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
21629 (if line (point-at-eol) nil) t)
21630 (add-text-properties
21631 (match-beginning 2) (match-end 2)
21632 (list 'face (list 'org-tag (get-text-property
21633 (match-beginning 2) 'face))))
21634 (setq l (- (match-end 2) (match-beginning 2))
21635 c (if (< org-agenda-tags-column 0)
21636 (- (abs org-agenda-tags-column) l)
21637 org-agenda-tags-column))
21638 (delete-region (match-beginning 1) (match-end 1))
21639 (goto-char (match-beginning 1))
21640 (insert (org-add-props
21641 (make-string (max 1 (- c (current-column))) ?\ )
21642 (text-properties-at (point))))))))
21644 (defun org-agenda-priority-up ()
21645 "Increase the priority of line at point, also in Org-mode file."
21646 (interactive)
21647 (org-agenda-priority 'up))
21649 (defun org-agenda-priority-down ()
21650 "Decrease the priority of line at point, also in Org-mode file."
21651 (interactive)
21652 (org-agenda-priority 'down))
21654 (defun org-agenda-priority (&optional force-direction)
21655 "Set the priority of line at point, also in Org-mode file.
21656 This changes the line at point, all other lines in the agenda referring to
21657 the same tree node, and the headline of the tree node in the Org-mode file."
21658 (interactive)
21659 (org-agenda-check-no-diary)
21660 (let* ((marker (or (get-text-property (point) 'org-marker)
21661 (org-agenda-error)))
21662 (hdmarker (get-text-property (point) 'org-hd-marker))
21663 (buffer (marker-buffer hdmarker))
21664 (pos (marker-position hdmarker))
21665 (inhibit-read-only t)
21666 newhead)
21667 (org-with-remote-undo buffer
21668 (with-current-buffer buffer
21669 (widen)
21670 (goto-char pos)
21671 (org-show-context 'agenda)
21672 (save-excursion
21673 (and (outline-next-heading)
21674 (org-flag-heading nil))) ; show the next heading
21675 (funcall 'org-priority force-direction)
21676 (end-of-line 1)
21677 (setq newhead (org-get-heading)))
21678 (org-agenda-change-all-lines newhead hdmarker)
21679 (beginning-of-line 1))))
21681 (defun org-get-tags-at (&optional pos)
21682 "Get a list of all headline tags applicable at POS.
21683 POS defaults to point. If tags are inherited, the list contains
21684 the targets in the same sequence as the headlines appear, i.e.
21685 the tags of the current headline come last."
21686 (interactive)
21687 (let (tags lastpos)
21688 (save-excursion
21689 (save-restriction
21690 (widen)
21691 (goto-char (or pos (point)))
21692 (save-match-data
21693 (org-back-to-heading t)
21694 (condition-case nil
21695 (while (not (equal lastpos (point)))
21696 (setq lastpos (point))
21697 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
21698 (setq tags (append (org-split-string
21699 (org-match-string-no-properties 1) ":")
21700 tags)))
21701 (or org-use-tag-inheritance (error ""))
21702 (org-up-heading-all 1))
21703 (error nil))))
21704 tags)))
21706 ;; FIXME: should fix the tags property of the agenda line.
21707 (defun org-agenda-set-tags ()
21708 "Set tags for the current headline."
21709 (interactive)
21710 (org-agenda-check-no-diary)
21711 (if (and (org-region-active-p) (interactive-p))
21712 (call-interactively 'org-change-tag-in-region)
21713 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21714 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21715 (org-agenda-error)))
21716 (buffer (marker-buffer hdmarker))
21717 (pos (marker-position hdmarker))
21718 (inhibit-read-only t)
21719 newhead)
21720 (org-with-remote-undo buffer
21721 (with-current-buffer buffer
21722 (widen)
21723 (goto-char pos)
21724 (save-excursion
21725 (org-show-context 'agenda))
21726 (save-excursion
21727 (and (outline-next-heading)
21728 (org-flag-heading nil))) ; show the next heading
21729 (goto-char pos)
21730 (call-interactively 'org-set-tags)
21731 (end-of-line 1)
21732 (setq newhead (org-get-heading)))
21733 (org-agenda-change-all-lines newhead hdmarker)
21734 (beginning-of-line 1)))))
21736 (defun org-agenda-toggle-archive-tag ()
21737 "Toggle the archive tag for the current entry."
21738 (interactive)
21739 (org-agenda-check-no-diary)
21740 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
21741 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
21742 (org-agenda-error)))
21743 (buffer (marker-buffer hdmarker))
21744 (pos (marker-position hdmarker))
21745 (inhibit-read-only t)
21746 newhead)
21747 (org-with-remote-undo buffer
21748 (with-current-buffer buffer
21749 (widen)
21750 (goto-char pos)
21751 (org-show-context 'agenda)
21752 (save-excursion
21753 (and (outline-next-heading)
21754 (org-flag-heading nil))) ; show the next heading
21755 (call-interactively 'org-toggle-archive-tag)
21756 (end-of-line 1)
21757 (setq newhead (org-get-heading)))
21758 (org-agenda-change-all-lines newhead hdmarker)
21759 (beginning-of-line 1))))
21761 (defun org-agenda-date-later (arg &optional what)
21762 "Change the date of this item to one day later."
21763 (interactive "p")
21764 (org-agenda-check-type t 'agenda 'timeline)
21765 (org-agenda-check-no-diary)
21766 (let* ((marker (or (get-text-property (point) 'org-marker)
21767 (org-agenda-error)))
21768 (buffer (marker-buffer marker))
21769 (pos (marker-position marker)))
21770 (org-with-remote-undo buffer
21771 (with-current-buffer buffer
21772 (widen)
21773 (goto-char pos)
21774 (if (not (org-at-timestamp-p))
21775 (error "Cannot find time stamp"))
21776 (org-timestamp-change arg (or what 'day)))
21777 (org-agenda-show-new-time marker org-last-changed-timestamp))
21778 (message "Time stamp changed to %s" org-last-changed-timestamp)))
21780 (defun org-agenda-date-earlier (arg &optional what)
21781 "Change the date of this item to one day earlier."
21782 (interactive "p")
21783 (org-agenda-date-later (- arg) what))
21785 (defun org-agenda-show-new-time (marker stamp &optional prefix)
21786 "Show new date stamp via text properties."
21787 ;; We use text properties to make this undoable
21788 (let ((inhibit-read-only t))
21789 (setq stamp (concat " " prefix " => " stamp))
21790 (save-excursion
21791 (goto-char (point-max))
21792 (while (not (bobp))
21793 (when (equal marker (get-text-property (point) 'org-marker))
21794 (move-to-column (- (window-width) (length stamp)) t)
21795 (if (featurep 'xemacs)
21796 ;; Use `duplicable' property to trigger undo recording
21797 (let ((ex (make-extent nil nil))
21798 (gl (make-glyph stamp)))
21799 (set-glyph-face gl 'secondary-selection)
21800 (set-extent-properties
21801 ex (list 'invisible t 'end-glyph gl 'duplicable t))
21802 (insert-extent ex (1- (point)) (point-at-eol)))
21803 (add-text-properties
21804 (1- (point)) (point-at-eol)
21805 (list 'display (org-add-props stamp nil
21806 'face 'secondary-selection))))
21807 (beginning-of-line 1))
21808 (beginning-of-line 0)))))
21810 (defun org-agenda-date-prompt (arg)
21811 "Change the date of this item. Date is prompted for, with default today.
21812 The prefix ARG is passed to the `org-time-stamp' command and can therefore
21813 be used to request time specification in the time stamp."
21814 (interactive "P")
21815 (org-agenda-check-type t 'agenda 'timeline)
21816 (org-agenda-check-no-diary)
21817 (let* ((marker (or (get-text-property (point) 'org-marker)
21818 (org-agenda-error)))
21819 (buffer (marker-buffer marker))
21820 (pos (marker-position marker)))
21821 (org-with-remote-undo buffer
21822 (with-current-buffer buffer
21823 (widen)
21824 (goto-char pos)
21825 (if (not (org-at-timestamp-p))
21826 (error "Cannot find time stamp"))
21827 (org-time-stamp arg)
21828 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
21830 (defun org-agenda-schedule (arg)
21831 "Schedule the item at point."
21832 (interactive "P")
21833 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21834 (org-agenda-check-no-diary)
21835 (let* ((marker (or (get-text-property (point) 'org-marker)
21836 (org-agenda-error)))
21837 (buffer (marker-buffer marker))
21838 (pos (marker-position marker))
21839 (org-insert-labeled-timestamps-at-point nil)
21841 (org-with-remote-undo buffer
21842 (with-current-buffer buffer
21843 (widen)
21844 (goto-char pos)
21845 (setq ts (org-schedule arg)))
21846 (org-agenda-show-new-time marker ts "S"))
21847 (message "Item scheduled for %s" ts)))
21849 (defun org-agenda-deadline (arg)
21850 "Schedule the item at point."
21851 (interactive "P")
21852 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
21853 (org-agenda-check-no-diary)
21854 (let* ((marker (or (get-text-property (point) 'org-marker)
21855 (org-agenda-error)))
21856 (buffer (marker-buffer marker))
21857 (pos (marker-position marker))
21858 (org-insert-labeled-timestamps-at-point nil)
21860 (org-with-remote-undo buffer
21861 (with-current-buffer buffer
21862 (widen)
21863 (goto-char pos)
21864 (setq ts (org-deadline arg)))
21865 (org-agenda-show-new-time marker ts "S"))
21866 (message "Deadline for this item set to %s" ts)))
21868 (defun org-get-heading (&optional no-tags)
21869 "Return the heading of the current entry, without the stars."
21870 (save-excursion
21871 (org-back-to-heading t)
21872 (if (looking-at
21873 (if no-tags
21874 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
21875 "\\*+[ \t]+\\([^\r\n]*\\)"))
21876 (match-string 1) "")))
21878 (defun org-agenda-clock-in (&optional arg)
21879 "Start the clock on the currently selected item."
21880 (interactive "P")
21881 (org-agenda-check-no-diary)
21882 (let* ((marker (or (get-text-property (point) 'org-marker)
21883 (org-agenda-error)))
21884 (pos (marker-position marker)))
21885 (org-with-remote-undo (marker-buffer marker)
21886 (with-current-buffer (marker-buffer marker)
21887 (widen)
21888 (goto-char pos)
21889 (org-clock-in)))))
21891 (defun org-agenda-clock-out (&optional arg)
21892 "Stop the currently running clock."
21893 (interactive "P")
21894 (unless (marker-buffer org-clock-marker)
21895 (error "No running clock"))
21896 (org-with-remote-undo (marker-buffer org-clock-marker)
21897 (org-clock-out)))
21899 (defun org-agenda-clock-cancel (&optional arg)
21900 "Cancel the currently running clock."
21901 (interactive "P")
21902 (unless (marker-buffer org-clock-marker)
21903 (error "No running clock"))
21904 (org-with-remote-undo (marker-buffer org-clock-marker)
21905 (org-clock-cancel)))
21907 (defun org-agenda-diary-entry ()
21908 "Make a diary entry, like the `i' command from the calendar.
21909 All the standard commands work: block, weekly etc."
21910 (interactive)
21911 (org-agenda-check-type t 'agenda 'timeline)
21912 (require 'diary-lib)
21913 (let* ((char (progn
21914 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
21915 (read-char-exclusive)))
21916 (cmd (cdr (assoc char
21917 '((?d . insert-diary-entry)
21918 (?w . insert-weekly-diary-entry)
21919 (?m . insert-monthly-diary-entry)
21920 (?y . insert-yearly-diary-entry)
21921 (?a . insert-anniversary-diary-entry)
21922 (?b . insert-block-diary-entry)
21923 (?c . insert-cyclic-diary-entry)))))
21924 (oldf (symbol-function 'calendar-cursor-to-date))
21925 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
21926 (point (point))
21927 (mark (or (mark t) (point))))
21928 (unless cmd
21929 (error "No command associated with <%c>" char))
21930 (unless (and (get-text-property point 'day)
21931 (or (not (equal ?b char))
21932 (get-text-property mark 'day)))
21933 (error "Don't know which date to use for diary entry"))
21934 ;; We implement this by hacking the `calendar-cursor-to-date' function
21935 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
21936 (let ((calendar-mark-ring
21937 (list (calendar-gregorian-from-absolute
21938 (or (get-text-property mark 'day)
21939 (get-text-property point 'day))))))
21940 (unwind-protect
21941 (progn
21942 (fset 'calendar-cursor-to-date
21943 (lambda (&optional error)
21944 (calendar-gregorian-from-absolute
21945 (get-text-property point 'day))))
21946 (call-interactively cmd))
21947 (fset 'calendar-cursor-to-date oldf)))))
21950 (defun org-agenda-execute-calendar-command (cmd)
21951 "Execute a calendar command from the agenda, with the date associated to
21952 the cursor position."
21953 (org-agenda-check-type t 'agenda 'timeline)
21954 (require 'diary-lib)
21955 (unless (get-text-property (point) 'day)
21956 (error "Don't know which date to use for calendar command"))
21957 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
21958 (point (point))
21959 (date (calendar-gregorian-from-absolute
21960 (get-text-property point 'day)))
21961 ;; the following 3 vars are needed in the calendar
21962 (displayed-day (extract-calendar-day date))
21963 (displayed-month (extract-calendar-month date))
21964 (displayed-year (extract-calendar-year date)))
21965 (unwind-protect
21966 (progn
21967 (fset 'calendar-cursor-to-date
21968 (lambda (&optional error)
21969 (calendar-gregorian-from-absolute
21970 (get-text-property point 'day))))
21971 (call-interactively cmd))
21972 (fset 'calendar-cursor-to-date oldf))))
21974 (defun org-agenda-phases-of-moon ()
21975 "Display the phases of the moon for the 3 months around the cursor date."
21976 (interactive)
21977 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
21979 (defun org-agenda-holidays ()
21980 "Display the holidays for the 3 months around the cursor date."
21981 (interactive)
21982 (org-agenda-execute-calendar-command 'list-calendar-holidays))
21984 (defun org-agenda-sunrise-sunset (arg)
21985 "Display sunrise and sunset for the cursor date.
21986 Latitude and longitude can be specified with the variables
21987 `calendar-latitude' and `calendar-longitude'. When called with prefix
21988 argument, latitude and longitude will be prompted for."
21989 (interactive "P")
21990 (let ((calendar-longitude (if arg nil calendar-longitude))
21991 (calendar-latitude (if arg nil calendar-latitude))
21992 (calendar-location-name
21993 (if arg "the given coordinates" calendar-location-name)))
21994 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
21996 (defun org-agenda-goto-calendar ()
21997 "Open the Emacs calendar with the date at the cursor."
21998 (interactive)
21999 (org-agenda-check-type t 'agenda 'timeline)
22000 (let* ((day (or (get-text-property (point) 'day)
22001 (error "Don't know which date to open in calendar")))
22002 (date (calendar-gregorian-from-absolute day))
22003 (calendar-move-hook nil)
22004 (view-calendar-holidays-initially nil)
22005 (view-diary-entries-initially nil))
22006 (calendar)
22007 (calendar-goto-date date)))
22009 (defun org-calendar-goto-agenda ()
22010 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
22011 This is a command that has to be installed in `calendar-mode-map'."
22012 (interactive)
22013 (org-agenda-list nil (calendar-absolute-from-gregorian
22014 (calendar-cursor-to-date))
22015 nil))
22017 (defun org-agenda-convert-date ()
22018 (interactive)
22019 (org-agenda-check-type t 'agenda 'timeline)
22020 (let ((day (get-text-property (point) 'day))
22021 date s)
22022 (unless day
22023 (error "Don't know which date to convert"))
22024 (setq date (calendar-gregorian-from-absolute day))
22025 (setq s (concat
22026 "Gregorian: " (calendar-date-string date) "\n"
22027 "ISO: " (calendar-iso-date-string date) "\n"
22028 "Day of Yr: " (calendar-day-of-year-string date) "\n"
22029 "Julian: " (calendar-julian-date-string date) "\n"
22030 "Astron. JD: " (calendar-astro-date-string date)
22031 " (Julian date number at noon UTC)\n"
22032 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
22033 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
22034 "French: " (calendar-french-date-string date) "\n"
22035 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
22036 "Mayan: " (calendar-mayan-date-string date) "\n"
22037 "Coptic: " (calendar-coptic-date-string date) "\n"
22038 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
22039 "Persian: " (calendar-persian-date-string date) "\n"
22040 "Chinese: " (calendar-chinese-date-string date) "\n"))
22041 (with-output-to-temp-buffer "*Dates*"
22042 (princ s))
22043 (if (fboundp 'fit-window-to-buffer)
22044 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
22047 ;;;; Embedded LaTeX
22049 (defvar org-cdlatex-mode-map (make-sparse-keymap)
22050 "Keymap for the minor `org-cdlatex-mode'.")
22052 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
22053 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
22054 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
22055 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
22056 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
22058 (defvar org-cdlatex-texmathp-advice-is-done nil
22059 "Flag remembering if we have applied the advice to texmathp already.")
22061 (define-minor-mode org-cdlatex-mode
22062 "Toggle the minor `org-cdlatex-mode'.
22063 This mode supports entering LaTeX environment and math in LaTeX fragments
22064 in Org-mode.
22065 \\{org-cdlatex-mode-map}"
22066 nil " OCDL" nil
22067 (when org-cdlatex-mode (require 'cdlatex))
22068 (unless org-cdlatex-texmathp-advice-is-done
22069 (setq org-cdlatex-texmathp-advice-is-done t)
22070 (defadvice texmathp (around org-math-always-on activate)
22071 "Always return t in org-mode buffers.
22072 This is because we want to insert math symbols without dollars even outside
22073 the LaTeX math segments. If Orgmode thinks that point is actually inside
22074 en embedded LaTeX fragement, let texmathp do its job.
22075 \\[org-cdlatex-mode-map]"
22076 (interactive)
22077 (let (p)
22078 (cond
22079 ((not (org-mode-p)) ad-do-it)
22080 ((eq this-command 'cdlatex-math-symbol)
22081 (setq ad-return-value t
22082 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
22084 (let ((p (org-inside-LaTeX-fragment-p)))
22085 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
22086 (setq ad-return-value t
22087 texmathp-why '("Org-mode embedded math" . 0))
22088 (if p ad-do-it)))))))))
22090 (defun turn-on-org-cdlatex ()
22091 "Unconditionally turn on `org-cdlatex-mode'."
22092 (org-cdlatex-mode 1))
22094 (defun org-inside-LaTeX-fragment-p ()
22095 "Test if point is inside a LaTeX fragment.
22096 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
22097 sequence appearing also before point.
22098 Even though the matchers for math are configurable, this function assumes
22099 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
22100 delimiters are skipped when they have been removed by customization.
22101 The return value is nil, or a cons cell with the delimiter and
22102 and the position of this delimiter.
22104 This function does a reasonably good job, but can locally be fooled by
22105 for example currency specifications. For example it will assume being in
22106 inline math after \"$22.34\". The LaTeX fragment formatter will only format
22107 fragments that are properly closed, but during editing, we have to live
22108 with the uncertainty caused by missing closing delimiters. This function
22109 looks only before point, not after."
22110 (catch 'exit
22111 (let ((pos (point))
22112 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
22113 (lim (progn
22114 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
22115 (point)))
22116 dd-on str (start 0) m re)
22117 (goto-char pos)
22118 (when dodollar
22119 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
22120 re (nth 1 (assoc "$" org-latex-regexps)))
22121 (while (string-match re str start)
22122 (cond
22123 ((= (match-end 0) (length str))
22124 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
22125 ((= (match-end 0) (- (length str) 5))
22126 (throw 'exit nil))
22127 (t (setq start (match-end 0))))))
22128 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
22129 (goto-char pos)
22130 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
22131 (and (match-beginning 2) (throw 'exit nil))
22132 ;; count $$
22133 (while (re-search-backward "\\$\\$" lim t)
22134 (setq dd-on (not dd-on)))
22135 (goto-char pos)
22136 (if dd-on (cons "$$" m))))))
22139 (defun org-try-cdlatex-tab ()
22140 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
22141 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
22142 - inside a LaTeX fragment, or
22143 - after the first word in a line, where an abbreviation expansion could
22144 insert a LaTeX environment."
22145 (when org-cdlatex-mode
22146 (cond
22147 ((save-excursion
22148 (skip-chars-backward "a-zA-Z0-9*")
22149 (skip-chars-backward " \t")
22150 (bolp))
22151 (cdlatex-tab) t)
22152 ((org-inside-LaTeX-fragment-p)
22153 (cdlatex-tab) t)
22154 (t nil))))
22156 (defun org-cdlatex-underscore-caret (&optional arg)
22157 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
22158 Revert to the normal definition outside of these fragments."
22159 (interactive "P")
22160 (if (org-inside-LaTeX-fragment-p)
22161 (call-interactively 'cdlatex-sub-superscript)
22162 (let (org-cdlatex-mode)
22163 (call-interactively (key-binding (vector last-input-event))))))
22165 (defun org-cdlatex-math-modify (&optional arg)
22166 "Execute `cdlatex-math-modify' in LaTeX fragments.
22167 Revert to the normal definition outside of these fragments."
22168 (interactive "P")
22169 (if (org-inside-LaTeX-fragment-p)
22170 (call-interactively 'cdlatex-math-modify)
22171 (let (org-cdlatex-mode)
22172 (call-interactively (key-binding (vector last-input-event))))))
22174 (defvar org-latex-fragment-image-overlays nil
22175 "List of overlays carrying the images of latex fragments.")
22176 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
22178 (defun org-remove-latex-fragment-image-overlays ()
22179 "Remove all overlays with LaTeX fragment images in current buffer."
22180 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
22181 (setq org-latex-fragment-image-overlays nil))
22183 (defun org-preview-latex-fragment (&optional subtree)
22184 "Preview the LaTeX fragment at point, or all locally or globally.
22185 If the cursor is in a LaTeX fragment, create the image and overlay
22186 it over the source code. If there is no fragment at point, display
22187 all fragments in the current text, from one headline to the next. With
22188 prefix SUBTREE, display all fragments in the current subtree. With a
22189 double prefix `C-u C-u', or when the cursor is before the first headline,
22190 display all fragments in the buffer.
22191 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
22192 (interactive "P")
22193 (org-remove-latex-fragment-image-overlays)
22194 (save-excursion
22195 (save-restriction
22196 (let (beg end at msg)
22197 (cond
22198 ((or (equal subtree '(16))
22199 (not (save-excursion
22200 (re-search-backward (concat "^" outline-regexp) nil t))))
22201 (setq beg (point-min) end (point-max)
22202 msg "Creating images for buffer...%s"))
22203 ((equal subtree '(4))
22204 (org-back-to-heading)
22205 (setq beg (point) end (org-end-of-subtree t)
22206 msg "Creating images for subtree...%s"))
22208 (if (setq at (org-inside-LaTeX-fragment-p))
22209 (goto-char (max (point-min) (- (cdr at) 2)))
22210 (org-back-to-heading))
22211 (setq beg (point) end (progn (outline-next-heading) (point))
22212 msg (if at "Creating image...%s"
22213 "Creating images for entry...%s"))))
22214 (message msg "")
22215 (narrow-to-region beg end)
22216 (goto-char beg)
22217 (org-format-latex
22218 (concat "ltxpng/" (file-name-sans-extension
22219 (file-name-nondirectory
22220 buffer-file-name)))
22221 default-directory 'overlays msg at 'forbuffer)
22222 (message msg "done. Use `C-c C-c' to remove images.")))))
22224 (defvar org-latex-regexps
22225 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
22226 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
22227 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
22228 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
22229 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
22230 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
22231 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
22232 "Regular expressions for matching embedded LaTeX.")
22234 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
22235 "Replace LaTeX fragments with links to an image, and produce images."
22236 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
22237 (let* ((prefixnodir (file-name-nondirectory prefix))
22238 (absprefix (expand-file-name prefix dir))
22239 (todir (file-name-directory absprefix))
22240 (opt org-format-latex-options)
22241 (matchers (plist-get opt :matchers))
22242 (re-list org-latex-regexps)
22243 (cnt 0) txt link beg end re e checkdir
22244 m n block linkfile movefile ov)
22245 ;; Check if there are old images files with this prefix, and remove them
22246 (when (file-directory-p todir)
22247 (mapc 'delete-file
22248 (directory-files
22249 todir 'full
22250 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
22251 ;; Check the different regular expressions
22252 (while (setq e (pop re-list))
22253 (setq m (car e) re (nth 1 e) n (nth 2 e)
22254 block (if (nth 3 e) "\n\n" ""))
22255 (when (member m matchers)
22256 (goto-char (point-min))
22257 (while (re-search-forward re nil t)
22258 (when (or (not at) (equal (cdr at) (match-beginning n)))
22259 (setq txt (match-string n)
22260 beg (match-beginning n) end (match-end n)
22261 cnt (1+ cnt)
22262 linkfile (format "%s_%04d.png" prefix cnt)
22263 movefile (format "%s_%04d.png" absprefix cnt)
22264 link (concat block "[[file:" linkfile "]]" block))
22265 (if msg (message msg cnt))
22266 (goto-char beg)
22267 (unless checkdir ; make sure the directory exists
22268 (setq checkdir t)
22269 (or (file-directory-p todir) (make-directory todir)))
22270 (org-create-formula-image
22271 txt movefile opt forbuffer)
22272 (if overlays
22273 (progn
22274 (setq ov (org-make-overlay beg end))
22275 (if (featurep 'xemacs)
22276 (progn
22277 (org-overlay-put ov 'invisible t)
22278 (org-overlay-put
22279 ov 'end-glyph
22280 (make-glyph (vector 'png :file movefile))))
22281 (org-overlay-put
22282 ov 'display
22283 (list 'image :type 'png :file movefile :ascent 'center)))
22284 (push ov org-latex-fragment-image-overlays)
22285 (goto-char end))
22286 (delete-region beg end)
22287 (insert link))))))))
22289 ;; This function borrows from Ganesh Swami's latex2png.el
22290 (defun org-create-formula-image (string tofile options buffer)
22291 (let* ((tmpdir (if (featurep 'xemacs)
22292 (temp-directory)
22293 temporary-file-directory))
22294 (texfilebase (make-temp-name
22295 (expand-file-name "orgtex" tmpdir)))
22296 (texfile (concat texfilebase ".tex"))
22297 (dvifile (concat texfilebase ".dvi"))
22298 (pngfile (concat texfilebase ".png"))
22299 (fnh (face-attribute 'default :height nil))
22300 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
22301 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
22302 (fg (or (plist-get options (if buffer :foreground :html-foreground))
22303 "Black"))
22304 (bg (or (plist-get options (if buffer :background :html-background))
22305 "Transparent")))
22306 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
22307 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
22308 (with-temp-file texfile
22309 (insert org-format-latex-header
22310 "\n\\begin{document}\n" string "\n\\end{document}\n"))
22311 (let ((dir default-directory))
22312 (condition-case nil
22313 (progn
22314 (cd tmpdir)
22315 (call-process "latex" nil nil nil texfile))
22316 (error nil))
22317 (cd dir))
22318 (if (not (file-exists-p dvifile))
22319 (progn (message "Failed to create dvi file from %s" texfile) nil)
22320 (call-process "dvipng" nil nil nil
22321 "-E" "-fg" fg "-bg" bg
22322 "-D" dpi
22323 ;;"-x" scale "-y" scale
22324 "-T" "tight"
22325 "-o" pngfile
22326 dvifile)
22327 (if (not (file-exists-p pngfile))
22328 (progn (message "Failed to create png file from %s" texfile) nil)
22329 ;; Use the requested file name and clean up
22330 (copy-file pngfile tofile 'replace)
22331 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
22332 (delete-file (concat texfilebase e)))
22333 pngfile))))
22335 (defun org-dvipng-color (attr)
22336 "Return an rgb color specification for dvipng."
22337 (apply 'format "rgb %s %s %s"
22338 (mapcar 'org-normalize-color
22339 (color-values (face-attribute 'default attr nil)))))
22341 (defun org-normalize-color (value)
22342 "Return string to be used as color value for an RGB component."
22343 (format "%g" (/ value 65535.0)))
22345 ;;;; Exporting
22347 ;;; Variables, constants, and parameter plists
22349 (defconst org-level-max 20)
22351 (defvar org-export-html-preamble nil
22352 "Preamble, to be inserted just after <body>. Set by publishing functions.")
22353 (defvar org-export-html-postamble nil
22354 "Preamble, to be inserted just before </body>. Set by publishing functions.")
22355 (defvar org-export-html-auto-preamble t
22356 "Should default preamble be inserted? Set by publishing functions.")
22357 (defvar org-export-html-auto-postamble t
22358 "Should default postamble be inserted? Set by publishing functions.")
22359 (defvar org-current-export-file nil) ; dynamically scoped parameter
22360 (defvar org-current-export-dir nil) ; dynamically scoped parameter
22363 (defconst org-export-plist-vars
22364 '((:language . org-export-default-language)
22365 (:customtime . org-display-custom-times)
22366 (:headline-levels . org-export-headline-levels)
22367 (:section-numbers . org-export-with-section-numbers)
22368 (:table-of-contents . org-export-with-toc)
22369 (:preserve-breaks . org-export-preserve-breaks)
22370 (:archived-trees . org-export-with-archived-trees)
22371 (:emphasize . org-export-with-emphasize)
22372 (:sub-superscript . org-export-with-sub-superscripts)
22373 (:special-strings . org-export-with-special-strings)
22374 (:footnotes . org-export-with-footnotes)
22375 (:drawers . org-export-with-drawers)
22376 (:tags . org-export-with-tags)
22377 (:TeX-macros . org-export-with-TeX-macros)
22378 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
22379 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
22380 (:fixed-width . org-export-with-fixed-width)
22381 (:timestamps . org-export-with-timestamps)
22382 (:author-info . org-export-author-info)
22383 (:time-stamp-file . org-export-time-stamp-file)
22384 (:tables . org-export-with-tables)
22385 (:table-auto-headline . org-export-highlight-first-table-line)
22386 (:style . org-export-html-style)
22387 (:agenda-style . org-agenda-export-html-style) ;; FIXME: Does this work????
22388 (:convert-org-links . org-export-html-link-org-files-as-html)
22389 (:inline-images . org-export-html-inline-images)
22390 (:html-extension . org-export-html-extension)
22391 (:html-table-tag . org-export-html-table-tag)
22392 (:expand-quoted-html . org-export-html-expand)
22393 (:timestamp . org-export-html-with-timestamp)
22394 (:publishing-directory . org-export-publishing-directory)
22395 (:preamble . org-export-html-preamble)
22396 (:postamble . org-export-html-postamble)
22397 (:auto-preamble . org-export-html-auto-preamble)
22398 (:auto-postamble . org-export-html-auto-postamble)
22399 (:author . user-full-name)
22400 (:email . user-mail-address)))
22402 (defun org-default-export-plist ()
22403 "Return the property list with default settings for the export variables."
22404 (let ((l org-export-plist-vars) rtn e)
22405 (while (setq e (pop l))
22406 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
22407 rtn))
22409 (defun org-infile-export-plist ()
22410 "Return the property list with file-local settings for export."
22411 (save-excursion
22412 (goto-char 0)
22413 (let ((re (org-make-options-regexp
22414 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
22415 p key val text options)
22416 (while (re-search-forward re nil t)
22417 (setq key (org-match-string-no-properties 1)
22418 val (org-match-string-no-properties 2))
22419 (cond
22420 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
22421 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
22422 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
22423 ((string-equal key "DATE") (setq p (plist-put p :date val)))
22424 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
22425 ((string-equal key "TEXT")
22426 (setq text (if text (concat text "\n" val) val)))
22427 ((string-equal key "OPTIONS") (setq options val))))
22428 (setq p (plist-put p :text text))
22429 (when options
22430 (let ((op '(("H" . :headline-levels)
22431 ("num" . :section-numbers)
22432 ("toc" . :table-of-contents)
22433 ("\\n" . :preserve-breaks)
22434 ("@" . :expand-quoted-html)
22435 (":" . :fixed-width)
22436 ("|" . :tables)
22437 ("^" . :sub-superscript)
22438 ("-" . :special-strings)
22439 ("f" . :footnotes)
22440 ("d" . :drawers)
22441 ("tags" . :tags)
22442 ("*" . :emphasize)
22443 ("TeX" . :TeX-macros)
22444 ("LaTeX" . :LaTeX-fragments)
22445 ("skip" . :skip-before-1st-heading)
22446 ("author" . :author-info)
22447 ("timestamp" . :time-stamp-file)))
22449 (while (setq o (pop op))
22450 (if (string-match (concat (regexp-quote (car o))
22451 ":\\([^ \t\n\r;,.]*\\)")
22452 options)
22453 (setq p (plist-put p (cdr o)
22454 (car (read-from-string
22455 (match-string 1 options)))))))))
22456 p)))
22458 (defun org-export-directory (type plist)
22459 (let* ((val (plist-get plist :publishing-directory))
22460 (dir (if (listp val)
22461 (or (cdr (assoc type val)) ".")
22462 val)))
22463 dir))
22465 (defun org-skip-comments (lines)
22466 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
22467 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
22468 (re2 "^\\(\\*+\\)[ \t\n\r]")
22469 (case-fold-search nil)
22470 rtn line level)
22471 (while (setq line (pop lines))
22472 (cond
22473 ((and (string-match re1 line)
22474 (setq level (- (match-end 1) (match-beginning 1))))
22475 ;; Beginning of a COMMENT subtree. Skip it.
22476 (while (and (setq line (pop lines))
22477 (or (not (string-match re2 line))
22478 (> (- (match-end 1) (match-beginning 1)) level))))
22479 (setq lines (cons line lines)))
22480 ((string-match "^#" line)
22481 ;; an ordinary comment line
22483 ((and org-export-table-remove-special-lines
22484 (string-match "^[ \t]*|" line)
22485 (or (string-match "^[ \t]*| *[!_^] *|" line)
22486 (and (string-match "| *<[0-9]+> *|" line)
22487 (not (string-match "| *[^ <|]" line)))))
22488 ;; a special table line that should be removed
22490 (t (setq rtn (cons line rtn)))))
22491 (nreverse rtn)))
22493 (defun org-export (&optional arg)
22494 (interactive)
22495 (let ((help "[t] insert the export option template
22496 \[v] limit export to visible part of outline tree
22498 \[a] export as ASCII
22500 \[h] export as HTML
22501 \[H] export as HTML to temporary buffer
22502 \[R] export region as HTML
22503 \[b] export as HTML and browse immediately
22504 \[x] export as XOXO
22506 \[l] export as LaTeX
22507 \[L] export as LaTeX to temporary buffer
22509 \[i] export current file as iCalendar file
22510 \[I] export all agenda files as iCalendar files
22511 \[c] export agenda files into combined iCalendar file
22513 \[F] publish current file
22514 \[P] publish current project
22515 \[X] publish... (project will be prompted for)
22516 \[A] publish all projects")
22517 (cmds
22518 '((?t . org-insert-export-options-template)
22519 (?v . org-export-visible)
22520 (?a . org-export-as-ascii)
22521 (?h . org-export-as-html)
22522 (?b . org-export-as-html-and-open)
22523 (?H . org-export-as-html-to-buffer)
22524 (?R . org-export-region-as-html)
22525 (?x . org-export-as-xoxo)
22526 (?l . org-export-as-latex)
22527 (?L . org-export-as-latex-to-buffer)
22528 (?i . org-export-icalendar-this-file)
22529 (?I . org-export-icalendar-all-agenda-files)
22530 (?c . org-export-icalendar-combine-agenda-files)
22531 (?F . org-publish-current-file)
22532 (?P . org-publish-current-project)
22533 (?X . org-publish)
22534 (?A . org-publish-all)))
22535 r1 r2 ass)
22536 (save-window-excursion
22537 (delete-other-windows)
22538 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
22539 (princ help))
22540 (message "Select command: ")
22541 (setq r1 (read-char-exclusive)))
22542 (setq r2 (if (< r1 27) (+ r1 96) r1))
22543 (if (setq ass (assq r2 cmds))
22544 (call-interactively (cdr ass))
22545 (error "No command associated with key %c" r1))))
22547 (defconst org-html-entities
22548 '(("nbsp")
22549 ("iexcl")
22550 ("cent")
22551 ("pound")
22552 ("curren")
22553 ("yen")
22554 ("brvbar")
22555 ("vert" . "&#124;")
22556 ("sect")
22557 ("uml")
22558 ("copy")
22559 ("ordf")
22560 ("laquo")
22561 ("not")
22562 ("shy")
22563 ("reg")
22564 ("macr")
22565 ("deg")
22566 ("plusmn")
22567 ("sup2")
22568 ("sup3")
22569 ("acute")
22570 ("micro")
22571 ("para")
22572 ("middot")
22573 ("odot"."o")
22574 ("star"."*")
22575 ("cedil")
22576 ("sup1")
22577 ("ordm")
22578 ("raquo")
22579 ("frac14")
22580 ("frac12")
22581 ("frac34")
22582 ("iquest")
22583 ("Agrave")
22584 ("Aacute")
22585 ("Acirc")
22586 ("Atilde")
22587 ("Auml")
22588 ("Aring") ("AA"."&Aring;")
22589 ("AElig")
22590 ("Ccedil")
22591 ("Egrave")
22592 ("Eacute")
22593 ("Ecirc")
22594 ("Euml")
22595 ("Igrave")
22596 ("Iacute")
22597 ("Icirc")
22598 ("Iuml")
22599 ("ETH")
22600 ("Ntilde")
22601 ("Ograve")
22602 ("Oacute")
22603 ("Ocirc")
22604 ("Otilde")
22605 ("Ouml")
22606 ("times")
22607 ("Oslash")
22608 ("Ugrave")
22609 ("Uacute")
22610 ("Ucirc")
22611 ("Uuml")
22612 ("Yacute")
22613 ("THORN")
22614 ("szlig")
22615 ("agrave")
22616 ("aacute")
22617 ("acirc")
22618 ("atilde")
22619 ("auml")
22620 ("aring")
22621 ("aelig")
22622 ("ccedil")
22623 ("egrave")
22624 ("eacute")
22625 ("ecirc")
22626 ("euml")
22627 ("igrave")
22628 ("iacute")
22629 ("icirc")
22630 ("iuml")
22631 ("eth")
22632 ("ntilde")
22633 ("ograve")
22634 ("oacute")
22635 ("ocirc")
22636 ("otilde")
22637 ("ouml")
22638 ("divide")
22639 ("oslash")
22640 ("ugrave")
22641 ("uacute")
22642 ("ucirc")
22643 ("uuml")
22644 ("yacute")
22645 ("thorn")
22646 ("yuml")
22647 ("fnof")
22648 ("Alpha")
22649 ("Beta")
22650 ("Gamma")
22651 ("Delta")
22652 ("Epsilon")
22653 ("Zeta")
22654 ("Eta")
22655 ("Theta")
22656 ("Iota")
22657 ("Kappa")
22658 ("Lambda")
22659 ("Mu")
22660 ("Nu")
22661 ("Xi")
22662 ("Omicron")
22663 ("Pi")
22664 ("Rho")
22665 ("Sigma")
22666 ("Tau")
22667 ("Upsilon")
22668 ("Phi")
22669 ("Chi")
22670 ("Psi")
22671 ("Omega")
22672 ("alpha")
22673 ("beta")
22674 ("gamma")
22675 ("delta")
22676 ("epsilon")
22677 ("varepsilon"."&epsilon;")
22678 ("zeta")
22679 ("eta")
22680 ("theta")
22681 ("iota")
22682 ("kappa")
22683 ("lambda")
22684 ("mu")
22685 ("nu")
22686 ("xi")
22687 ("omicron")
22688 ("pi")
22689 ("rho")
22690 ("sigmaf") ("varsigma"."&sigmaf;")
22691 ("sigma")
22692 ("tau")
22693 ("upsilon")
22694 ("phi")
22695 ("chi")
22696 ("psi")
22697 ("omega")
22698 ("thetasym") ("vartheta"."&thetasym;")
22699 ("upsih")
22700 ("piv")
22701 ("bull") ("bullet"."&bull;")
22702 ("hellip") ("dots"."&hellip;")
22703 ("prime")
22704 ("Prime")
22705 ("oline")
22706 ("frasl")
22707 ("weierp")
22708 ("image")
22709 ("real")
22710 ("trade")
22711 ("alefsym")
22712 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
22713 ("uarr") ("uparrow"."&uarr;")
22714 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
22715 ("darr")("downarrow"."&darr;")
22716 ("harr") ("leftrightarrow"."&harr;")
22717 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
22718 ("lArr") ("Leftarrow"."&lArr;")
22719 ("uArr") ("Uparrow"."&uArr;")
22720 ("rArr") ("Rightarrow"."&rArr;")
22721 ("dArr") ("Downarrow"."&dArr;")
22722 ("hArr") ("Leftrightarrow"."&hArr;")
22723 ("forall")
22724 ("part") ("partial"."&part;")
22725 ("exist") ("exists"."&exist;")
22726 ("empty") ("emptyset"."&empty;")
22727 ("nabla")
22728 ("isin") ("in"."&isin;")
22729 ("notin")
22730 ("ni")
22731 ("prod")
22732 ("sum")
22733 ("minus")
22734 ("lowast") ("ast"."&lowast;")
22735 ("radic")
22736 ("prop") ("proptp"."&prop;")
22737 ("infin") ("infty"."&infin;")
22738 ("ang") ("angle"."&ang;")
22739 ("and") ("wedge"."&and;")
22740 ("or") ("vee"."&or;")
22741 ("cap")
22742 ("cup")
22743 ("int")
22744 ("there4")
22745 ("sim")
22746 ("cong") ("simeq"."&cong;")
22747 ("asymp")("approx"."&asymp;")
22748 ("ne") ("neq"."&ne;")
22749 ("equiv")
22750 ("le")
22751 ("ge")
22752 ("sub") ("subset"."&sub;")
22753 ("sup") ("supset"."&sup;")
22754 ("nsub")
22755 ("sube")
22756 ("supe")
22757 ("oplus")
22758 ("otimes")
22759 ("perp")
22760 ("sdot") ("cdot"."&sdot;")
22761 ("lceil")
22762 ("rceil")
22763 ("lfloor")
22764 ("rfloor")
22765 ("lang")
22766 ("rang")
22767 ("loz") ("Diamond"."&loz;")
22768 ("spades") ("spadesuit"."&spades;")
22769 ("clubs") ("clubsuit"."&clubs;")
22770 ("hearts") ("diamondsuit"."&hearts;")
22771 ("diams") ("diamondsuit"."&diams;")
22772 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
22773 ("quot")
22774 ("amp")
22775 ("lt")
22776 ("gt")
22777 ("OElig")
22778 ("oelig")
22779 ("Scaron")
22780 ("scaron")
22781 ("Yuml")
22782 ("circ")
22783 ("tilde")
22784 ("ensp")
22785 ("emsp")
22786 ("thinsp")
22787 ("zwnj")
22788 ("zwj")
22789 ("lrm")
22790 ("rlm")
22791 ("ndash")
22792 ("mdash")
22793 ("lsquo")
22794 ("rsquo")
22795 ("sbquo")
22796 ("ldquo")
22797 ("rdquo")
22798 ("bdquo")
22799 ("dagger")
22800 ("Dagger")
22801 ("permil")
22802 ("lsaquo")
22803 ("rsaquo")
22804 ("euro")
22806 ("arccos"."arccos")
22807 ("arcsin"."arcsin")
22808 ("arctan"."arctan")
22809 ("arg"."arg")
22810 ("cos"."cos")
22811 ("cosh"."cosh")
22812 ("cot"."cot")
22813 ("coth"."coth")
22814 ("csc"."csc")
22815 ("deg"."deg")
22816 ("det"."det")
22817 ("dim"."dim")
22818 ("exp"."exp")
22819 ("gcd"."gcd")
22820 ("hom"."hom")
22821 ("inf"."inf")
22822 ("ker"."ker")
22823 ("lg"."lg")
22824 ("lim"."lim")
22825 ("liminf"."liminf")
22826 ("limsup"."limsup")
22827 ("ln"."ln")
22828 ("log"."log")
22829 ("max"."max")
22830 ("min"."min")
22831 ("Pr"."Pr")
22832 ("sec"."sec")
22833 ("sin"."sin")
22834 ("sinh"."sinh")
22835 ("sup"."sup")
22836 ("tan"."tan")
22837 ("tanh"."tanh")
22839 "Entities for TeX->HTML translation.
22840 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
22841 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
22842 In that case, \"\\ent\" will be translated to \"&other;\".
22843 The list contains HTML entities for Latin-1, Greek and other symbols.
22844 It is supplemented by a number of commonly used TeX macros with appropriate
22845 translations. There is currently no way for users to extend this.")
22847 ;;; General functions for all backends
22849 (defun org-cleaned-string-for-export (string &rest parameters)
22850 "Cleanup a buffer STRING so that links can be created safely."
22851 (interactive)
22852 (let* ((re-radio (and org-target-link-regexp
22853 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
22854 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
22855 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
22856 (re-archive (concat ":" org-archive-tag ":"))
22857 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
22858 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
22859 (htmlp (plist-get parameters :for-html))
22860 (asciip (plist-get parameters :for-ascii))
22861 (latexp (plist-get parameters :for-LaTeX))
22862 (commentsp (plist-get parameters :comments))
22863 (archived-trees (plist-get parameters :archived-trees))
22864 (inhibit-read-only t)
22865 (drawers org-drawers)
22866 (exp-drawers (plist-get parameters :drawers))
22867 (outline-regexp "\\*+ ")
22868 a b xx
22869 rtn p)
22870 (with-current-buffer (get-buffer-create " org-mode-tmp")
22871 (erase-buffer)
22872 (insert string)
22873 ;; Remove license-to-kill stuff
22874 (while (setq p (text-property-any (point-min) (point-max)
22875 :org-license-to-kill t))
22876 (delete-region p (next-single-property-change p :org-license-to-kill)))
22878 (let ((org-inhibit-startup t)) (org-mode))
22879 (untabify (point-min) (point-max))
22881 ;; Get the correct stuff before the first headline
22882 (when (plist-get parameters :skip-before-1st-heading)
22883 (goto-char (point-min))
22884 (when (re-search-forward "^\\*+[ \t]" nil t)
22885 (delete-region (point-min) (match-beginning 0))
22886 (goto-char (point-min))
22887 (insert "\n")))
22888 (when (plist-get parameters :add-text)
22889 (goto-char (point-min))
22890 (insert (plist-get parameters :add-text) "\n"))
22892 ;; Get rid of archived trees
22893 (when (not (eq archived-trees t))
22894 (goto-char (point-min))
22895 (while (re-search-forward re-archive nil t)
22896 (if (not (org-on-heading-p t))
22897 (org-end-of-subtree t)
22898 (beginning-of-line 1)
22899 (setq a (if archived-trees
22900 (1+ (point-at-eol)) (point))
22901 b (org-end-of-subtree t))
22902 (if (> b a) (delete-region a b)))))
22904 ;; Get rid of drawers
22905 (unless (eq t exp-drawers)
22906 (goto-char (point-min))
22907 (let ((re (concat "^[ \t]*:\\("
22908 (mapconcat
22909 'identity
22910 (org-delete-all exp-drawers
22911 (copy-sequence drawers))
22912 "\\|")
22913 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
22914 (while (re-search-forward re nil t)
22915 (replace-match ""))))
22917 ;; Find targets in comments and move them out of comments,
22918 ;; but mark them as targets that should be invisible
22919 (goto-char (point-min))
22920 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
22921 (replace-match "\\1(INVISIBLE)"))
22923 ;; Protect backend specific stuff, throw away the others.
22924 (let ((formatters
22925 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
22926 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
22927 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
22928 fmt)
22929 (goto-char (point-min))
22930 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
22931 (goto-char (match-end 0))
22932 (while (not (looking-at "#\\+END_EXAMPLE"))
22933 (insert ": ")
22934 (beginning-of-line 2)))
22935 (goto-char (point-min))
22936 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
22937 (add-text-properties (match-beginning 0) (match-end 0)
22938 '(org-protected t)))
22939 (while formatters
22940 (setq fmt (pop formatters))
22941 (when (car fmt)
22942 (goto-char (point-min))
22943 (while (re-search-forward (concat "^#\\+" (cadr fmt)
22944 ":[ \t]*\\(.*\\)") nil t)
22945 (replace-match "\\1" t)
22946 (add-text-properties
22947 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
22948 '(org-protected t))))
22949 (goto-char (point-min))
22950 (while (re-search-forward
22951 (concat "^#\\+"
22952 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
22953 (cadddr fmt) "\\>.*\n?") nil t)
22954 (if (car fmt)
22955 (add-text-properties (match-beginning 1) (1+ (match-end 1))
22956 '(org-protected t))
22957 (delete-region (match-beginning 0) (match-end 0))))))
22959 ;; Protect quoted subtrees
22960 (goto-char (point-min))
22961 (while (re-search-forward re-quote nil t)
22962 (goto-char (match-beginning 0))
22963 (end-of-line 1)
22964 (add-text-properties (point) (org-end-of-subtree t)
22965 '(org-protected t)))
22967 ;; Protect verbatim elements
22968 (goto-char (point-min))
22969 (while (re-search-forward org-verbatim-re nil t)
22970 (add-text-properties (match-beginning 4) (match-end 4)
22971 '(org-protected t))
22972 (goto-char (1+ (match-end 4))))
22974 ;; Remove subtrees that are commented
22975 (goto-char (point-min))
22976 (while (re-search-forward re-commented nil t)
22977 (goto-char (match-beginning 0))
22978 (delete-region (point) (org-end-of-subtree t)))
22980 ;; Remove special table lines
22981 (when org-export-table-remove-special-lines
22982 (goto-char (point-min))
22983 (while (re-search-forward "^[ \t]*|" nil t)
22984 (beginning-of-line 1)
22985 (if (or (looking-at "[ \t]*| *[!_^] *|")
22986 (and (looking-at ".*?| *<[0-9]+> *|")
22987 (not (looking-at ".*?| *[^ <|]"))))
22988 (delete-region (max (point-min) (1- (point-at-bol)))
22989 (point-at-eol))
22990 (end-of-line 1))))
22992 ;; Specific LaTeX stuff
22993 (when latexp
22994 (require 'org-export-latex nil)
22995 (org-export-latex-cleaned-string))
22997 (when asciip
22998 (org-export-ascii-clean-string))
23000 ;; Specific HTML stuff
23001 (when htmlp
23002 ;; Convert LaTeX fragments to images
23003 (when (plist-get parameters :LaTeX-fragments)
23004 (org-format-latex
23005 (concat "ltxpng/" (file-name-sans-extension
23006 (file-name-nondirectory
23007 org-current-export-file)))
23008 org-current-export-dir nil "Creating LaTeX image %s"))
23009 (message "Exporting..."))
23011 ;; Remove or replace comments
23012 (goto-char (point-min))
23013 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
23014 (if commentsp
23015 (progn (add-text-properties
23016 (match-beginning 0) (match-end 0) '(org-protected t))
23017 (replace-match (format commentsp (match-string 1)) t t))
23018 (replace-match "")))
23020 ;; Find matches for radio targets and turn them into internal links
23021 (goto-char (point-min))
23022 (when re-radio
23023 (while (re-search-forward re-radio nil t)
23024 (org-if-unprotected
23025 (replace-match "\\1[[\\2]]"))))
23027 ;; Find all links that contain a newline and put them into a single line
23028 (goto-char (point-min))
23029 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
23030 (org-if-unprotected
23031 (replace-match "\\1 \\3")
23032 (goto-char (match-beginning 0))))
23035 ;; Normalize links: Convert angle and plain links into bracket links
23036 ;; Expand link abbreviations
23037 (goto-char (point-min))
23038 (while (re-search-forward re-plain-link nil t)
23039 (goto-char (1- (match-end 0)))
23040 (org-if-unprotected
23041 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23042 ":" (match-string 3) "]]")))
23043 ;; added 'org-link face to links
23044 (put-text-property 0 (length s) 'face 'org-link s)
23045 (replace-match s t t))))
23046 (goto-char (point-min))
23047 (while (re-search-forward re-angle-link nil t)
23048 (goto-char (1- (match-end 0)))
23049 (org-if-unprotected
23050 (let* ((s (concat (match-string 1) "[[" (match-string 2)
23051 ":" (match-string 3) "]]")))
23052 (put-text-property 0 (length s) 'face 'org-link s)
23053 (replace-match s t t))))
23054 (goto-char (point-min))
23055 (while (re-search-forward org-bracket-link-regexp nil t)
23056 (org-if-unprotected
23057 (let* ((s (concat "[[" (setq xx (save-match-data
23058 (org-link-expand-abbrev (match-string 1))))
23060 (if (match-end 3)
23061 (match-string 2)
23062 (concat "[" xx "]"))
23063 "]")))
23064 (put-text-property 0 (length s) 'face 'org-link s)
23065 (replace-match s t t))))
23067 ;; Find multiline emphasis and put them into single line
23068 (when (plist-get parameters :emph-multiline)
23069 (goto-char (point-min))
23070 (while (re-search-forward org-emph-re nil t)
23071 (if (not (= (char-after (match-beginning 3))
23072 (char-after (match-beginning 4))))
23073 (org-if-unprotected
23074 (subst-char-in-region (match-beginning 0) (match-end 0)
23075 ?\n ?\ t)
23076 (goto-char (1- (match-end 0))))
23077 (goto-char (1+ (match-beginning 0))))))
23079 (setq rtn (buffer-string)))
23080 (kill-buffer " org-mode-tmp")
23081 rtn))
23083 (defun org-export-grab-title-from-buffer ()
23084 "Get a title for the current document, from looking at the buffer."
23085 (let ((inhibit-read-only t))
23086 (save-excursion
23087 (goto-char (point-min))
23088 (let ((end (save-excursion (outline-next-heading) (point))))
23089 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
23090 ;; Mark the line so that it will not be exported as normal text.
23091 (org-unmodified
23092 (add-text-properties (match-beginning 0) (match-end 0)
23093 (list :org-license-to-kill t)))
23094 ;; Return the title string
23095 (org-trim (match-string 0)))))))
23097 (defun org-export-get-title-from-subtree ()
23098 "Return subtree title and exclude it from export."
23099 (let (title (m (mark)))
23100 (save-excursion
23101 (goto-char (region-beginning))
23102 (when (and (org-at-heading-p)
23103 (>= (org-end-of-subtree t t) (region-end)))
23104 ;; This is a subtree, we take the title from the first heading
23105 (goto-char (region-beginning))
23106 (looking-at org-todo-line-regexp)
23107 (setq title (match-string 3))
23108 (org-unmodified
23109 (add-text-properties (point) (1+ (point-at-eol))
23110 (list :org-license-to-kill t)))))
23111 title))
23113 (defun org-solidify-link-text (s &optional alist)
23114 "Take link text and make a safe target out of it."
23115 (save-match-data
23116 (let* ((rtn
23117 (mapconcat
23118 'identity
23119 (org-split-string s "[ \t\r\n]+") "--"))
23120 (a (assoc rtn alist)))
23121 (or (cdr a) rtn))))
23123 (defun org-get-min-level (lines)
23124 "Get the minimum level in LINES."
23125 (let ((re "^\\(\\*+\\) ") l min)
23126 (catch 'exit
23127 (while (setq l (pop lines))
23128 (if (string-match re l)
23129 (throw 'exit (org-tr-level (length (match-string 1 l))))))
23130 1)))
23132 ;; Variable holding the vector with section numbers
23133 (defvar org-section-numbers (make-vector org-level-max 0))
23135 (defun org-init-section-numbers ()
23136 "Initialize the vector for the section numbers."
23137 (let* ((level -1)
23138 (numbers (nreverse (org-split-string "" "\\.")))
23139 (depth (1- (length org-section-numbers)))
23140 (i depth) number-string)
23141 (while (>= i 0)
23142 (if (> i level)
23143 (aset org-section-numbers i 0)
23144 (setq number-string (or (car numbers) "0"))
23145 (if (string-match "\\`[A-Z]\\'" number-string)
23146 (aset org-section-numbers i
23147 (- (string-to-char number-string) ?A -1))
23148 (aset org-section-numbers i (string-to-number number-string)))
23149 (pop numbers))
23150 (setq i (1- i)))))
23152 (defun org-section-number (&optional level)
23153 "Return a string with the current section number.
23154 When LEVEL is non-nil, increase section numbers on that level."
23155 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
23156 (when level
23157 (when (> level -1)
23158 (aset org-section-numbers
23159 level (1+ (aref org-section-numbers level))))
23160 (setq idx (1+ level))
23161 (while (<= idx depth)
23162 (if (not (= idx 1))
23163 (aset org-section-numbers idx 0))
23164 (setq idx (1+ idx))))
23165 (setq idx 0)
23166 (while (<= idx depth)
23167 (setq n (aref org-section-numbers idx))
23168 (setq string (concat string (if (not (string= string "")) "." "")
23169 (int-to-string n)))
23170 (setq idx (1+ idx)))
23171 (save-match-data
23172 (if (string-match "\\`\\([@0]\\.\\)+" string)
23173 (setq string (replace-match "" t nil string)))
23174 (if (string-match "\\(\\.0\\)+\\'" string)
23175 (setq string (replace-match "" t nil string))))
23176 string))
23178 ;;; ASCII export
23180 (defvar org-last-level nil) ; dynamically scoped variable
23181 (defvar org-min-level nil) ; dynamically scoped variable
23182 (defvar org-levels-open nil) ; dynamically scoped parameter
23183 (defvar org-ascii-current-indentation nil) ; For communication
23185 (defun org-export-as-ascii (arg)
23186 "Export the outline as a pretty ASCII file.
23187 If there is an active region, export only the region.
23188 The prefix ARG specifies how many levels of the outline should become
23189 underlined headlines. The default is 3."
23190 (interactive "P")
23191 (setq-default org-todo-line-regexp org-todo-line-regexp)
23192 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23193 (org-infile-export-plist)))
23194 (region-p (org-region-active-p))
23195 (subtree-p
23196 (when region-p
23197 (save-excursion
23198 (goto-char (region-beginning))
23199 (and (org-at-heading-p)
23200 (>= (org-end-of-subtree t t) (region-end))))))
23201 (custom-times org-display-custom-times)
23202 (org-ascii-current-indentation '(0 . 0))
23203 (level 0) line txt
23204 (umax nil)
23205 (umax-toc nil)
23206 (case-fold-search nil)
23207 (filename (concat (file-name-as-directory
23208 (org-export-directory :ascii opt-plist))
23209 (file-name-sans-extension
23210 (or (and subtree-p
23211 (org-entry-get (region-beginning)
23212 "EXPORT_FILE_NAME" t))
23213 (file-name-nondirectory buffer-file-name)))
23214 ".txt"))
23215 (filename (if (equal (file-truename filename)
23216 (file-truename buffer-file-name))
23217 (concat filename ".txt")
23218 filename))
23219 (buffer (find-file-noselect filename))
23220 (org-levels-open (make-vector org-level-max nil))
23221 (odd org-odd-levels-only)
23222 (date (plist-get opt-plist :date))
23223 (author (plist-get opt-plist :author))
23224 (title (or (and subtree-p (org-export-get-title-from-subtree))
23225 (plist-get opt-plist :title)
23226 (and (not
23227 (plist-get opt-plist :skip-before-1st-heading))
23228 (org-export-grab-title-from-buffer))
23229 (file-name-sans-extension
23230 (file-name-nondirectory buffer-file-name))))
23231 (email (plist-get opt-plist :email))
23232 (language (plist-get opt-plist :language))
23233 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23234 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
23235 (todo nil)
23236 (lang-words nil)
23237 (region
23238 (buffer-substring
23239 (if (org-region-active-p) (region-beginning) (point-min))
23240 (if (org-region-active-p) (region-end) (point-max))))
23241 (lines (org-split-string
23242 (org-cleaned-string-for-export
23243 region
23244 :for-ascii t
23245 :skip-before-1st-heading
23246 (plist-get opt-plist :skip-before-1st-heading)
23247 :drawers (plist-get opt-plist :drawers)
23248 :verbatim-multiline t
23249 :archived-trees
23250 (plist-get opt-plist :archived-trees)
23251 :add-text (plist-get opt-plist :text))
23252 "\n"))
23253 thetoc have-headings first-heading-pos
23254 table-open table-buffer)
23256 (let ((inhibit-read-only t))
23257 (org-unmodified
23258 (remove-text-properties (point-min) (point-max)
23259 '(:org-license-to-kill t))))
23261 (setq org-min-level (org-get-min-level lines))
23262 (setq org-last-level org-min-level)
23263 (org-init-section-numbers)
23265 (find-file-noselect filename)
23267 (setq lang-words (or (assoc language org-export-language-setup)
23268 (assoc "en" org-export-language-setup)))
23269 (switch-to-buffer-other-window buffer)
23270 (erase-buffer)
23271 (fundamental-mode)
23272 ;; create local variables for all options, to make sure all called
23273 ;; functions get the correct information
23274 (mapc (lambda (x)
23275 (set (make-local-variable (cdr x))
23276 (plist-get opt-plist (car x))))
23277 org-export-plist-vars)
23278 (org-set-local 'org-odd-levels-only odd)
23279 (setq umax (if arg (prefix-numeric-value arg)
23280 org-export-headline-levels))
23281 (setq umax-toc (if (integerp org-export-with-toc)
23282 (min org-export-with-toc umax)
23283 umax))
23285 ;; File header
23286 (if title (org-insert-centered title ?=))
23287 (insert "\n")
23288 (if (and (or author email)
23289 org-export-author-info)
23290 (insert (concat (nth 1 lang-words) ": " (or author "")
23291 (if email (concat " <" email ">") "")
23292 "\n")))
23294 (cond
23295 ((and date (string-match "%" date))
23296 (setq date (format-time-string date (current-time))))
23297 (date)
23298 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23300 (if (and date org-export-time-stamp-file)
23301 (insert (concat (nth 2 lang-words) ": " date"\n")))
23303 (insert "\n\n")
23305 (if org-export-with-toc
23306 (progn
23307 (push (concat (nth 3 lang-words) "\n") thetoc)
23308 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
23309 (mapc '(lambda (line)
23310 (if (string-match org-todo-line-regexp
23311 line)
23312 ;; This is a headline
23313 (progn
23314 (setq have-headings t)
23315 (setq level (- (match-end 1) (match-beginning 1))
23316 level (org-tr-level level)
23317 txt (match-string 3 line)
23318 todo
23319 (or (and org-export-mark-todo-in-toc
23320 (match-beginning 2)
23321 (not (member (match-string 2 line)
23322 org-done-keywords)))
23323 ; TODO, not DONE
23324 (and org-export-mark-todo-in-toc
23325 (= level umax-toc)
23326 (org-search-todo-below
23327 line lines level))))
23328 (setq txt (org-html-expand-for-ascii txt))
23330 (while (string-match org-bracket-link-regexp txt)
23331 (setq txt
23332 (replace-match
23333 (match-string (if (match-end 2) 3 1) txt)
23334 t t txt)))
23336 (if (and (memq org-export-with-tags '(not-in-toc nil))
23337 (string-match
23338 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
23339 txt))
23340 (setq txt (replace-match "" t t txt)))
23341 (if (string-match quote-re0 txt)
23342 (setq txt (replace-match "" t t txt)))
23344 (if org-export-with-section-numbers
23345 (setq txt (concat (org-section-number level)
23346 " " txt)))
23347 (if (<= level umax-toc)
23348 (progn
23349 (push
23350 (concat
23351 (make-string
23352 (* (max 0 (- level org-min-level)) 4) ?\ )
23353 (format (if todo "%s (*)\n" "%s\n") txt))
23354 thetoc)
23355 (setq org-last-level level))
23356 ))))
23357 lines)
23358 (setq thetoc (if have-headings (nreverse thetoc) nil))))
23360 (org-init-section-numbers)
23361 (while (setq line (pop lines))
23362 ;; Remove the quoted HTML tags.
23363 (setq line (org-html-expand-for-ascii line))
23364 ;; Remove targets
23365 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
23366 (setq line (replace-match "" t t line)))
23367 ;; Replace internal links
23368 (while (string-match org-bracket-link-regexp line)
23369 (setq line (replace-match
23370 (if (match-end 3) "[\\3]" "[\\1]")
23371 t nil line)))
23372 (when custom-times
23373 (setq line (org-translate-time line)))
23374 (cond
23375 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
23376 ;; a Headline
23377 (setq first-heading-pos (or first-heading-pos (point)))
23378 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
23379 txt (match-string 2 line))
23380 (org-ascii-level-start level txt umax lines))
23382 ((and org-export-with-tables
23383 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
23384 (if (not table-open)
23385 ;; New table starts
23386 (setq table-open t table-buffer nil))
23387 ;; Accumulate lines
23388 (setq table-buffer (cons line table-buffer))
23389 (when (or (not lines)
23390 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
23391 (car lines))))
23392 (setq table-open nil
23393 table-buffer (nreverse table-buffer))
23394 (insert (mapconcat
23395 (lambda (x)
23396 (org-fix-indentation x org-ascii-current-indentation))
23397 (org-format-table-ascii table-buffer)
23398 "\n") "\n")))
23400 (setq line (org-fix-indentation line org-ascii-current-indentation))
23401 (if (and org-export-with-fixed-width
23402 (string-match "^\\([ \t]*\\)\\(:\\)" line))
23403 (setq line (replace-match "\\1" nil nil line)))
23404 (insert line "\n"))))
23406 (normal-mode)
23408 ;; insert the table of contents
23409 (when thetoc
23410 (goto-char (point-min))
23411 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
23412 (progn
23413 (goto-char (match-beginning 0))
23414 (replace-match ""))
23415 (goto-char first-heading-pos))
23416 (mapc 'insert thetoc)
23417 (or (looking-at "[ \t]*\n[ \t]*\n")
23418 (insert "\n\n")))
23420 ;; Convert whitespace place holders
23421 (goto-char (point-min))
23422 (let (beg end)
23423 (while (setq beg (next-single-property-change (point) 'org-whitespace))
23424 (setq end (next-single-property-change beg 'org-whitespace))
23425 (goto-char beg)
23426 (delete-region beg end)
23427 (insert (make-string (- end beg) ?\ ))))
23429 (save-buffer)
23430 ;; remove display and invisible chars
23431 (let (beg end)
23432 (goto-char (point-min))
23433 (while (setq beg (next-single-property-change (point) 'display))
23434 (setq end (next-single-property-change beg 'display))
23435 (delete-region beg end)
23436 (goto-char beg)
23437 (insert "=>"))
23438 (goto-char (point-min))
23439 (while (setq beg (next-single-property-change (point) 'org-cwidth))
23440 (setq end (next-single-property-change beg 'org-cwidth))
23441 (delete-region beg end)
23442 (goto-char beg)))
23443 (goto-char (point-min))))
23445 (defun org-export-ascii-clean-string ()
23446 "Do extra work for ASCII export"
23447 (goto-char (point-min))
23448 (while (re-search-forward org-verbatim-re nil t)
23449 (goto-char (match-end 2))
23450 (backward-delete-char 1) (insert "'")
23451 (goto-char (match-beginning 2))
23452 (delete-char 1) (insert "`")
23453 (goto-char (match-end 2))))
23455 (defun org-search-todo-below (line lines level)
23456 "Search the subtree below LINE for any TODO entries."
23457 (let ((rest (cdr (memq line lines)))
23458 (re org-todo-line-regexp)
23459 line lv todo)
23460 (catch 'exit
23461 (while (setq line (pop rest))
23462 (if (string-match re line)
23463 (progn
23464 (setq lv (- (match-end 1) (match-beginning 1))
23465 todo (and (match-beginning 2)
23466 (not (member (match-string 2 line)
23467 org-done-keywords))))
23468 ; TODO, not DONE
23469 (if (<= lv level) (throw 'exit nil))
23470 (if todo (throw 'exit t))))))))
23472 (defun org-html-expand-for-ascii (line)
23473 "Handle quoted HTML for ASCII export."
23474 (if org-export-html-expand
23475 (while (string-match "@<[^<>\n]*>" line)
23476 ;; We just remove the tags for now.
23477 (setq line (replace-match "" nil nil line))))
23478 line)
23480 (defun org-insert-centered (s &optional underline)
23481 "Insert the string S centered and underline it with character UNDERLINE."
23482 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
23483 (insert (make-string ind ?\ ) s "\n")
23484 (if underline
23485 (insert (make-string ind ?\ )
23486 (make-string (string-width s) underline)
23487 "\n"))))
23489 (defun org-ascii-level-start (level title umax &optional lines)
23490 "Insert a new level in ASCII export."
23491 (let (char (n (- level umax 1)) (ind 0))
23492 (if (> level umax)
23493 (progn
23494 (insert (make-string (* 2 n) ?\ )
23495 (char-to-string (nth (% n (length org-export-ascii-bullets))
23496 org-export-ascii-bullets))
23497 " " title "\n")
23498 ;; find the indentation of the next non-empty line
23499 (catch 'stop
23500 (while lines
23501 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
23502 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
23503 (throw 'stop (setq ind (org-get-indentation (car lines)))))
23504 (pop lines)))
23505 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
23506 (if (or (not (equal (char-before) ?\n))
23507 (not (equal (char-before (1- (point))) ?\n)))
23508 (insert "\n"))
23509 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
23510 (unless org-export-with-tags
23511 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
23512 (setq title (replace-match "" t t title))))
23513 (if org-export-with-section-numbers
23514 (setq title (concat (org-section-number level) " " title)))
23515 (insert title "\n" (make-string (string-width title) char) "\n")
23516 (setq org-ascii-current-indentation '(0 . 0)))))
23518 (defun org-export-visible (type arg)
23519 "Create a copy of the visible part of the current buffer, and export it.
23520 The copy is created in a temporary buffer and removed after use.
23521 TYPE is the final key (as a string) that also select the export command in
23522 the `C-c C-e' export dispatcher.
23523 As a special case, if the you type SPC at the prompt, the temporary
23524 org-mode file will not be removed but presented to you so that you can
23525 continue to use it. The prefix arg ARG is passed through to the exporting
23526 command."
23527 (interactive
23528 (list (progn
23529 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
23530 (read-char-exclusive))
23531 current-prefix-arg))
23532 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
23533 (error "Invalid export key"))
23534 (let* ((binding (cdr (assoc type
23535 '((?a . org-export-as-ascii)
23536 (?\C-a . org-export-as-ascii)
23537 (?b . org-export-as-html-and-open)
23538 (?\C-b . org-export-as-html-and-open)
23539 (?h . org-export-as-html)
23540 (?H . org-export-as-html-to-buffer)
23541 (?R . org-export-region-as-html)
23542 (?x . org-export-as-xoxo)))))
23543 (keepp (equal type ?\ ))
23544 (file buffer-file-name)
23545 (buffer (get-buffer-create "*Org Export Visible*"))
23546 s e)
23547 ;; Need to hack the drawers here.
23548 (save-excursion
23549 (goto-char (point-min))
23550 (while (re-search-forward org-drawer-regexp nil t)
23551 (goto-char (match-beginning 1))
23552 (or (org-invisible-p) (org-flag-drawer nil))))
23553 (with-current-buffer buffer (erase-buffer))
23554 (save-excursion
23555 (setq s (goto-char (point-min)))
23556 (while (not (= (point) (point-max)))
23557 (goto-char (org-find-invisible))
23558 (append-to-buffer buffer s (point))
23559 (setq s (goto-char (org-find-visible))))
23560 (org-cycle-hide-drawers 'all)
23561 (goto-char (point-min))
23562 (unless keepp
23563 ;; Copy all comment lines to the end, to make sure #+ settings are
23564 ;; still available for the second export step. Kind of a hack, but
23565 ;; does do the trick.
23566 (if (looking-at "#[^\r\n]*")
23567 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
23568 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
23569 (append-to-buffer buffer (1+ (match-beginning 0))
23570 (min (point-max) (1+ (match-end 0))))))
23571 (set-buffer buffer)
23572 (let ((buffer-file-name file)
23573 (org-inhibit-startup t))
23574 (org-mode)
23575 (show-all)
23576 (unless keepp (funcall binding arg))))
23577 (if (not keepp)
23578 (kill-buffer buffer)
23579 (switch-to-buffer-other-window buffer)
23580 (goto-char (point-min)))))
23582 (defun org-find-visible ()
23583 (let ((s (point)))
23584 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23585 (get-char-property s 'invisible)))
23587 (defun org-find-invisible ()
23588 (let ((s (point)))
23589 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
23590 (not (get-char-property s 'invisible))))
23593 ;;; HTML export
23595 (defun org-get-current-options ()
23596 "Return a string with current options as keyword options.
23597 Does include HTML export options as well as TODO and CATEGORY stuff."
23598 (format
23599 "#+TITLE: %s
23600 #+AUTHOR: %s
23601 #+EMAIL: %s
23602 #+LANGUAGE: %s
23603 #+TEXT: Some descriptive text to be emitted. Several lines OK.
23604 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s -:%s f:%s *:%s TeX:%s LaTeX:%s skip:%s d:%s tags:%s
23605 #+CATEGORY: %s
23606 #+SEQ_TODO: %s
23607 #+TYP_TODO: %s
23608 #+PRIORITIES: %c %c %c
23609 #+DRAWERS: %s
23610 #+STARTUP: %s %s %s %s %s
23611 #+TAGS: %s
23612 #+ARCHIVE: %s
23613 #+LINK: %s
23615 (buffer-name) (user-full-name) user-mail-address org-export-default-language
23616 org-export-headline-levels
23617 org-export-with-section-numbers
23618 org-export-with-toc
23619 org-export-preserve-breaks
23620 org-export-html-expand
23621 org-export-with-fixed-width
23622 org-export-with-tables
23623 org-export-with-sub-superscripts
23624 org-export-with-special-strings
23625 org-export-with-footnotes
23626 org-export-with-emphasize
23627 org-export-with-TeX-macros
23628 org-export-with-LaTeX-fragments
23629 org-export-skip-text-before-1st-heading
23630 org-export-with-drawers
23631 org-export-with-tags
23632 (file-name-nondirectory buffer-file-name)
23633 "TODO FEEDBACK VERIFY DONE"
23634 "Me Jason Marie DONE"
23635 org-highest-priority org-lowest-priority org-default-priority
23636 (mapconcat 'identity org-drawers " ")
23637 (cdr (assoc org-startup-folded
23638 '((nil . "showall") (t . "overview") (content . "content"))))
23639 (if org-odd-levels-only "odd" "oddeven")
23640 (if org-hide-leading-stars "hidestars" "showstars")
23641 (if org-startup-align-all-tables "align" "noalign")
23642 (cond ((eq t org-log-done) "logdone")
23643 ((not org-log-done) "nologging")
23644 ((listp org-log-done)
23645 (mapconcat (lambda (x) (concat "lognote" (symbol-name x)))
23646 org-log-done " ")))
23647 (or (mapconcat (lambda (x)
23648 (cond
23649 ((equal '(:startgroup) x) "{")
23650 ((equal '(:endgroup) x) "}")
23651 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
23652 (t (car x))))
23653 (or org-tag-alist (org-get-buffer-tags)) " ") "")
23654 org-archive-location
23655 "org file:~/org/%s.org"
23658 (defun org-insert-export-options-template ()
23659 "Insert into the buffer a template with information for exporting."
23660 (interactive)
23661 (if (not (bolp)) (newline))
23662 (let ((s (org-get-current-options)))
23663 (and (string-match "#\\+CATEGORY" s)
23664 (setq s (substring s 0 (match-beginning 0))))
23665 (insert s)))
23667 (defun org-toggle-fixed-width-section (arg)
23668 "Toggle the fixed-width export.
23669 If there is no active region, the QUOTE keyword at the current headline is
23670 inserted or removed. When present, it causes the text between this headline
23671 and the next to be exported as fixed-width text, and unmodified.
23672 If there is an active region, this command adds or removes a colon as the
23673 first character of this line. If the first character of a line is a colon,
23674 this line is also exported in fixed-width font."
23675 (interactive "P")
23676 (let* ((cc 0)
23677 (regionp (org-region-active-p))
23678 (beg (if regionp (region-beginning) (point)))
23679 (end (if regionp (region-end)))
23680 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
23681 (case-fold-search nil)
23682 (re "[ \t]*\\(:\\)")
23683 off)
23684 (if regionp
23685 (save-excursion
23686 (goto-char beg)
23687 (setq cc (current-column))
23688 (beginning-of-line 1)
23689 (setq off (looking-at re))
23690 (while (> nlines 0)
23691 (setq nlines (1- nlines))
23692 (beginning-of-line 1)
23693 (cond
23694 (arg
23695 (move-to-column cc t)
23696 (insert ":\n")
23697 (forward-line -1))
23698 ((and off (looking-at re))
23699 (replace-match "" t t nil 1))
23700 ((not off) (move-to-column cc t) (insert ":")))
23701 (forward-line 1)))
23702 (save-excursion
23703 (org-back-to-heading)
23704 (if (looking-at (concat outline-regexp
23705 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
23706 (replace-match "" t t nil 1)
23707 (if (looking-at outline-regexp)
23708 (progn
23709 (goto-char (match-end 0))
23710 (insert org-quote-string " "))))))))
23712 (defun org-export-as-html-and-open (arg)
23713 "Export the outline as HTML and immediately open it with a browser.
23714 If there is an active region, export only the region.
23715 The prefix ARG specifies how many levels of the outline should become
23716 headlines. The default is 3. Lower levels will become bulleted lists."
23717 (interactive "P")
23718 (org-export-as-html arg 'hidden)
23719 (org-open-file buffer-file-name))
23721 (defun org-export-as-html-batch ()
23722 "Call `org-export-as-html', may be used in batch processing as
23723 emacs --batch
23724 --load=$HOME/lib/emacs/org.el
23725 --eval \"(setq org-export-headline-levels 2)\"
23726 --visit=MyFile --funcall org-export-as-html-batch"
23727 (org-export-as-html org-export-headline-levels 'hidden))
23729 (defun org-export-as-html-to-buffer (arg)
23730 "Call `org-exort-as-html` with output to a temporary buffer.
23731 No file is created. The prefix ARG is passed through to `org-export-as-html'."
23732 (interactive "P")
23733 (org-export-as-html arg nil nil "*Org HTML Export*")
23734 (switch-to-buffer-other-window "*Org HTML Export*"))
23736 (defun org-replace-region-by-html (beg end)
23737 "Assume the current region has org-mode syntax, and convert it to HTML.
23738 This can be used in any buffer. For example, you could write an
23739 itemized list in org-mode syntax in an HTML buffer and then use this
23740 command to convert it."
23741 (interactive "r")
23742 (let (reg html buf pop-up-frames)
23743 (save-window-excursion
23744 (if (org-mode-p)
23745 (setq html (org-export-region-as-html
23746 beg end t 'string))
23747 (setq reg (buffer-substring beg end)
23748 buf (get-buffer-create "*Org tmp*"))
23749 (with-current-buffer buf
23750 (erase-buffer)
23751 (insert reg)
23752 (org-mode)
23753 (setq html (org-export-region-as-html
23754 (point-min) (point-max) t 'string)))
23755 (kill-buffer buf)))
23756 (delete-region beg end)
23757 (insert html)))
23759 (defun org-export-region-as-html (beg end &optional body-only buffer)
23760 "Convert region from BEG to END in org-mode buffer to HTML.
23761 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
23762 contents, and only produce the region of converted text, useful for
23763 cut-and-paste operations.
23764 If BUFFER is a buffer or a string, use/create that buffer as a target
23765 of the converted HTML. If BUFFER is the symbol `string', return the
23766 produced HTML as a string and leave not buffer behind. For example,
23767 a Lisp program could call this function in the following way:
23769 (setq html (org-export-region-as-html beg end t 'string))
23771 When called interactively, the output buffer is selected, and shown
23772 in a window. A non-interactive call will only retunr the buffer."
23773 (interactive "r\nP")
23774 (when (interactive-p)
23775 (setq buffer "*Org HTML Export*"))
23776 (let ((transient-mark-mode t) (zmacs-regions t)
23777 rtn)
23778 (goto-char end)
23779 (set-mark (point)) ;; to activate the region
23780 (goto-char beg)
23781 (setq rtn (org-export-as-html
23782 nil nil nil
23783 buffer body-only))
23784 (if (fboundp 'deactivate-mark) (deactivate-mark))
23785 (if (and (interactive-p) (bufferp rtn))
23786 (switch-to-buffer-other-window rtn)
23787 rtn)))
23789 (defvar html-table-tag nil) ; dynamically scoped into this.
23790 (defun org-export-as-html (arg &optional hidden ext-plist
23791 to-buffer body-only)
23792 "Export the outline as a pretty HTML file.
23793 If there is an active region, export only the region. The prefix
23794 ARG specifies how many levels of the outline should become
23795 headlines. The default is 3. Lower levels will become bulleted
23796 lists. When HIDDEN is non-nil, don't display the HTML buffer.
23797 EXT-PLIST is a property list with external parameters overriding
23798 org-mode's default settings, but still inferior to file-local
23799 settings. When TO-BUFFER is non-nil, create a buffer with that
23800 name and export to that buffer. If TO-BUFFER is the symbol `string',
23801 don't leave any buffer behind but just return the resulting HTML as
23802 a string. When BODY-ONLY is set, don't produce the file header and footer,
23803 simply return the content of <body>...</body>, without even
23804 the body tags themselves."
23805 (interactive "P")
23807 ;; Make sure we have a file name when we need it.
23808 (when (and (not (or to-buffer body-only))
23809 (not buffer-file-name))
23810 (if (buffer-base-buffer)
23811 (org-set-local 'buffer-file-name
23812 (with-current-buffer (buffer-base-buffer)
23813 buffer-file-name))
23814 (error "Need a file name to be able to export.")))
23816 (message "Exporting...")
23817 (setq-default org-todo-line-regexp org-todo-line-regexp)
23818 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
23819 (setq-default org-done-keywords org-done-keywords)
23820 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
23821 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
23822 ext-plist
23823 (org-infile-export-plist)))
23825 (style (plist-get opt-plist :style))
23826 (link-validate (plist-get opt-plist :link-validation-function))
23827 valid thetoc have-headings first-heading-pos
23828 (odd org-odd-levels-only)
23829 (region-p (org-region-active-p))
23830 (subtree-p
23831 (when region-p
23832 (save-excursion
23833 (goto-char (region-beginning))
23834 (and (org-at-heading-p)
23835 (>= (org-end-of-subtree t t) (region-end))))))
23836 ;; The following two are dynamically scoped into other
23837 ;; routines below.
23838 (org-current-export-dir (org-export-directory :html opt-plist))
23839 (org-current-export-file buffer-file-name)
23840 (level 0) (line "") (origline "") txt todo
23841 (umax nil)
23842 (umax-toc nil)
23843 (filename (if to-buffer nil
23844 (concat (file-name-as-directory
23845 (org-export-directory :html opt-plist))
23846 (file-name-sans-extension
23847 (or (and subtree-p
23848 (org-entry-get (region-beginning)
23849 "EXPORT_FILE_NAME" t))
23850 (file-name-nondirectory buffer-file-name)))
23851 "." org-export-html-extension)))
23852 (current-dir (if buffer-file-name
23853 (file-name-directory buffer-file-name)
23854 default-directory))
23855 (buffer (if to-buffer
23856 (cond
23857 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
23858 (t (get-buffer-create to-buffer)))
23859 (find-file-noselect filename)))
23860 (org-levels-open (make-vector org-level-max nil))
23861 (date (plist-get opt-plist :date))
23862 (author (plist-get opt-plist :author))
23863 (title (or (and subtree-p (org-export-get-title-from-subtree))
23864 (plist-get opt-plist :title)
23865 (and (not
23866 (plist-get opt-plist :skip-before-1st-heading))
23867 (org-export-grab-title-from-buffer))
23868 (and buffer-file-name
23869 (file-name-sans-extension
23870 (file-name-nondirectory buffer-file-name)))
23871 "UNTITLED"))
23872 (html-table-tag (plist-get opt-plist :html-table-tag))
23873 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
23874 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
23875 (inquote nil)
23876 (infixed nil)
23877 (in-local-list nil)
23878 (local-list-num nil)
23879 (local-list-indent nil)
23880 (llt org-plain-list-ordered-item-terminator)
23881 (email (plist-get opt-plist :email))
23882 (language (plist-get opt-plist :language))
23883 (lang-words nil)
23884 (target-alist nil) tg
23885 (head-count 0) cnt
23886 (start 0)
23887 (coding-system (and (boundp 'buffer-file-coding-system)
23888 buffer-file-coding-system))
23889 (coding-system-for-write (or org-export-html-coding-system
23890 coding-system))
23891 (save-buffer-coding-system (or org-export-html-coding-system
23892 coding-system))
23893 (charset (and coding-system-for-write
23894 (fboundp 'coding-system-get)
23895 (coding-system-get coding-system-for-write
23896 'mime-charset)))
23897 (region
23898 (buffer-substring
23899 (if region-p (region-beginning) (point-min))
23900 (if region-p (region-end) (point-max))))
23901 (lines
23902 (org-split-string
23903 (org-cleaned-string-for-export
23904 region
23905 :emph-multiline t
23906 :for-html t
23907 :skip-before-1st-heading
23908 (plist-get opt-plist :skip-before-1st-heading)
23909 :drawers (plist-get opt-plist :drawers)
23910 :archived-trees
23911 (plist-get opt-plist :archived-trees)
23912 :add-text
23913 (plist-get opt-plist :text)
23914 :LaTeX-fragments
23915 (plist-get opt-plist :LaTeX-fragments))
23916 "[\r\n]"))
23917 table-open type
23918 table-buffer table-orig-buffer
23919 ind start-is-num starter didclose
23920 rpl path desc descp desc1 desc2 link
23923 (let ((inhibit-read-only t))
23924 (org-unmodified
23925 (remove-text-properties (point-min) (point-max)
23926 '(:org-license-to-kill t))))
23928 (message "Exporting...")
23930 (setq org-min-level (org-get-min-level lines))
23931 (setq org-last-level org-min-level)
23932 (org-init-section-numbers)
23934 (cond
23935 ((and date (string-match "%" date))
23936 (setq date (format-time-string date (current-time))))
23937 (date)
23938 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
23940 ;; Get the language-dependent settings
23941 (setq lang-words (or (assoc language org-export-language-setup)
23942 (assoc "en" org-export-language-setup)))
23944 ;; Switch to the output buffer
23945 (set-buffer buffer)
23946 (erase-buffer)
23947 (fundamental-mode)
23949 (and (fboundp 'set-buffer-file-coding-system)
23950 (set-buffer-file-coding-system coding-system-for-write))
23952 (let ((case-fold-search nil)
23953 (org-odd-levels-only odd))
23954 ;; create local variables for all options, to make sure all called
23955 ;; functions get the correct information
23956 (mapc (lambda (x)
23957 (set (make-local-variable (cdr x))
23958 (plist-get opt-plist (car x))))
23959 org-export-plist-vars)
23960 (setq umax (if arg (prefix-numeric-value arg)
23961 org-export-headline-levels))
23962 (setq umax-toc (if (integerp org-export-with-toc)
23963 (min org-export-with-toc umax)
23964 umax))
23965 (unless body-only
23966 ;; File header
23967 (insert (format
23968 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
23969 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
23970 <html xmlns=\"http://www.w3.org/1999/xhtml\"
23971 lang=\"%s\" xml:lang=\"%s\">
23972 <head>
23973 <title>%s</title>
23974 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
23975 <meta name=\"generator\" content=\"Org-mode\"/>
23976 <meta name=\"generated\" content=\"%s\"/>
23977 <meta name=\"author\" content=\"%s\"/>
23979 </head><body>
23981 language language (org-html-expand title)
23982 (or charset "iso-8859-1") date author style))
23984 (insert (or (plist-get opt-plist :preamble) ""))
23986 (when (plist-get opt-plist :auto-preamble)
23987 (if title (insert (format org-export-html-title-format
23988 (org-html-expand title))))))
23990 (if (and org-export-with-toc (not body-only))
23991 (progn
23992 (push (format "<h%d>%s</h%d>\n"
23993 org-export-html-toplevel-hlevel
23994 (nth 3 lang-words)
23995 org-export-html-toplevel-hlevel)
23996 thetoc)
23997 (push "<ul>\n<li>" thetoc)
23998 (setq lines
23999 (mapcar '(lambda (line)
24000 (if (string-match org-todo-line-regexp line)
24001 ;; This is a headline
24002 (progn
24003 (setq have-headings t)
24004 (setq level (- (match-end 1) (match-beginning 1))
24005 level (org-tr-level level)
24006 txt (save-match-data
24007 (org-html-expand
24008 (org-export-cleanup-toc-line
24009 (match-string 3 line))))
24010 todo
24011 (or (and org-export-mark-todo-in-toc
24012 (match-beginning 2)
24013 (not (member (match-string 2 line)
24014 org-done-keywords)))
24015 ; TODO, not DONE
24016 (and org-export-mark-todo-in-toc
24017 (= level umax-toc)
24018 (org-search-todo-below
24019 line lines level))))
24020 (if (string-match
24021 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
24022 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
24023 (if (string-match quote-re0 txt)
24024 (setq txt (replace-match "" t t txt)))
24025 (if org-export-with-section-numbers
24026 (setq txt (concat (org-section-number level)
24027 " " txt)))
24028 (if (<= level (max umax umax-toc))
24029 (setq head-count (+ head-count 1)))
24030 (if (<= level umax-toc)
24031 (progn
24032 (if (> level org-last-level)
24033 (progn
24034 (setq cnt (- level org-last-level))
24035 (while (>= (setq cnt (1- cnt)) 0)
24036 (push "\n<ul>\n<li>" thetoc))
24037 (push "\n" thetoc)))
24038 (if (< level org-last-level)
24039 (progn
24040 (setq cnt (- org-last-level level))
24041 (while (>= (setq cnt (1- cnt)) 0)
24042 (push "</li>\n</ul>" thetoc))
24043 (push "\n" thetoc)))
24044 ;; Check for targets
24045 (while (string-match org-target-regexp line)
24046 (setq tg (match-string 1 line)
24047 line (replace-match
24048 (concat "@<span class=\"target\">" tg "@</span> ")
24049 t t line))
24050 (push (cons (org-solidify-link-text tg)
24051 (format "sec-%d" head-count))
24052 target-alist))
24053 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
24054 (setq txt (replace-match "" t t txt)))
24055 (push
24056 (format
24057 (if todo
24058 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
24059 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
24060 head-count txt) thetoc)
24062 (setq org-last-level level))
24064 line)
24065 lines))
24066 (while (> org-last-level (1- org-min-level))
24067 (setq org-last-level (1- org-last-level))
24068 (push "</li>\n</ul>\n" thetoc))
24069 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24071 (setq head-count 0)
24072 (org-init-section-numbers)
24074 (while (setq line (pop lines) origline line)
24075 (catch 'nextline
24077 ;; end of quote section?
24078 (when (and inquote (string-match "^\\*+ " line))
24079 (insert "</pre>\n")
24080 (setq inquote nil))
24081 ;; inside a quote section?
24082 (when inquote
24083 (insert (org-html-protect line) "\n")
24084 (throw 'nextline nil))
24086 ;; verbatim lines
24087 (when (and org-export-with-fixed-width
24088 (string-match "^[ \t]*:\\(.*\\)" line))
24089 (when (not infixed)
24090 (setq infixed t)
24091 (insert "<pre>\n"))
24092 (insert (org-html-protect (match-string 1 line)) "\n")
24093 (when (and lines
24094 (not (string-match "^[ \t]*\\(:.*\\)"
24095 (car lines))))
24096 (setq infixed nil)
24097 (insert "</pre>\n"))
24098 (throw 'nextline nil))
24100 ;; Protected HTML
24101 (when (get-text-property 0 'org-protected line)
24102 (let (par)
24103 (when (re-search-backward
24104 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
24105 (setq par (match-string 1))
24106 (replace-match "\\2\n"))
24107 (insert line "\n")
24108 (while (and lines
24109 (get-text-property 0 'org-protected (car lines)))
24110 (insert (pop lines) "\n"))
24111 (and par (insert "<p>\n")))
24112 (throw 'nextline nil))
24114 ;; Horizontal line
24115 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
24116 (insert "\n<hr/>\n")
24117 (throw 'nextline nil))
24119 ;; make targets to anchors
24120 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
24121 (cond
24122 ((match-end 2)
24123 (setq line (replace-match
24124 (concat "@<a name=\""
24125 (org-solidify-link-text (match-string 1 line))
24126 "\">\\nbsp@</a>")
24127 t t line)))
24128 ((and org-export-with-toc (equal (string-to-char line) ?*))
24129 (setq line (replace-match
24130 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
24131 ; (concat "@<i>" (match-string 1 line) "@</i> ")
24132 t t line)))
24134 (setq line (replace-match
24135 (concat "@<a name=\""
24136 (org-solidify-link-text (match-string 1 line))
24137 "\" class=\"target\">" (match-string 1 line) "@</a> ")
24138 t t line)))))
24140 (setq line (org-html-handle-time-stamps line))
24142 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
24143 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
24144 ;; Also handle sub_superscripts and checkboxes
24145 (or (string-match org-table-hline-regexp line)
24146 (setq line (org-html-expand line)))
24148 ;; Format the links
24149 (setq start 0)
24150 (while (string-match org-bracket-link-analytic-regexp line start)
24151 (setq start (match-beginning 0))
24152 (setq type (if (match-end 2) (match-string 2 line) "internal"))
24153 (setq path (match-string 3 line))
24154 (setq desc1 (if (match-end 5) (match-string 5 line))
24155 desc2 (if (match-end 2) (concat type ":" path) path)
24156 descp (and desc1 (not (equal desc1 desc2)))
24157 desc (or desc1 desc2))
24158 ;; Make an image out of the description if that is so wanted
24159 (when (and descp (org-file-image-p desc))
24160 (save-match-data
24161 (if (string-match "^file:" desc)
24162 (setq desc (substring desc (match-end 0)))))
24163 (setq desc (concat "<img src=\"" desc "\"/>")))
24164 ;; FIXME: do we need to unescape here somewhere?
24165 (cond
24166 ((equal type "internal")
24167 (setq rpl
24168 (concat
24169 "<a href=\"#"
24170 (org-solidify-link-text
24171 (save-match-data (org-link-unescape path)) target-alist)
24172 "\">" desc "</a>")))
24173 ((member type '("http" "https"))
24174 ;; standard URL, just check if we need to inline an image
24175 (if (and (or (eq t org-export-html-inline-images)
24176 (and org-export-html-inline-images (not descp)))
24177 (org-file-image-p path))
24178 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
24179 (setq link (concat type ":" path))
24180 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
24181 ((member type '("ftp" "mailto" "news"))
24182 ;; standard URL
24183 (setq link (concat type ":" path))
24184 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
24185 ((string= type "file")
24186 ;; FILE link
24187 (let* ((filename path)
24188 (abs-p (file-name-absolute-p filename))
24189 thefile file-is-image-p search)
24190 (save-match-data
24191 (if (string-match "::\\(.*\\)" filename)
24192 (setq search (match-string 1 filename)
24193 filename (replace-match "" t nil filename)))
24194 (setq valid
24195 (if (functionp link-validate)
24196 (funcall link-validate filename current-dir)
24198 (setq file-is-image-p (org-file-image-p filename))
24199 (setq thefile (if abs-p (expand-file-name filename) filename))
24200 (when (and org-export-html-link-org-files-as-html
24201 (string-match "\\.org$" thefile))
24202 (setq thefile (concat (substring thefile 0
24203 (match-beginning 0))
24204 "." org-export-html-extension))
24205 (if (and search
24206 ;; make sure this is can be used as target search
24207 (not (string-match "^[0-9]*$" search))
24208 (not (string-match "^\\*" search))
24209 (not (string-match "^/.*/$" search)))
24210 (setq thefile (concat thefile "#"
24211 (org-solidify-link-text
24212 (org-link-unescape search)))))
24213 (when (string-match "^file:" desc)
24214 (setq desc (replace-match "" t t desc))
24215 (if (string-match "\\.org$" desc)
24216 (setq desc (replace-match "" t t desc))))))
24217 (setq rpl (if (and file-is-image-p
24218 (or (eq t org-export-html-inline-images)
24219 (and org-export-html-inline-images
24220 (not descp))))
24221 (concat "<img src=\"" thefile "\"/>")
24222 (concat "<a href=\"" thefile "\">" desc "</a>")))
24223 (if (not valid) (setq rpl desc))))
24224 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
24225 (setq rpl (concat "<i>&lt;" type ":"
24226 (save-match-data (org-link-unescape path))
24227 "&gt;</i>"))))
24228 (setq line (replace-match rpl t t line)
24229 start (+ start (length rpl))))
24231 ;; TODO items
24232 (if (and (string-match org-todo-line-regexp line)
24233 (match-beginning 2))
24235 (setq line
24236 (concat (substring line 0 (match-beginning 2))
24237 "<span class=\""
24238 (if (member (match-string 2 line)
24239 org-done-keywords)
24240 "done" "todo")
24241 "\">" (match-string 2 line)
24242 "</span>" (substring line (match-end 2)))))
24244 ;; Does this contain a reference to a footnote?
24245 (when org-export-with-footnotes
24246 (setq start 0)
24247 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
24248 (if (get-text-property (match-beginning 2) 'org-protected line)
24249 (setq start (match-end 2))
24250 (let ((n (match-string 2 line)))
24251 (setq line
24252 (replace-match
24253 (format
24254 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
24255 (match-string 1 line) n n n)
24256 t t line))))))
24258 (cond
24259 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24260 ;; This is a headline
24261 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24262 txt (match-string 2 line))
24263 (if (string-match quote-re0 txt)
24264 (setq txt (replace-match "" t t txt)))
24265 (if (<= level (max umax umax-toc))
24266 (setq head-count (+ head-count 1)))
24267 (when in-local-list
24268 ;; Close any local lists before inserting a new header line
24269 (while local-list-num
24270 (org-close-li)
24271 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24272 (pop local-list-num))
24273 (setq local-list-indent nil
24274 in-local-list nil))
24275 (setq first-heading-pos (or first-heading-pos (point)))
24276 (org-html-level-start level txt umax
24277 (and org-export-with-toc (<= level umax))
24278 head-count)
24279 ;; QUOTES
24280 (when (string-match quote-re line)
24281 (insert "<pre>")
24282 (setq inquote t)))
24284 ((and org-export-with-tables
24285 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24286 (if (not table-open)
24287 ;; New table starts
24288 (setq table-open t table-buffer nil table-orig-buffer nil))
24289 ;; Accumulate lines
24290 (setq table-buffer (cons line table-buffer)
24291 table-orig-buffer (cons origline table-orig-buffer))
24292 (when (or (not lines)
24293 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24294 (car lines))))
24295 (setq table-open nil
24296 table-buffer (nreverse table-buffer)
24297 table-orig-buffer (nreverse table-orig-buffer))
24298 (org-close-par-maybe)
24299 (insert (org-format-table-html table-buffer table-orig-buffer))))
24301 ;; Normal lines
24302 (when (string-match
24303 (cond
24304 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24305 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24306 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
24307 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
24308 line)
24309 (setq ind (org-get-string-indentation line)
24310 start-is-num (match-beginning 4)
24311 starter (if (match-beginning 2)
24312 (substring (match-string 2 line) 0 -1))
24313 line (substring line (match-beginning 5)))
24314 (unless (string-match "[^ \t]" line)
24315 ;; empty line. Pretend indentation is large.
24316 (setq ind (if org-empty-line-terminates-plain-lists
24318 (1+ (or (car local-list-indent) 1)))))
24319 (setq didclose nil)
24320 (while (and in-local-list
24321 (or (and (= ind (car local-list-indent))
24322 (not starter))
24323 (< ind (car local-list-indent))))
24324 (setq didclose t)
24325 (org-close-li)
24326 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
24327 (pop local-list-num) (pop local-list-indent)
24328 (setq in-local-list local-list-indent))
24329 (cond
24330 ((and starter
24331 (or (not in-local-list)
24332 (> ind (car local-list-indent))))
24333 ;; Start new (level of) list
24334 (org-close-par-maybe)
24335 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
24336 (push start-is-num local-list-num)
24337 (push ind local-list-indent)
24338 (setq in-local-list t))
24339 (starter
24340 ;; continue current list
24341 (org-close-li)
24342 (insert "<li>\n"))
24343 (didclose
24344 ;; we did close a list, normal text follows: need <p>
24345 (org-open-par)))
24346 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
24347 (setq line
24348 (replace-match
24349 (if (equal (match-string 1 line) "X")
24350 "<b>[X]</b>"
24351 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
24352 t t line))))
24354 ;; Empty lines start a new paragraph. If hand-formatted lists
24355 ;; are not fully interpreted, lines starting with "-", "+", "*"
24356 ;; also start a new paragraph.
24357 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
24359 ;; Is this the start of a footnote?
24360 (when org-export-with-footnotes
24361 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
24362 (org-close-par-maybe)
24363 (let ((n (match-string 1 line)))
24364 (setq line (replace-match
24365 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
24367 ;; Check if the line break needs to be conserved
24368 (cond
24369 ((string-match "\\\\\\\\[ \t]*$" line)
24370 (setq line (replace-match "<br/>" t t line)))
24371 (org-export-preserve-breaks
24372 (setq line (concat line "<br/>"))))
24374 (insert line "\n")))))
24376 ;; Properly close all local lists and other lists
24377 (when inquote (insert "</pre>\n"))
24378 (when in-local-list
24379 ;; Close any local lists before inserting a new header line
24380 (while local-list-num
24381 (org-close-li)
24382 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
24383 (pop local-list-num))
24384 (setq local-list-indent nil
24385 in-local-list nil))
24386 (org-html-level-start 1 nil umax
24387 (and org-export-with-toc (<= level umax))
24388 head-count)
24390 (unless body-only
24391 (when (plist-get opt-plist :auto-postamble)
24392 (insert "<div id=\"postamble\">")
24393 (when (and org-export-author-info author)
24394 (insert "<p class=\"author\"> "
24395 (nth 1 lang-words) ": " author "\n")
24396 (when email
24397 (if (listp (split-string email ",+ *"))
24398 (mapc (lambda(e)
24399 (insert "<a href=\"mailto:" e "\">&lt;"
24400 e "&gt;</a>\n"))
24401 (split-string email ",+ *"))
24402 (insert "<a href=\"mailto:" email "\">&lt;"
24403 email "&gt;</a>\n")))
24404 (insert "</p>\n"))
24405 (when (and date org-export-time-stamp-file)
24406 (insert "<p class=\"date\"> "
24407 (nth 2 lang-words) ": "
24408 date "</p>\n"))
24409 (insert "</div>"))
24411 (if org-export-html-with-timestamp
24412 (insert org-export-html-html-helper-timestamp))
24413 (insert (or (plist-get opt-plist :postamble) ""))
24414 (insert "</body>\n</html>\n"))
24416 (normal-mode)
24417 (if (eq major-mode default-major-mode) (html-mode))
24419 ;; insert the table of contents
24420 (goto-char (point-min))
24421 (when thetoc
24422 (if (or (re-search-forward
24423 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
24424 (re-search-forward
24425 "\\[TABLE-OF-CONTENTS\\]" nil t))
24426 (progn
24427 (goto-char (match-beginning 0))
24428 (replace-match ""))
24429 (goto-char first-heading-pos)
24430 (when (looking-at "\\s-*</p>")
24431 (goto-char (match-end 0))
24432 (insert "\n")))
24433 (insert "<div id=\"table-of-contents\">\n")
24434 (mapc 'insert thetoc)
24435 (insert "</div>\n"))
24436 ;; remove empty paragraphs and lists
24437 (goto-char (point-min))
24438 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
24439 (replace-match ""))
24440 (goto-char (point-min))
24441 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
24442 (replace-match ""))
24443 ;; Convert whitespace place holders
24444 (goto-char (point-min))
24445 (let (beg end n)
24446 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24447 (setq n (get-text-property beg 'org-whitespace)
24448 end (next-single-property-change beg 'org-whitespace))
24449 (goto-char beg)
24450 (delete-region beg end)
24451 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
24452 (make-string n ?x)))))
24454 (or to-buffer (save-buffer))
24455 (goto-char (point-min))
24456 (message "Exporting... done")
24457 (if (eq to-buffer 'string)
24458 (prog1 (buffer-substring (point-min) (point-max))
24459 (kill-buffer (current-buffer)))
24460 (current-buffer)))))
24462 (defvar org-table-colgroup-info nil)
24463 (defun org-format-table-ascii (lines)
24464 "Format a table for ascii export."
24465 (if (stringp lines)
24466 (setq lines (org-split-string lines "\n")))
24467 (if (not (string-match "^[ \t]*|" (car lines)))
24468 ;; Table made by table.el - test for spanning
24469 lines
24471 ;; A normal org table
24472 ;; Get rid of hlines at beginning and end
24473 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24474 (setq lines (nreverse lines))
24475 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24476 (setq lines (nreverse lines))
24477 (when org-export-table-remove-special-lines
24478 ;; Check if the table has a marking column. If yes remove the
24479 ;; column and the special lines
24480 (setq lines (org-table-clean-before-export lines)))
24481 ;; Get rid of the vertical lines except for grouping
24482 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
24483 rtn line vl1 start)
24484 (while (setq line (pop lines))
24485 (if (string-match org-table-hline-regexp line)
24486 (and (string-match "|\\(.*\\)|" line)
24487 (setq line (replace-match " \\1" t nil line)))
24488 (setq start 0 vl1 vl)
24489 (while (string-match "|" line start)
24490 (setq start (match-end 0))
24491 (or (pop vl1) (setq line (replace-match " " t t line)))))
24492 (push line rtn))
24493 (nreverse rtn))))
24495 (defun org-colgroup-info-to-vline-list (info)
24496 (let (vl new last)
24497 (while info
24498 (setq last new new (pop info))
24499 (if (or (memq last '(:end :startend))
24500 (memq new '(:start :startend)))
24501 (push t vl)
24502 (push nil vl)))
24503 (setq vl (nreverse vl))
24504 (and vl (setcar vl nil))
24505 vl))
24507 (defun org-format-table-html (lines olines)
24508 "Find out which HTML converter to use and return the HTML code."
24509 (if (stringp lines)
24510 (setq lines (org-split-string lines "\n")))
24511 (if (string-match "^[ \t]*|" (car lines))
24512 ;; A normal org table
24513 (org-format-org-table-html lines)
24514 ;; Table made by table.el - test for spanning
24515 (let* ((hlines (delq nil (mapcar
24516 (lambda (x)
24517 (if (string-match "^[ \t]*\\+-" x) x
24518 nil))
24519 lines)))
24520 (first (car hlines))
24521 (ll (and (string-match "\\S-+" first)
24522 (match-string 0 first)))
24523 (re (concat "^[ \t]*" (regexp-quote ll)))
24524 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
24525 hlines))))
24526 (if (and (not spanning)
24527 (not org-export-prefer-native-exporter-for-tables))
24528 ;; We can use my own converter with HTML conversions
24529 (org-format-table-table-html lines)
24530 ;; Need to use the code generator in table.el, with the original text.
24531 (org-format-table-table-html-using-table-generate-source olines)))))
24533 (defun org-format-org-table-html (lines &optional splice)
24534 "Format a table into HTML."
24535 ;; Get rid of hlines at beginning and end
24536 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24537 (setq lines (nreverse lines))
24538 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
24539 (setq lines (nreverse lines))
24540 (when org-export-table-remove-special-lines
24541 ;; Check if the table has a marking column. If yes remove the
24542 ;; column and the special lines
24543 (setq lines (org-table-clean-before-export lines)))
24545 (let ((head (and org-export-highlight-first-table-line
24546 (delq nil (mapcar
24547 (lambda (x) (string-match "^[ \t]*|-" x))
24548 (cdr lines)))))
24549 (nlines 0) fnum i
24550 tbopen line fields html gr colgropen)
24551 (if splice (setq head nil))
24552 (unless splice (push (if head "<thead>" "<tbody>") html))
24553 (setq tbopen t)
24554 (while (setq line (pop lines))
24555 (catch 'next-line
24556 (if (string-match "^[ \t]*|-" line)
24557 (progn
24558 (unless splice
24559 (push (if head "</thead>" "</tbody>") html)
24560 (if lines (push "<tbody>" html) (setq tbopen nil)))
24561 (setq head nil) ;; head ends here, first time around
24562 ;; ignore this line
24563 (throw 'next-line t)))
24564 ;; Break the line into fields
24565 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24566 (unless fnum (setq fnum (make-vector (length fields) 0)))
24567 (setq nlines (1+ nlines) i -1)
24568 (push (concat "<tr>"
24569 (mapconcat
24570 (lambda (x)
24571 (setq i (1+ i))
24572 (if (and (< i nlines)
24573 (string-match org-table-number-regexp x))
24574 (incf (aref fnum i)))
24575 (if head
24576 (concat (car org-export-table-header-tags) x
24577 (cdr org-export-table-header-tags))
24578 (concat (car org-export-table-data-tags) x
24579 (cdr org-export-table-data-tags))))
24580 fields "")
24581 "</tr>")
24582 html)))
24583 (unless splice (if tbopen (push "</tbody>" html)))
24584 (unless splice (push "</table>\n" html))
24585 (setq html (nreverse html))
24586 (unless splice
24587 ;; Put in col tags with the alignment (unfortuntely often ignored...)
24588 (push (mapconcat
24589 (lambda (x)
24590 (setq gr (pop org-table-colgroup-info))
24591 (format "%s<col align=\"%s\"></col>%s"
24592 (if (memq gr '(:start :startend))
24593 (prog1
24594 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
24595 (setq colgropen t))
24597 (if (> (/ (float x) nlines) org-table-number-fraction)
24598 "right" "left")
24599 (if (memq gr '(:end :startend))
24600 (progn (setq colgropen nil) "</colgroup>")
24601 "")))
24602 fnum "")
24603 html)
24604 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
24605 (push html-table-tag html))
24606 (concat (mapconcat 'identity html "\n") "\n")))
24608 (defun org-table-clean-before-export (lines)
24609 "Check if the table has a marking column.
24610 If yes remove the column and the special lines."
24611 (setq org-table-colgroup-info nil)
24612 (if (memq nil
24613 (mapcar
24614 (lambda (x) (or (string-match "^[ \t]*|-" x)
24615 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
24616 lines))
24617 (progn
24618 (setq org-table-clean-did-remove-column nil)
24619 (delq nil
24620 (mapcar
24621 (lambda (x)
24622 (cond
24623 ((string-match "^[ \t]*| */ *|" x)
24624 (setq org-table-colgroup-info
24625 (mapcar (lambda (x)
24626 (cond ((member x '("<" "&lt;")) :start)
24627 ((member x '(">" "&gt;")) :end)
24628 ((member x '("<>" "&lt;&gt;")) :startend)
24629 (t nil)))
24630 (org-split-string x "[ \t]*|[ \t]*")))
24631 nil)
24632 (t x)))
24633 lines)))
24634 (setq org-table-clean-did-remove-column t)
24635 (delq nil
24636 (mapcar
24637 (lambda (x)
24638 (cond
24639 ((string-match "^[ \t]*| */ *|" x)
24640 (setq org-table-colgroup-info
24641 (mapcar (lambda (x)
24642 (cond ((member x '("<" "&lt;")) :start)
24643 ((member x '(">" "&gt;")) :end)
24644 ((member x '("<>" "&lt;&gt;")) :startend)
24645 (t nil)))
24646 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
24647 nil)
24648 ((string-match "^[ \t]*| *[!_^/] *|" x)
24649 nil) ; ignore this line
24650 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
24651 (string-match "^\\([ \t]*\\)|[^|]*|" x))
24652 ;; remove the first column
24653 (replace-match "\\1|" t nil x))))
24654 lines))))
24656 (defun org-format-table-table-html (lines)
24657 "Format a table generated by table.el into HTML.
24658 This conversion does *not* use `table-generate-source' from table.el.
24659 This has the advantage that Org-mode's HTML conversions can be used.
24660 But it has the disadvantage, that no cell- or row-spanning is allowed."
24661 (let (line field-buffer
24662 (head org-export-highlight-first-table-line)
24663 fields html empty)
24664 (setq html (concat html-table-tag "\n"))
24665 (while (setq line (pop lines))
24666 (setq empty "&nbsp;")
24667 (catch 'next-line
24668 (if (string-match "^[ \t]*\\+-" line)
24669 (progn
24670 (if field-buffer
24671 (progn
24672 (setq
24673 html
24674 (concat
24675 html
24676 "<tr>"
24677 (mapconcat
24678 (lambda (x)
24679 (if (equal x "") (setq x empty))
24680 (if head
24681 (concat (car org-export-table-header-tags) x
24682 (cdr org-export-table-header-tags))
24683 (concat (car org-export-table-data-tags) x
24684 (cdr org-export-table-data-tags))))
24685 field-buffer "\n")
24686 "</tr>\n"))
24687 (setq head nil)
24688 (setq field-buffer nil)))
24689 ;; Ignore this line
24690 (throw 'next-line t)))
24691 ;; Break the line into fields and store the fields
24692 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
24693 (if field-buffer
24694 (setq field-buffer (mapcar
24695 (lambda (x)
24696 (concat x "<br/>" (pop fields)))
24697 field-buffer))
24698 (setq field-buffer fields))))
24699 (setq html (concat html "</table>\n"))
24700 html))
24702 (defun org-format-table-table-html-using-table-generate-source (lines)
24703 "Format a table into html, using `table-generate-source' from table.el.
24704 This has the advantage that cell- or row-spanning is allowed.
24705 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
24706 (require 'table)
24707 (with-current-buffer (get-buffer-create " org-tmp1 ")
24708 (erase-buffer)
24709 (insert (mapconcat 'identity lines "\n"))
24710 (goto-char (point-min))
24711 (if (not (re-search-forward "|[^+]" nil t))
24712 (error "Error processing table"))
24713 (table-recognize-table)
24714 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
24715 (table-generate-source 'html " org-tmp2 ")
24716 (set-buffer " org-tmp2 ")
24717 (buffer-substring (point-min) (point-max))))
24719 (defun org-html-handle-time-stamps (s)
24720 "Format time stamps in string S, or remove them."
24721 (catch 'exit
24722 (let (r b)
24723 (while (string-match org-maybe-keyword-time-regexp s)
24724 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
24725 ;; never export CLOCK
24726 (throw 'exit ""))
24727 (or b (setq b (substring s 0 (match-beginning 0))))
24728 (if (not org-export-with-timestamps)
24729 (setq r (concat r (substring s 0 (match-beginning 0)))
24730 s (substring s (match-end 0)))
24731 (setq r (concat
24732 r (substring s 0 (match-beginning 0))
24733 (if (match-end 1)
24734 (format "@<span class=\"timestamp-kwd\">%s @</span>"
24735 (match-string 1 s)))
24736 (format " @<span class=\"timestamp\">%s@</span>"
24737 (substring
24738 (org-translate-time (match-string 3 s)) 1 -1)))
24739 s (substring s (match-end 0)))))
24740 ;; Line break if line started and ended with time stamp stuff
24741 (if (not r)
24743 (setq r (concat r s))
24744 (unless (string-match "\\S-" (concat b s))
24745 (setq r (concat r "@<br/>")))
24746 r))))
24748 (defun org-html-protect (s)
24749 ;; convert & to &amp;, < to &lt; and > to &gt;
24750 (let ((start 0))
24751 (while (string-match "&" s start)
24752 (setq s (replace-match "&amp;" t t s)
24753 start (1+ (match-beginning 0))))
24754 (while (string-match "<" s)
24755 (setq s (replace-match "&lt;" t t s)))
24756 (while (string-match ">" s)
24757 (setq s (replace-match "&gt;" t t s))))
24760 (defun org-export-cleanup-toc-line (s)
24761 "Remove tags and time staps from lines going into the toc."
24762 (when (memq org-export-with-tags '(not-in-toc nil))
24763 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
24764 (setq s (replace-match "" t t s))))
24765 (when org-export-remove-timestamps-from-toc
24766 (while (string-match org-maybe-keyword-time-regexp s)
24767 (setq s (replace-match "" t t s))))
24768 (while (string-match org-bracket-link-regexp s)
24769 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
24770 t t s)))
24773 (defun org-html-expand (string)
24774 "Prepare STRING for HTML export. Applies all active conversions.
24775 If there are links in the string, don't modify these."
24776 (let* ((re (concat org-bracket-link-regexp "\\|"
24777 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
24778 m s l res)
24779 (while (setq m (string-match re string))
24780 (setq s (substring string 0 m)
24781 l (match-string 0 string)
24782 string (substring string (match-end 0)))
24783 (push (org-html-do-expand s) res)
24784 (push l res))
24785 (push (org-html-do-expand string) res)
24786 (apply 'concat (nreverse res))))
24788 (defun org-html-do-expand (s)
24789 "Apply all active conversions to translate special ASCII to HTML."
24790 (setq s (org-html-protect s))
24791 (if org-export-html-expand
24792 (let ((start 0))
24793 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
24794 (setq s (replace-match "<\\1>" t nil s)))))
24795 (if org-export-with-emphasize
24796 (setq s (org-export-html-convert-emphasize s)))
24797 (if org-export-with-special-strings
24798 (setq s (org-export-html-convert-special-strings s)))
24799 (if org-export-with-sub-superscripts
24800 (setq s (org-export-html-convert-sub-super s)))
24801 (if org-export-with-TeX-macros
24802 (let ((start 0) wd ass)
24803 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
24804 (if (get-text-property (match-beginning 0) 'org-protected s)
24805 (setq start (match-end 0))
24806 (setq wd (match-string 1 s))
24807 (if (setq ass (assoc wd org-html-entities))
24808 (setq s (replace-match (or (cdr ass)
24809 (concat "&" (car ass) ";"))
24810 t t s))
24811 (setq start (+ start (length wd))))))))
24814 (defun org-create-multibrace-regexp (left right n)
24815 "Create a regular expression which will match a balanced sexp.
24816 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
24817 as single character strings.
24818 The regexp returned will match the entire expression including the
24819 delimiters. It will also define a single group which contains the
24820 match except for the outermost delimiters. The maximum depth of
24821 stacked delimiters is N. Escaping delimiters is not possible."
24822 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
24823 (or "\\|")
24824 (re nothing)
24825 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
24826 (while (> n 1)
24827 (setq n (1- n)
24828 re (concat re or next)
24829 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
24830 (concat left "\\(" re "\\)" right)))
24832 (defvar org-match-substring-regexp
24833 (concat
24834 "\\([^\\]\\)\\([_^]\\)\\("
24835 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24836 "\\|"
24837 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
24838 "\\|"
24839 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
24840 "The regular expression matching a sub- or superscript.")
24842 (defvar org-match-substring-with-braces-regexp
24843 (concat
24844 "\\([^\\]\\)\\([_^]\\)\\("
24845 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
24846 "\\)")
24847 "The regular expression matching a sub- or superscript, forcing braces.")
24849 (defconst org-export-html-special-string-regexps
24850 '(("\\\\-" . "&shy;")
24851 ("---\\([^-]\\)" . "&mdash;\\1")
24852 ("--\\([^-]\\)" . "&ndash;\\1")
24853 ("\\.\\.\\." . "&hellip;"))
24854 "Regular expressions for special string conversion.")
24856 (defun org-export-html-convert-special-strings (string)
24857 "Convert special characters in STRING to HTML."
24858 (let ((all org-export-html-special-string-regexps)
24859 e a re rpl start)
24860 (while (setq a (pop all))
24861 (setq re (car a) rpl (cdr a) start 0)
24862 (while (string-match re string start)
24863 (if (get-text-property (match-beginning 0) 'org-protected string)
24864 (setq start (match-end 0))
24865 (setq string (replace-match rpl t nil string)))))
24866 string))
24868 (defun org-export-html-convert-sub-super (string)
24869 "Convert sub- and superscripts in STRING to HTML."
24870 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
24871 (while (string-match org-match-substring-regexp string s)
24872 (cond
24873 ((and requireb (match-end 8)) (setq s (match-end 2)))
24874 ((get-text-property (match-beginning 2) 'org-protected string)
24875 (setq s (match-end 2)))
24877 (setq s (match-end 1)
24878 key (if (string= (match-string 2 string) "_") "sub" "sup")
24879 c (or (match-string 8 string)
24880 (match-string 6 string)
24881 (match-string 5 string))
24882 string (replace-match
24883 (concat (match-string 1 string)
24884 "<" key ">" c "</" key ">")
24885 t t string)))))
24886 (while (string-match "\\\\\\([_^]\\)" string)
24887 (setq string (replace-match (match-string 1 string) t t string)))
24888 string))
24890 (defun org-export-html-convert-emphasize (string)
24891 "Apply emphasis."
24892 (let ((s 0) rpl)
24893 (while (string-match org-emph-re string s)
24894 (if (not (equal
24895 (substring string (match-beginning 3) (1+ (match-beginning 3)))
24896 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
24897 (setq s (match-beginning 0)
24899 (concat
24900 (match-string 1 string)
24901 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
24902 (match-string 4 string)
24903 (nth 3 (assoc (match-string 3 string)
24904 org-emphasis-alist))
24905 (match-string 5 string))
24906 string (replace-match rpl t t string)
24907 s (+ s (- (length rpl) 2)))
24908 (setq s (1+ s))))
24909 string))
24911 (defvar org-par-open nil)
24912 (defun org-open-par ()
24913 "Insert <p>, but first close previous paragraph if any."
24914 (org-close-par-maybe)
24915 (insert "\n<p>")
24916 (setq org-par-open t))
24917 (defun org-close-par-maybe ()
24918 "Close paragraph if there is one open."
24919 (when org-par-open
24920 (insert "</p>")
24921 (setq org-par-open nil)))
24922 (defun org-close-li ()
24923 "Close <li> if necessary."
24924 (org-close-par-maybe)
24925 (insert "</li>\n"))
24927 (defvar body-only) ; dynamically scoped into this.
24928 (defun org-html-level-start (level title umax with-toc head-count)
24929 "Insert a new level in HTML export.
24930 When TITLE is nil, just close all open levels."
24931 (org-close-par-maybe)
24932 (let ((l org-level-max))
24933 (while (>= l level)
24934 (if (aref org-levels-open (1- l))
24935 (progn
24936 (org-html-level-close l umax)
24937 (aset org-levels-open (1- l) nil)))
24938 (setq l (1- l)))
24939 (when title
24940 ;; If title is nil, this means this function is called to close
24941 ;; all levels, so the rest is done only if title is given
24942 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
24943 (setq title (replace-match
24944 (if org-export-with-tags
24945 (save-match-data
24946 (concat
24947 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
24948 (mapconcat 'identity (org-split-string
24949 (match-string 1 title) ":")
24950 "&nbsp;")
24951 "</span>"))
24953 t t title)))
24954 (if (> level umax)
24955 (progn
24956 (if (aref org-levels-open (1- level))
24957 (progn
24958 (org-close-li)
24959 (insert "<li>" title "<br/>\n"))
24960 (aset org-levels-open (1- level) t)
24961 (org-close-par-maybe)
24962 (insert "<ul>\n<li>" title "<br/>\n")))
24963 (aset org-levels-open (1- level) t)
24964 (if (and org-export-with-section-numbers (not body-only))
24965 (setq title (concat (org-section-number level) " " title)))
24966 (setq level (+ level org-export-html-toplevel-hlevel -1))
24967 (if with-toc
24968 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
24969 level level head-count title level))
24970 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
24971 (org-open-par)))))
24973 (defun org-html-level-close (level max-outline-level)
24974 "Terminate one level in HTML export."
24975 (if (<= level max-outline-level)
24976 (insert "</div>\n")
24977 (org-close-li)
24978 (insert "</ul>\n")))
24980 ;;; iCalendar export
24982 ;;;###autoload
24983 (defun org-export-icalendar-this-file ()
24984 "Export current file as an iCalendar file.
24985 The iCalendar file will be located in the same directory as the Org-mode
24986 file, but with extension `.ics'."
24987 (interactive)
24988 (org-export-icalendar nil buffer-file-name))
24990 ;;;###autoload
24991 (defun org-export-icalendar-all-agenda-files ()
24992 "Export all files in `org-agenda-files' to iCalendar .ics files.
24993 Each iCalendar file will be located in the same directory as the Org-mode
24994 file, but with extension `.ics'."
24995 (interactive)
24996 (apply 'org-export-icalendar nil (org-agenda-files t)))
24998 ;;;###autoload
24999 (defun org-export-icalendar-combine-agenda-files ()
25000 "Export all files in `org-agenda-files' to a single combined iCalendar file.
25001 The file is stored under the name `org-combined-agenda-icalendar-file'."
25002 (interactive)
25003 (apply 'org-export-icalendar t (org-agenda-files t)))
25005 (defun org-export-icalendar (combine &rest files)
25006 "Create iCalendar files for all elements of FILES.
25007 If COMBINE is non-nil, combine all calendar entries into a single large
25008 file and store it under the name `org-combined-agenda-icalendar-file'."
25009 (save-excursion
25010 (org-prepare-agenda-buffers files)
25011 (let* ((dir (org-export-directory
25012 :ical (list :publishing-directory
25013 org-export-publishing-directory)))
25014 file ical-file ical-buffer category started org-agenda-new-buffers)
25016 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
25017 (when combine
25018 (setq ical-file
25019 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
25020 org-combined-agenda-icalendar-file
25021 (expand-file-name org-combined-agenda-icalendar-file dir))
25022 ical-buffer (org-get-agenda-file-buffer ical-file))
25023 (set-buffer ical-buffer) (erase-buffer))
25024 (while (setq file (pop files))
25025 (catch 'nextfile
25026 (org-check-agenda-file file)
25027 (set-buffer (org-get-agenda-file-buffer file))
25028 (unless combine
25029 (setq ical-file (concat (file-name-as-directory dir)
25030 (file-name-sans-extension
25031 (file-name-nondirectory buffer-file-name))
25032 ".ics"))
25033 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
25034 (with-current-buffer ical-buffer (erase-buffer)))
25035 (setq category (or org-category
25036 (file-name-sans-extension
25037 (file-name-nondirectory buffer-file-name))))
25038 (if (symbolp category) (setq category (symbol-name category)))
25039 (let ((standard-output ical-buffer))
25040 (if combine
25041 (and (not started) (setq started t)
25042 (org-start-icalendar-file org-icalendar-combined-name))
25043 (org-start-icalendar-file category))
25044 (org-print-icalendar-entries combine)
25045 (when (or (and combine (not files)) (not combine))
25046 (org-finish-icalendar-file)
25047 (set-buffer ical-buffer)
25048 (save-buffer)
25049 (run-hooks 'org-after-save-iCalendar-file-hook)))))
25050 (org-release-buffers org-agenda-new-buffers))))
25052 (defvar org-after-save-iCalendar-file-hook nil
25053 "Hook run after an iCalendar file has been saved.
25054 The iCalendar buffer is still current when this hook is run.
25055 A good way to use this is to tell a desktop calenndar application to re-read
25056 the iCalendar file.")
25058 (defun org-print-icalendar-entries (&optional combine)
25059 "Print iCalendar entries for the current Org-mode file to `standard-output'.
25060 When COMBINE is non nil, add the category to each line."
25061 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
25062 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
25063 (dts (org-ical-ts-to-string
25064 (format-time-string (cdr org-time-stamp-formats) (current-time))
25065 "DTSTART"))
25066 hd ts ts2 state status (inc t) pos b sexp rrule
25067 scheduledp deadlinep tmp pri category entry location summary desc
25068 (sexp-buffer (get-buffer-create "*ical-tmp*")))
25069 (org-refresh-category-properties)
25070 (save-excursion
25071 (goto-char (point-min))
25072 (while (re-search-forward re1 nil t)
25073 (catch :skip
25074 (org-agenda-skip)
25075 (setq pos (match-beginning 0)
25076 ts (match-string 0)
25077 inc t
25078 hd (org-get-heading)
25079 summary (org-icalendar-cleanup-string
25080 (org-entry-get nil "SUMMARY"))
25081 desc (org-icalendar-cleanup-string
25082 (or (org-entry-get nil "DESCRIPTION")
25083 (and org-icalendar-include-body (org-get-entry)))
25084 t org-icalendar-include-body)
25085 location (org-icalendar-cleanup-string
25086 (org-entry-get nil "LOCATION"))
25087 category (org-get-category))
25088 (if (looking-at re2)
25089 (progn
25090 (goto-char (match-end 0))
25091 (setq ts2 (match-string 1) inc nil))
25092 (setq tmp (buffer-substring (max (point-min)
25093 (- pos org-ds-keyword-length))
25094 pos)
25095 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
25096 (progn
25097 (setq inc nil)
25098 (replace-match "\\1" t nil ts))
25100 deadlinep (string-match org-deadline-regexp tmp)
25101 scheduledp (string-match org-scheduled-regexp tmp)
25102 ;; donep (org-entry-is-done-p)
25104 (if (or (string-match org-tr-regexp hd)
25105 (string-match org-ts-regexp hd))
25106 (setq hd (replace-match "" t t hd)))
25107 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
25108 (setq rrule
25109 (concat "\nRRULE:FREQ="
25110 (cdr (assoc
25111 (match-string 2 ts)
25112 '(("d" . "DAILY")("w" . "WEEKLY")
25113 ("m" . "MONTHLY")("y" . "YEARLY"))))
25114 ";INTERVAL=" (match-string 1 ts)))
25115 (setq rrule ""))
25116 (setq summary (or summary hd))
25117 (if (string-match org-bracket-link-regexp summary)
25118 (setq summary
25119 (replace-match (if (match-end 3)
25120 (match-string 3 summary)
25121 (match-string 1 summary))
25122 t t summary)))
25123 (if deadlinep (setq summary (concat "DL: " summary)))
25124 (if scheduledp (setq summary (concat "S: " summary)))
25125 (if (string-match "\\`<%%" ts)
25126 (with-current-buffer sexp-buffer
25127 (insert (substring ts 1 -1) " " summary "\n"))
25128 (princ (format "BEGIN:VEVENT
25130 %s%s
25131 SUMMARY:%s%s%s
25132 CATEGORIES:%s
25133 END:VEVENT\n"
25134 (org-ical-ts-to-string ts "DTSTART")
25135 (org-ical-ts-to-string ts2 "DTEND" inc)
25136 rrule summary
25137 (if (and desc (string-match "\\S-" desc))
25138 (concat "\nDESCRIPTION: " desc) "")
25139 (if (and location (string-match "\\S-" location))
25140 (concat "\nLOCATION: " location) "")
25141 category)))))
25143 (when (and org-icalendar-include-sexps
25144 (condition-case nil (require 'icalendar) (error nil))
25145 (fboundp 'icalendar-export-region))
25146 ;; Get all the literal sexps
25147 (goto-char (point-min))
25148 (while (re-search-forward "^&?%%(" nil t)
25149 (catch :skip
25150 (org-agenda-skip)
25151 (setq b (match-beginning 0))
25152 (goto-char (1- (match-end 0)))
25153 (forward-sexp 1)
25154 (end-of-line 1)
25155 (setq sexp (buffer-substring b (point)))
25156 (with-current-buffer sexp-buffer
25157 (insert sexp "\n"))
25158 (princ (org-diary-to-ical-string sexp-buffer)))))
25160 (when org-icalendar-include-todo
25161 (goto-char (point-min))
25162 (while (re-search-forward org-todo-line-regexp nil t)
25163 (catch :skip
25164 (org-agenda-skip)
25165 (setq state (match-string 2))
25166 (setq status (if (member state org-done-keywords)
25167 "COMPLETED" "NEEDS-ACTION"))
25168 (when (and state
25169 (or (not (member state org-done-keywords))
25170 (eq org-icalendar-include-todo 'all))
25171 (not (member org-archive-tag (org-get-tags-at)))
25173 (setq hd (match-string 3)
25174 summary (org-icalendar-cleanup-string
25175 (org-entry-get nil "SUMMARY"))
25176 desc (org-icalendar-cleanup-string
25177 (or (org-entry-get nil "DESCRIPTION")
25178 (and org-icalendar-include-body (org-get-entry)))
25179 t org-icalendar-include-body)
25180 location (org-icalendar-cleanup-string
25181 (org-entry-get nil "LOCATION")))
25182 (if (string-match org-bracket-link-regexp hd)
25183 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
25184 (match-string 1 hd))
25185 t t hd)))
25186 (if (string-match org-priority-regexp hd)
25187 (setq pri (string-to-char (match-string 2 hd))
25188 hd (concat (substring hd 0 (match-beginning 1))
25189 (substring hd (match-end 1))))
25190 (setq pri org-default-priority))
25191 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
25192 (- org-lowest-priority org-highest-priority))))))
25194 (princ (format "BEGIN:VTODO
25196 SUMMARY:%s%s%s
25197 CATEGORIES:%s
25198 SEQUENCE:1
25199 PRIORITY:%d
25200 STATUS:%s
25201 END:VTODO\n"
25203 (or summary hd)
25204 (if (and location (string-match "\\S-" location))
25205 (concat "\nLOCATION: " location) "")
25206 (if (and desc (string-match "\\S-" desc))
25207 (concat "\nDESCRIPTION: " desc) "")
25208 category pri status)))))))))
25210 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
25211 "Take out stuff and quote what needs to be quoted.
25212 When IS-BODY is non-nil, assume that this is the body of an item, clean up
25213 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
25214 characters."
25215 (if (not s)
25217 (when is-body
25218 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
25219 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
25220 (while (string-match re s) (setq s (replace-match "" t t s)))
25221 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
25222 (let ((start 0))
25223 (while (string-match "\\([,;\\]\\)" s start)
25224 (setq start (+ (match-beginning 0) 2)
25225 s (replace-match "\\\\\\1" nil nil s))))
25226 (when is-body
25227 (while (string-match "[ \t]*\n[ \t]*" s)
25228 (setq s (replace-match "\\n" t t s))))
25229 (setq s (org-trim s))
25230 (if is-body
25231 (if maxlength
25232 (if (and (numberp maxlength)
25233 (> (length s) maxlength))
25234 (setq s (substring s 0 maxlength)))))
25237 (defun org-get-entry ()
25238 "Clean-up description string."
25239 (save-excursion
25240 (org-back-to-heading t)
25241 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
25243 (defun org-start-icalendar-file (name)
25244 "Start an iCalendar file by inserting the header."
25245 (let ((user user-full-name)
25246 (name (or name "unknown"))
25247 (timezone (cadr (current-time-zone))))
25248 (princ
25249 (format "BEGIN:VCALENDAR
25250 VERSION:2.0
25251 X-WR-CALNAME:%s
25252 PRODID:-//%s//Emacs with Org-mode//EN
25253 X-WR-TIMEZONE:%s
25254 CALSCALE:GREGORIAN\n" name user timezone))))
25256 (defun org-finish-icalendar-file ()
25257 "Finish an iCalendar file by inserting the END statement."
25258 (princ "END:VCALENDAR\n"))
25260 (defun org-ical-ts-to-string (s keyword &optional inc)
25261 "Take a time string S and convert it to iCalendar format.
25262 KEYWORD is added in front, to make a complete line like DTSTART....
25263 When INC is non-nil, increase the hour by two (if time string contains
25264 a time), or the day by one (if it does not contain a time)."
25265 (let ((t1 (org-parse-time-string s 'nodefault))
25266 t2 fmt have-time time)
25267 (if (and (car t1) (nth 1 t1) (nth 2 t1))
25268 (setq t2 t1 have-time t)
25269 (setq t2 (org-parse-time-string s)))
25270 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
25271 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
25272 (when inc
25273 (if have-time
25274 (if org-agenda-default-appointment-duration
25275 (setq mi (+ org-agenda-default-appointment-duration mi))
25276 (setq h (+ 2 h)))
25277 (setq d (1+ d))))
25278 (setq time (encode-time s mi h d m y)))
25279 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
25280 (concat keyword (format-time-string fmt time))))
25282 ;;; XOXO export
25284 (defun org-export-as-xoxo-insert-into (buffer &rest output)
25285 (with-current-buffer buffer
25286 (apply 'insert output)))
25287 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
25289 (defun org-export-as-xoxo (&optional buffer)
25290 "Export the org buffer as XOXO.
25291 The XOXO buffer is named *xoxo-<source buffer name>*"
25292 (interactive (list (current-buffer)))
25293 ;; A quickie abstraction
25295 ;; Output everything as XOXO
25296 (with-current-buffer (get-buffer buffer)
25297 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
25298 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25299 (org-infile-export-plist)))
25300 (filename (concat (file-name-as-directory
25301 (org-export-directory :xoxo opt-plist))
25302 (file-name-sans-extension
25303 (file-name-nondirectory buffer-file-name))
25304 ".html"))
25305 (out (find-file-noselect filename))
25306 (last-level 1)
25307 (hanging-li nil))
25308 ;; Check the output buffer is empty.
25309 (with-current-buffer out (erase-buffer))
25310 ;; Kick off the output
25311 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
25312 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
25313 (let* ((hd (match-string-no-properties 1))
25314 (level (length hd))
25315 (text (concat
25316 (match-string-no-properties 2)
25317 (save-excursion
25318 (goto-char (match-end 0))
25319 (let ((str ""))
25320 (catch 'loop
25321 (while 't
25322 (forward-line)
25323 (if (looking-at "^[ \t]\\(.*\\)")
25324 (setq str (concat str (match-string-no-properties 1)))
25325 (throw 'loop str)))))))))
25327 ;; Handle level rendering
25328 (cond
25329 ((> level last-level)
25330 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
25332 ((< level last-level)
25333 (dotimes (- (- last-level level) 1)
25334 (if hanging-li
25335 (org-export-as-xoxo-insert-into out "</li>\n"))
25336 (org-export-as-xoxo-insert-into out "</ol>\n"))
25337 (when hanging-li
25338 (org-export-as-xoxo-insert-into out "</li>\n")
25339 (setq hanging-li nil)))
25341 ((equal level last-level)
25342 (if hanging-li
25343 (org-export-as-xoxo-insert-into out "</li>\n")))
25346 (setq last-level level)
25348 ;; And output the new li
25349 (setq hanging-li 't)
25350 (if (equal ?+ (elt text 0))
25351 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
25352 (org-export-as-xoxo-insert-into out "<li>" text))))
25354 ;; Finally finish off the ol
25355 (dotimes (- last-level 1)
25356 (if hanging-li
25357 (org-export-as-xoxo-insert-into out "</li>\n"))
25358 (org-export-as-xoxo-insert-into out "</ol>\n"))
25360 ;; Finish the buffer off and clean it up.
25361 (switch-to-buffer-other-window out)
25362 (indent-region (point-min) (point-max) nil)
25363 (save-buffer)
25364 (goto-char (point-min))
25368 ;;;; Key bindings
25370 ;; Make `C-c C-x' a prefix key
25371 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
25373 ;; TAB key with modifiers
25374 (org-defkey org-mode-map "\C-i" 'org-cycle)
25375 (org-defkey org-mode-map [(tab)] 'org-cycle)
25376 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
25377 (org-defkey org-mode-map [(meta tab)] 'org-complete)
25378 (org-defkey org-mode-map "\M-\t" 'org-complete)
25379 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
25380 ;; The following line is necessary under Suse GNU/Linux
25381 (unless (featurep 'xemacs)
25382 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
25383 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
25384 (define-key org-mode-map [backtab] 'org-shifttab)
25386 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
25387 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
25388 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
25390 ;; Cursor keys with modifiers
25391 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
25392 (org-defkey org-mode-map [(meta right)] 'org-metaright)
25393 (org-defkey org-mode-map [(meta up)] 'org-metaup)
25394 (org-defkey org-mode-map [(meta down)] 'org-metadown)
25396 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
25397 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
25398 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
25399 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
25401 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
25402 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
25403 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
25404 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
25406 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
25407 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
25409 ;;; Extra keys for tty access.
25410 ;; We only set them when really needed because otherwise the
25411 ;; menus don't show the simple keys
25413 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
25414 (not window-system))
25415 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
25416 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
25417 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
25418 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
25419 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
25420 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
25421 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
25422 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
25423 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
25424 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
25425 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
25426 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
25427 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
25428 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
25429 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
25430 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
25431 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
25432 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
25433 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
25434 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
25435 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
25436 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
25438 ;; All the other keys
25440 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
25441 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
25442 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
25443 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
25444 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
25445 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
25446 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
25447 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
25448 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
25449 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
25450 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
25451 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
25452 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
25453 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
25454 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
25455 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
25456 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
25457 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
25458 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
25459 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
25460 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
25461 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
25462 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
25463 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
25464 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
25465 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
25466 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
25467 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
25468 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
25469 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
25470 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
25471 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
25472 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
25473 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
25474 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
25475 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
25476 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
25477 (org-defkey org-mode-map "\C-c^" 'org-sort)
25478 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
25479 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
25480 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
25481 (org-defkey org-mode-map "\C-m" 'org-return)
25482 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
25483 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
25484 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
25485 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
25486 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
25487 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
25488 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
25489 (org-defkey org-mode-map "\C-c*" 'org-table-recalculate)
25490 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
25491 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
25492 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
25493 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
25494 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
25495 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
25496 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
25497 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
25499 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
25500 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
25501 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
25502 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
25504 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
25505 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
25506 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
25507 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
25508 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
25509 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
25510 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
25511 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
25512 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
25513 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
25514 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
25515 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
25517 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
25519 (when (featurep 'xemacs)
25520 (org-defkey org-mode-map 'button3 'popup-mode-menu))
25522 (defsubst org-table-p () (org-at-table-p))
25524 (defun org-self-insert-command (N)
25525 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
25526 If the cursor is in a table looking at whitespace, the whitespace is
25527 overwritten, and the table is not marked as requiring realignment."
25528 (interactive "p")
25529 (if (and (org-table-p)
25530 (progn
25531 ;; check if we blank the field, and if that triggers align
25532 (and org-table-auto-blank-field
25533 (member last-command
25534 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
25535 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
25536 ;; got extra space, this field does not determine column width
25537 (let (org-table-may-need-update) (org-table-blank-field))
25538 ;; no extra space, this field may determine column width
25539 (org-table-blank-field)))
25541 (eq N 1)
25542 (looking-at "[^|\n]* |"))
25543 (let (org-table-may-need-update)
25544 (goto-char (1- (match-end 0)))
25545 (delete-backward-char 1)
25546 (goto-char (match-beginning 0))
25547 (self-insert-command N))
25548 (setq org-table-may-need-update t)
25549 (self-insert-command N)
25550 (org-fix-tags-on-the-fly)))
25552 (defun org-fix-tags-on-the-fly ()
25553 (when (and (equal (char-after (point-at-bol)) ?*)
25554 (org-on-heading-p))
25555 (org-align-tags-here org-tags-column)))
25557 (defun org-delete-backward-char (N)
25558 "Like `delete-backward-char', insert whitespace at field end in tables.
25559 When deleting backwards, in tables this function will insert whitespace in
25560 front of the next \"|\" separator, to keep the table aligned. The table will
25561 still be marked for re-alignment if the field did fill the entire column,
25562 because, in this case the deletion might narrow the column."
25563 (interactive "p")
25564 (if (and (org-table-p)
25565 (eq N 1)
25566 (string-match "|" (buffer-substring (point-at-bol) (point)))
25567 (looking-at ".*?|"))
25568 (let ((pos (point))
25569 (noalign (looking-at "[^|\n\r]* |"))
25570 (c org-table-may-need-update))
25571 (backward-delete-char N)
25572 (skip-chars-forward "^|")
25573 (insert " ")
25574 (goto-char (1- pos))
25575 ;; noalign: if there were two spaces at the end, this field
25576 ;; does not determine the width of the column.
25577 (if noalign (setq org-table-may-need-update c)))
25578 (backward-delete-char N)
25579 (org-fix-tags-on-the-fly)))
25581 (defun org-delete-char (N)
25582 "Like `delete-char', but insert whitespace at field end in tables.
25583 When deleting characters, in tables this function will insert whitespace in
25584 front of the next \"|\" separator, to keep the table aligned. The table will
25585 still be marked for re-alignment if the field did fill the entire column,
25586 because, in this case the deletion might narrow the column."
25587 (interactive "p")
25588 (if (and (org-table-p)
25589 (not (bolp))
25590 (not (= (char-after) ?|))
25591 (eq N 1))
25592 (if (looking-at ".*?|")
25593 (let ((pos (point))
25594 (noalign (looking-at "[^|\n\r]* |"))
25595 (c org-table-may-need-update))
25596 (replace-match (concat
25597 (substring (match-string 0) 1 -1)
25598 " |"))
25599 (goto-char pos)
25600 ;; noalign: if there were two spaces at the end, this field
25601 ;; does not determine the width of the column.
25602 (if noalign (setq org-table-may-need-update c)))
25603 (delete-char N))
25604 (delete-char N)
25605 (org-fix-tags-on-the-fly)))
25607 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
25608 (put 'org-self-insert-command 'delete-selection t)
25609 (put 'orgtbl-self-insert-command 'delete-selection t)
25610 (put 'org-delete-char 'delete-selection 'supersede)
25611 (put 'org-delete-backward-char 'delete-selection 'supersede)
25613 ;; Make `flyspell-mode' delay after some commands
25614 (put 'org-self-insert-command 'flyspell-delayed t)
25615 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
25616 (put 'org-delete-char 'flyspell-delayed t)
25617 (put 'org-delete-backward-char 'flyspell-delayed t)
25619 ;; Make pabbrev-mode expand after org-mode commands
25620 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
25621 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
25623 ;; How to do this: Measure non-white length of current string
25624 ;; If equal to column width, we should realign.
25626 (defun org-remap (map &rest commands)
25627 "In MAP, remap the functions given in COMMANDS.
25628 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
25629 (let (new old)
25630 (while commands
25631 (setq old (pop commands) new (pop commands))
25632 (if (fboundp 'command-remapping)
25633 (org-defkey map (vector 'remap old) new)
25634 (substitute-key-definition old new map global-map)))))
25636 (when (eq org-enable-table-editor 'optimized)
25637 ;; If the user wants maximum table support, we need to hijack
25638 ;; some standard editing functions
25639 (org-remap org-mode-map
25640 'self-insert-command 'org-self-insert-command
25641 'delete-char 'org-delete-char
25642 'delete-backward-char 'org-delete-backward-char)
25643 (org-defkey org-mode-map "|" 'org-force-self-insert))
25645 (defun org-shiftcursor-error ()
25646 "Throw an error because Shift-Cursor command was applied in wrong context."
25647 (error "This command is active in special context like tables, headlines or timestamps"))
25649 (defun org-shifttab (&optional arg)
25650 "Global visibility cycling or move to previous table field.
25651 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
25652 on context.
25653 See the individual commands for more information."
25654 (interactive "P")
25655 (cond
25656 ((org-at-table-p) (call-interactively 'org-table-previous-field))
25657 (arg (message "Content view to level: ")
25658 (org-content (prefix-numeric-value arg))
25659 (setq org-cycle-global-status 'overview))
25660 (t (call-interactively 'org-global-cycle))))
25662 (defun org-shiftmetaleft ()
25663 "Promote subtree or delete table column.
25664 Calls `org-promote-subtree', `org-outdent-item',
25665 or `org-table-delete-column', depending on context.
25666 See the individual commands for more information."
25667 (interactive)
25668 (cond
25669 ((org-at-table-p) (call-interactively 'org-table-delete-column))
25670 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
25671 ((org-at-item-p) (call-interactively 'org-outdent-item))
25672 (t (org-shiftcursor-error))))
25674 (defun org-shiftmetaright ()
25675 "Demote subtree or insert table column.
25676 Calls `org-demote-subtree', `org-indent-item',
25677 or `org-table-insert-column', depending on context.
25678 See the individual commands for more information."
25679 (interactive)
25680 (cond
25681 ((org-at-table-p) (call-interactively 'org-table-insert-column))
25682 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
25683 ((org-at-item-p) (call-interactively 'org-indent-item))
25684 (t (org-shiftcursor-error))))
25686 (defun org-shiftmetaup (&optional arg)
25687 "Move subtree up or kill table row.
25688 Calls `org-move-subtree-up' or `org-table-kill-row' or
25689 `org-move-item-up' depending on context. See the individual commands
25690 for more information."
25691 (interactive "P")
25692 (cond
25693 ((org-at-table-p) (call-interactively 'org-table-kill-row))
25694 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25695 ((org-at-item-p) (call-interactively 'org-move-item-up))
25696 (t (org-shiftcursor-error))))
25697 (defun org-shiftmetadown (&optional arg)
25698 "Move subtree down or insert table row.
25699 Calls `org-move-subtree-down' or `org-table-insert-row' or
25700 `org-move-item-down', depending on context. See the individual
25701 commands for more information."
25702 (interactive "P")
25703 (cond
25704 ((org-at-table-p) (call-interactively 'org-table-insert-row))
25705 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25706 ((org-at-item-p) (call-interactively 'org-move-item-down))
25707 (t (org-shiftcursor-error))))
25709 (defun org-metaleft (&optional arg)
25710 "Promote heading or move table column to left.
25711 Calls `org-do-promote' or `org-table-move-column', depending on context.
25712 With no specific context, calls the Emacs default `backward-word'.
25713 See the individual commands for more information."
25714 (interactive "P")
25715 (cond
25716 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
25717 ((or (org-on-heading-p) (org-region-active-p))
25718 (call-interactively 'org-do-promote))
25719 ((org-at-item-p) (call-interactively 'org-outdent-item))
25720 (t (call-interactively 'backward-word))))
25722 (defun org-metaright (&optional arg)
25723 "Demote subtree or move table column to right.
25724 Calls `org-do-demote' or `org-table-move-column', depending on context.
25725 With no specific context, calls the Emacs default `forward-word'.
25726 See the individual commands for more information."
25727 (interactive "P")
25728 (cond
25729 ((org-at-table-p) (call-interactively 'org-table-move-column))
25730 ((or (org-on-heading-p) (org-region-active-p))
25731 (call-interactively 'org-do-demote))
25732 ((org-at-item-p) (call-interactively 'org-indent-item))
25733 (t (call-interactively 'forward-word))))
25735 (defun org-metaup (&optional arg)
25736 "Move subtree up or move table row up.
25737 Calls `org-move-subtree-up' or `org-table-move-row' or
25738 `org-move-item-up', depending on context. See the individual commands
25739 for more information."
25740 (interactive "P")
25741 (cond
25742 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
25743 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
25744 ((org-at-item-p) (call-interactively 'org-move-item-up))
25745 (t (transpose-lines 1) (beginning-of-line -1))))
25747 (defun org-metadown (&optional arg)
25748 "Move subtree down or move table row down.
25749 Calls `org-move-subtree-down' or `org-table-move-row' or
25750 `org-move-item-down', depending on context. See the individual
25751 commands for more information."
25752 (interactive "P")
25753 (cond
25754 ((org-at-table-p) (call-interactively 'org-table-move-row))
25755 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
25756 ((org-at-item-p) (call-interactively 'org-move-item-down))
25757 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
25759 (defun org-shiftup (&optional arg)
25760 "Increase item in timestamp or increase priority of current headline.
25761 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
25762 depending on context. See the individual commands for more information."
25763 (interactive "P")
25764 (cond
25765 ((org-at-timestamp-p t)
25766 (call-interactively (if org-edit-timestamp-down-means-later
25767 'org-timestamp-down 'org-timestamp-up)))
25768 ((org-on-heading-p) (call-interactively 'org-priority-up))
25769 ((org-at-item-p) (call-interactively 'org-previous-item))
25770 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
25772 (defun org-shiftdown (&optional arg)
25773 "Decrease item in timestamp or decrease priority of current headline.
25774 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
25775 depending on context. See the individual commands for more information."
25776 (interactive "P")
25777 (cond
25778 ((org-at-timestamp-p t)
25779 (call-interactively (if org-edit-timestamp-down-means-later
25780 'org-timestamp-up 'org-timestamp-down)))
25781 ((org-on-heading-p) (call-interactively 'org-priority-down))
25782 (t (call-interactively 'org-next-item))))
25784 (defun org-shiftright ()
25785 "Next TODO keyword or timestamp one day later, depending on context."
25786 (interactive)
25787 (cond
25788 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
25789 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
25790 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
25791 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
25792 (t (org-shiftcursor-error))))
25794 (defun org-shiftleft ()
25795 "Previous TODO keyword or timestamp one day earlier, depending on context."
25796 (interactive)
25797 (cond
25798 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
25799 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
25800 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
25801 ((org-at-property-p)
25802 (call-interactively 'org-property-previous-allowed-value))
25803 (t (org-shiftcursor-error))))
25805 (defun org-shiftcontrolright ()
25806 "Switch to next TODO set."
25807 (interactive)
25808 (cond
25809 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
25810 (t (org-shiftcursor-error))))
25812 (defun org-shiftcontrolleft ()
25813 "Switch to previous TODO set."
25814 (interactive)
25815 (cond
25816 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
25817 (t (org-shiftcursor-error))))
25819 (defun org-ctrl-c-ret ()
25820 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
25821 (interactive)
25822 (cond
25823 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
25824 (t (call-interactively 'org-insert-heading))))
25826 (defun org-copy-special ()
25827 "Copy region in table or copy current subtree.
25828 Calls `org-table-copy' or `org-copy-subtree', depending on context.
25829 See the individual commands for more information."
25830 (interactive)
25831 (call-interactively
25832 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
25834 (defun org-cut-special ()
25835 "Cut region in table or cut current subtree.
25836 Calls `org-table-copy' or `org-cut-subtree', depending on context.
25837 See the individual commands for more information."
25838 (interactive)
25839 (call-interactively
25840 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
25842 (defun org-paste-special (arg)
25843 "Paste rectangular region into table, or past subtree relative to level.
25844 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
25845 See the individual commands for more information."
25846 (interactive "P")
25847 (if (org-at-table-p)
25848 (org-table-paste-rectangle)
25849 (org-paste-subtree arg)))
25851 (defun org-ctrl-c-ctrl-c (&optional arg)
25852 "Set tags in headline, or update according to changed information at point.
25854 This command does many different things, depending on context:
25856 - If the cursor is in a headline, prompt for tags and insert them
25857 into the current line, aligned to `org-tags-column'. When called
25858 with prefix arg, realign all tags in the current buffer.
25860 - If the cursor is in one of the special #+KEYWORD lines, this
25861 triggers scanning the buffer for these lines and updating the
25862 information.
25864 - If the cursor is inside a table, realign the table. This command
25865 works even if the automatic table editor has been turned off.
25867 - If the cursor is on a #+TBLFM line, re-apply the formulas to
25868 the entire table.
25870 - If the cursor is a the beginning of a dynamic block, update it.
25872 - If the cursor is inside a table created by the table.el package,
25873 activate that table.
25875 - If the current buffer is a remember buffer, close note and file it.
25876 with a prefix argument, file it without further interaction to the default
25877 location.
25879 - If the cursor is on a <<<target>>>, update radio targets and corresponding
25880 links in this buffer.
25882 - If the cursor is on a numbered item in a plain list, renumber the
25883 ordered list.
25885 - If the cursor is on a checkbox, toggle it."
25886 (interactive "P")
25887 (let ((org-enable-table-editor t))
25888 (cond
25889 ((or org-clock-overlays
25890 org-occur-highlights
25891 org-latex-fragment-image-overlays)
25892 (org-remove-clock-overlays)
25893 (org-remove-occur-highlights)
25894 (org-remove-latex-fragment-image-overlays)
25895 (message "Temporary highlights/overlays removed from current buffer"))
25896 ((and (local-variable-p 'org-finish-function (current-buffer))
25897 (fboundp org-finish-function))
25898 (funcall org-finish-function))
25899 ((org-at-property-p)
25900 (call-interactively 'org-property-action))
25901 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
25902 ((org-on-heading-p) (call-interactively 'org-set-tags))
25903 ((org-at-table.el-p)
25904 (require 'table)
25905 (beginning-of-line 1)
25906 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
25907 (call-interactively 'table-recognize-table))
25908 ((org-at-table-p)
25909 (org-table-maybe-eval-formula)
25910 (if arg
25911 (call-interactively 'org-table-recalculate)
25912 (org-table-maybe-recalculate-line))
25913 (call-interactively 'org-table-align))
25914 ((org-at-item-checkbox-p)
25915 (call-interactively 'org-toggle-checkbox))
25916 ((org-at-item-p)
25917 (call-interactively 'org-maybe-renumber-ordered-list))
25918 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
25919 ;; Dynamic block
25920 (beginning-of-line 1)
25921 (org-update-dblock))
25922 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
25923 (cond
25924 ((equal (match-string 1) "TBLFM")
25925 ;; Recalculate the table before this line
25926 (save-excursion
25927 (beginning-of-line 1)
25928 (skip-chars-backward " \r\n\t")
25929 (if (org-at-table-p)
25930 (org-call-with-arg 'org-table-recalculate t))))
25932 (call-interactively 'org-mode-restart))))
25933 (t (error "C-c C-c can do nothing useful at this location.")))))
25935 (defun org-mode-restart ()
25936 "Restart Org-mode, to scan again for special lines.
25937 Also updates the keyword regular expressions."
25938 (interactive)
25939 (let ((org-inhibit-startup t)) (org-mode))
25940 (message "Org-mode restarted to refresh keyword and special line setup"))
25942 (defun org-kill-note-or-show-branches ()
25943 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
25944 (interactive)
25945 (if (not org-finish-function)
25946 (call-interactively 'show-branches)
25947 (let ((org-note-abort t))
25948 (funcall org-finish-function))))
25950 (defun org-return ()
25951 "Goto next table row or insert a newline.
25952 Calls `org-table-next-row' or `newline', depending on context.
25953 See the individual commands for more information."
25954 (interactive)
25955 (cond
25956 ((bobp) (newline))
25957 ((org-at-table-p)
25958 (org-table-justify-field-maybe)
25959 (call-interactively 'org-table-next-row))
25960 (t (newline))))
25963 (defun org-ctrl-c-minus ()
25964 "Insert separator line in table or modify bullet type in list.
25965 Calls `org-table-insert-hline' or `org-cycle-list-bullet',
25966 depending on context."
25967 (interactive)
25968 (cond
25969 ((org-at-table-p)
25970 (call-interactively 'org-table-insert-hline))
25971 ((org-on-heading-p)
25972 ;; Convert to item
25973 (save-excursion
25974 (beginning-of-line 1)
25975 (if (looking-at "\\*+ ")
25976 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
25977 ((org-in-item-p)
25978 (call-interactively 'org-cycle-list-bullet))
25979 (t (error "`C-c -' does have no function here."))))
25981 (defun org-meta-return (&optional arg)
25982 "Insert a new heading or wrap a region in a table.
25983 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
25984 See the individual commands for more information."
25985 (interactive "P")
25986 (cond
25987 ((org-at-table-p)
25988 (call-interactively 'org-table-wrap-region))
25989 (t (call-interactively 'org-insert-heading))))
25991 ;;; Menu entries
25993 ;; Define the Org-mode menus
25994 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
25995 '("Tbl"
25996 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
25997 ["Next Field" org-cycle (org-at-table-p)]
25998 ["Previous Field" org-shifttab (org-at-table-p)]
25999 ["Next Row" org-return (org-at-table-p)]
26000 "--"
26001 ["Blank Field" org-table-blank-field (org-at-table-p)]
26002 ["Edit Field" org-table-edit-field (org-at-table-p)]
26003 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
26004 "--"
26005 ("Column"
26006 ["Move Column Left" org-metaleft (org-at-table-p)]
26007 ["Move Column Right" org-metaright (org-at-table-p)]
26008 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
26009 ["Insert Column" org-shiftmetaright (org-at-table-p)])
26010 ("Row"
26011 ["Move Row Up" org-metaup (org-at-table-p)]
26012 ["Move Row Down" org-metadown (org-at-table-p)]
26013 ["Delete Row" org-shiftmetaup (org-at-table-p)]
26014 ["Insert Row" org-shiftmetadown (org-at-table-p)]
26015 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
26016 "--"
26017 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
26018 ("Rectangle"
26019 ["Copy Rectangle" org-copy-special (org-at-table-p)]
26020 ["Cut Rectangle" org-cut-special (org-at-table-p)]
26021 ["Paste Rectangle" org-paste-special (org-at-table-p)]
26022 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
26023 "--"
26024 ("Calculate"
26025 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
26026 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
26027 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
26028 "--"
26029 ["Recalculate line" org-table-recalculate (org-at-table-p)]
26030 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
26031 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
26032 "--"
26033 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
26034 "--"
26035 ["Sum Column/Rectangle" org-table-sum
26036 (or (org-at-table-p) (org-region-active-p))]
26037 ["Which Column?" org-table-current-column (org-at-table-p)])
26038 ["Debug Formulas"
26039 org-table-toggle-formula-debugger
26040 :style toggle :selected org-table-formula-debug]
26041 ["Show Col/Row Numbers"
26042 org-table-toggle-coordinate-overlays
26043 :style toggle :selected org-table-overlay-coordinates]
26044 "--"
26045 ["Create" org-table-create (and (not (org-at-table-p))
26046 org-enable-table-editor)]
26047 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
26048 ["Import from File" org-table-import (not (org-at-table-p))]
26049 ["Export to File" org-table-export (org-at-table-p)]
26050 "--"
26051 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
26053 (easy-menu-define org-org-menu org-mode-map "Org menu"
26054 '("Org"
26055 ("Show/Hide"
26056 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
26057 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
26058 ["Sparse Tree" org-occur t]
26059 ["Reveal Context" org-reveal t]
26060 ["Show All" show-all t]
26061 "--"
26062 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
26063 "--"
26064 ["New Heading" org-insert-heading t]
26065 ("Navigate Headings"
26066 ["Up" outline-up-heading t]
26067 ["Next" outline-next-visible-heading t]
26068 ["Previous" outline-previous-visible-heading t]
26069 ["Next Same Level" outline-forward-same-level t]
26070 ["Previous Same Level" outline-backward-same-level t]
26071 "--"
26072 ["Jump" org-goto t])
26073 ("Edit Structure"
26074 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
26075 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
26076 "--"
26077 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
26078 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
26079 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
26080 "--"
26081 ["Promote Heading" org-metaleft (not (org-at-table-p))]
26082 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
26083 ["Demote Heading" org-metaright (not (org-at-table-p))]
26084 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
26085 "--"
26086 ["Sort Region/Children" org-sort (not (org-at-table-p))]
26087 "--"
26088 ["Convert to odd levels" org-convert-to-odd-levels t]
26089 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
26090 ("Editing"
26091 ["Emphasis..." org-emphasize t])
26092 ("Archive"
26093 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
26094 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
26095 ; :active t :keys "C-u C-c C-x C-a"]
26096 ["Sparse trees open ARCHIVE trees"
26097 (setq org-sparse-tree-open-archived-trees
26098 (not org-sparse-tree-open-archived-trees))
26099 :style toggle :selected org-sparse-tree-open-archived-trees]
26100 ["Cycling opens ARCHIVE trees"
26101 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
26102 :style toggle :selected org-cycle-open-archived-trees]
26103 ["Agenda includes ARCHIVE trees"
26104 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
26105 :style toggle :selected (not org-agenda-skip-archived-trees)]
26106 "--"
26107 ["Move Subtree to Archive" org-advertized-archive-subtree t]
26108 ; ["Check and Move Children" (org-archive-subtree '(4))
26109 ; :active t :keys "C-u C-c C-x C-s"]
26111 "--"
26112 ("TODO Lists"
26113 ["TODO/DONE/-" org-todo t]
26114 ("Select keyword"
26115 ["Next keyword" org-shiftright (org-on-heading-p)]
26116 ["Previous keyword" org-shiftleft (org-on-heading-p)]
26117 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
26118 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
26119 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
26120 ["Show TODO Tree" org-show-todo-tree t]
26121 ["Global TODO list" org-todo-list t]
26122 "--"
26123 ["Set Priority" org-priority t]
26124 ["Priority Up" org-shiftup t]
26125 ["Priority Down" org-shiftdown t])
26126 ("TAGS and Properties"
26127 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
26128 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
26129 "--"
26130 ["Set property" 'org-set-property t]
26131 ["Column view of properties" org-columns t]
26132 ["Insert Column View DBlock" org-insert-columns-dblock t])
26133 ("Dates and Scheduling"
26134 ["Timestamp" org-time-stamp t]
26135 ["Timestamp (inactive)" org-time-stamp-inactive t]
26136 ("Change Date"
26137 ["1 Day Later" org-shiftright t]
26138 ["1 Day Earlier" org-shiftleft t]
26139 ["1 ... Later" org-shiftup t]
26140 ["1 ... Earlier" org-shiftdown t])
26141 ["Compute Time Range" org-evaluate-time-range t]
26142 ["Schedule Item" org-schedule t]
26143 ["Deadline" org-deadline t]
26144 "--"
26145 ["Custom time format" org-toggle-time-stamp-overlays
26146 :style radio :selected org-display-custom-times]
26147 "--"
26148 ["Goto Calendar" org-goto-calendar t]
26149 ["Date from Calendar" org-date-from-calendar t])
26150 ("Logging work"
26151 ["Clock in" org-clock-in t]
26152 ["Clock out" org-clock-out t]
26153 ["Clock cancel" org-clock-cancel t]
26154 ["Goto running clock" org-clock-goto t]
26155 ["Display times" org-clock-display t]
26156 ["Create clock table" org-clock-report t]
26157 "--"
26158 ["Record DONE time"
26159 (progn (setq org-log-done (not org-log-done))
26160 (message "Switching to %s will %s record a timestamp"
26161 (car org-done-keywords)
26162 (if org-log-done "automatically" "not")))
26163 :style toggle :selected org-log-done])
26164 "--"
26165 ["Agenda Command..." org-agenda t]
26166 ("File List for Agenda")
26167 ("Special views current file"
26168 ["TODO Tree" org-show-todo-tree t]
26169 ["Check Deadlines" org-check-deadlines t]
26170 ["Timeline" org-timeline t]
26171 ["Tags Tree" org-tags-sparse-tree t])
26172 "--"
26173 ("Hyperlinks"
26174 ["Store Link (Global)" org-store-link t]
26175 ["Insert Link" org-insert-link t]
26176 ["Follow Link" org-open-at-point t]
26177 "--"
26178 ["Next link" org-next-link t]
26179 ["Previous link" org-previous-link t]
26180 "--"
26181 ["Descriptive Links"
26182 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
26183 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
26184 ["Literal Links"
26185 (progn
26186 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
26187 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
26188 "--"
26189 ["Export/Publish..." org-export t]
26190 ("LaTeX"
26191 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
26192 :selected org-cdlatex-mode]
26193 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
26194 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
26195 ["Modify math symbol" org-cdlatex-math-modify
26196 (org-inside-LaTeX-fragment-p)]
26197 ["Export LaTeX fragments as images"
26198 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
26199 :style toggle :selected org-export-with-LaTeX-fragments])
26200 "--"
26201 ("Documentation"
26202 ["Show Version" org-version t]
26203 ["Info Documentation" org-info t])
26204 ("Customize"
26205 ["Browse Org Group" org-customize t]
26206 "--"
26207 ["Expand This Menu" org-create-customize-menu
26208 (fboundp 'customize-menu-create)])
26209 "--"
26210 ["Refresh setup" org-mode-restart t]
26213 (defun org-info (&optional node)
26214 "Read documentation for Org-mode in the info system.
26215 With optional NODE, go directly to that node."
26216 (interactive)
26217 (require 'info)
26218 (Info-goto-node (format "(org)%s" (or node ""))))
26220 (defun org-install-agenda-files-menu ()
26221 (let ((bl (buffer-list)))
26222 (save-excursion
26223 (while bl
26224 (set-buffer (pop bl))
26225 (if (org-mode-p) (setq bl nil)))
26226 (when (org-mode-p)
26227 (easy-menu-change
26228 '("Org") "File List for Agenda"
26229 (append
26230 (list
26231 ["Edit File List" (org-edit-agenda-file-list) t]
26232 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
26233 ["Remove Current File from List" org-remove-file t]
26234 ["Cycle through agenda files" org-cycle-agenda-files t]
26235 ["Occur in all agenda files" org-occur-in-agenda-files t]
26236 "--")
26237 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
26239 ;;;; Documentation
26241 (defun org-customize ()
26242 "Call the customize function with org as argument."
26243 (interactive)
26244 (customize-browse 'org))
26246 (defun org-create-customize-menu ()
26247 "Create a full customization menu for Org-mode, insert it into the menu."
26248 (interactive)
26249 (if (fboundp 'customize-menu-create)
26250 (progn
26251 (easy-menu-change
26252 '("Org") "Customize"
26253 `(["Browse Org group" org-customize t]
26254 "--"
26255 ,(customize-menu-create 'org)
26256 ["Set" Custom-set t]
26257 ["Save" Custom-save t]
26258 ["Reset to Current" Custom-reset-current t]
26259 ["Reset to Saved" Custom-reset-saved t]
26260 ["Reset to Standard Settings" Custom-reset-standard t]))
26261 (message "\"Org\"-menu now contains full customization menu"))
26262 (error "Cannot expand menu (outdated version of cus-edit.el)")))
26264 ;;;; Miscellaneous stuff
26267 ;;; Generally useful functions
26269 (defun org-context ()
26270 "Return a list of contexts of the current cursor position.
26271 If several contexts apply, all are returned.
26272 Each context entry is a list with a symbol naming the context, and
26273 two positions indicating start and end of the context. Possible
26274 contexts are:
26276 :headline anywhere in a headline
26277 :headline-stars on the leading stars in a headline
26278 :todo-keyword on a TODO keyword (including DONE) in a headline
26279 :tags on the TAGS in a headline
26280 :priority on the priority cookie in a headline
26281 :item on the first line of a plain list item
26282 :item-bullet on the bullet/number of a plain list item
26283 :checkbox on the checkbox in a plain list item
26284 :table in an org-mode table
26285 :table-special on a special filed in a table
26286 :table-table in a table.el table
26287 :link on a hyperlink
26288 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
26289 :target on a <<target>>
26290 :radio-target on a <<<radio-target>>>
26291 :latex-fragment on a LaTeX fragment
26292 :latex-preview on a LaTeX fragment with overlayed preview image
26294 This function expects the position to be visible because it uses font-lock
26295 faces as a help to recognize the following contexts: :table-special, :link,
26296 and :keyword."
26297 (let* ((f (get-text-property (point) 'face))
26298 (faces (if (listp f) f (list f)))
26299 (p (point)) clist o)
26300 ;; First the large context
26301 (cond
26302 ((org-on-heading-p t)
26303 (push (list :headline (point-at-bol) (point-at-eol)) clist)
26304 (when (progn
26305 (beginning-of-line 1)
26306 (looking-at org-todo-line-tags-regexp))
26307 (push (org-point-in-group p 1 :headline-stars) clist)
26308 (push (org-point-in-group p 2 :todo-keyword) clist)
26309 (push (org-point-in-group p 4 :tags) clist))
26310 (goto-char p)
26311 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
26312 (if (looking-at "\\[#[A-Z0-9]\\]")
26313 (push (org-point-in-group p 0 :priority) clist)))
26315 ((org-at-item-p)
26316 (push (org-point-in-group p 2 :item-bullet) clist)
26317 (push (list :item (point-at-bol)
26318 (save-excursion (org-end-of-item) (point)))
26319 clist)
26320 (and (org-at-item-checkbox-p)
26321 (push (org-point-in-group p 0 :checkbox) clist)))
26323 ((org-at-table-p)
26324 (push (list :table (org-table-begin) (org-table-end)) clist)
26325 (if (memq 'org-formula faces)
26326 (push (list :table-special
26327 (previous-single-property-change p 'face)
26328 (next-single-property-change p 'face)) clist)))
26329 ((org-at-table-p 'any)
26330 (push (list :table-table) clist)))
26331 (goto-char p)
26333 ;; Now the small context
26334 (cond
26335 ((org-at-timestamp-p)
26336 (push (org-point-in-group p 0 :timestamp) clist))
26337 ((memq 'org-link faces)
26338 (push (list :link
26339 (previous-single-property-change p 'face)
26340 (next-single-property-change p 'face)) clist))
26341 ((memq 'org-special-keyword faces)
26342 (push (list :keyword
26343 (previous-single-property-change p 'face)
26344 (next-single-property-change p 'face)) clist))
26345 ((org-on-target-p)
26346 (push (org-point-in-group p 0 :target) clist)
26347 (goto-char (1- (match-beginning 0)))
26348 (if (looking-at org-radio-target-regexp)
26349 (push (org-point-in-group p 0 :radio-target) clist))
26350 (goto-char p))
26351 ((setq o (car (delq nil
26352 (mapcar
26353 (lambda (x)
26354 (if (memq x org-latex-fragment-image-overlays) x))
26355 (org-overlays-at (point))))))
26356 (push (list :latex-fragment
26357 (org-overlay-start o) (org-overlay-end o)) clist)
26358 (push (list :latex-preview
26359 (org-overlay-start o) (org-overlay-end o)) clist))
26360 ((org-inside-LaTeX-fragment-p)
26361 ;; FIXME: positions wrong.
26362 (push (list :latex-fragment (point) (point)) clist)))
26364 (setq clist (nreverse (delq nil clist)))
26365 clist))
26367 ;; FIXME: Compare with at-regexp-p Do we need both?
26368 (defun org-in-regexp (re &optional nlines visually)
26369 "Check if point is inside a match of regexp.
26370 Normally only the current line is checked, but you can include NLINES extra
26371 lines both before and after point into the search.
26372 If VISUALLY is set, require that the cursor is not after the match but
26373 really on, so that the block visually is on the match."
26374 (catch 'exit
26375 (let ((pos (point))
26376 (eol (point-at-eol (+ 1 (or nlines 0))))
26377 (inc (if visually 1 0)))
26378 (save-excursion
26379 (beginning-of-line (- 1 (or nlines 0)))
26380 (while (re-search-forward re eol t)
26381 (if (and (<= (match-beginning 0) pos)
26382 (>= (+ inc (match-end 0)) pos))
26383 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
26385 (defun org-at-regexp-p (regexp)
26386 "Is point inside a match of REGEXP in the current line?"
26387 (catch 'exit
26388 (save-excursion
26389 (let ((pos (point)) (end (point-at-eol)))
26390 (beginning-of-line 1)
26391 (while (re-search-forward regexp end t)
26392 (if (and (<= (match-beginning 0) pos)
26393 (>= (match-end 0) pos))
26394 (throw 'exit t)))
26395 nil))))
26397 (defun org-occur-in-agenda-files (regexp &optional nlines)
26398 "Call `multi-occur' with buffers for all agenda files."
26399 (interactive "sOrg-files matching: \np")
26400 (let* ((files (org-agenda-files))
26401 (tnames (mapcar 'file-truename files))
26402 (extra org-agenda-multi-occur-extra-files)
26404 (while (setq f (pop extra))
26405 (unless (member (file-truename f) tnames)
26406 (add-to-list 'files f 'append)
26407 (add-to-list 'tnames (file-truename f) 'append)))
26408 (multi-occur
26409 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
26410 regexp)))
26412 (defun org-uniquify (list)
26413 "Remove duplicate elements from LIST."
26414 (let (res)
26415 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
26416 res))
26418 (defun org-delete-all (elts list)
26419 "Remove all elements in ELTS from LIST."
26420 (while elts
26421 (setq list (delete (pop elts) list)))
26422 list)
26424 (defun org-point-in-group (point group &optional context)
26425 "Check if POINT is in match-group GROUP.
26426 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
26427 match. If the match group does ot exist or point is not inside it,
26428 return nil."
26429 (and (match-beginning group)
26430 (>= point (match-beginning group))
26431 (<= point (match-end group))
26432 (if context
26433 (list context (match-beginning group) (match-end group))
26434 t)))
26436 (defun org-switch-to-buffer-other-window (&rest args)
26437 "Switch to buffer in a second window on the current frame.
26438 In particular, do not allow pop-up frames."
26439 (let (pop-up-frames special-display-buffer-names special-display-regexps
26440 special-display-function)
26441 (apply 'switch-to-buffer-other-window args)))
26443 (defun org-combine-plists (&rest plists)
26444 "Create a single property list from all plists in PLISTS.
26445 The process starts by copying the first list, and then setting properties
26446 from the other lists. Settings in the last list are the most significant
26447 ones and overrule settings in the other lists."
26448 (let ((rtn (copy-sequence (pop plists)))
26449 p v ls)
26450 (while plists
26451 (setq ls (pop plists))
26452 (while ls
26453 (setq p (pop ls) v (pop ls))
26454 (setq rtn (plist-put rtn p v))))
26455 rtn))
26457 (defun org-move-line-down (arg)
26458 "Move the current line down. With prefix argument, move it past ARG lines."
26459 (interactive "p")
26460 (let ((col (current-column))
26461 beg end pos)
26462 (beginning-of-line 1) (setq beg (point))
26463 (beginning-of-line 2) (setq end (point))
26464 (beginning-of-line (+ 1 arg))
26465 (setq pos (move-marker (make-marker) (point)))
26466 (insert (delete-and-extract-region beg end))
26467 (goto-char pos)
26468 (move-to-column col)))
26470 (defun org-move-line-up (arg)
26471 "Move the current line up. With prefix argument, move it past ARG lines."
26472 (interactive "p")
26473 (let ((col (current-column))
26474 beg end pos)
26475 (beginning-of-line 1) (setq beg (point))
26476 (beginning-of-line 2) (setq end (point))
26477 (beginning-of-line (- arg))
26478 (setq pos (move-marker (make-marker) (point)))
26479 (insert (delete-and-extract-region beg end))
26480 (goto-char pos)
26481 (move-to-column col)))
26483 (defun org-replace-escapes (string table)
26484 "Replace %-escapes in STRING with values in TABLE.
26485 TABLE is an association list with keys like \"%a\" and string values.
26486 The sequences in STRING may contain normal field width and padding information,
26487 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
26488 so values can contain further %-escapes if they are define later in TABLE."
26489 (let ((case-fold-search nil)
26490 e re rpl)
26491 (while (setq e (pop table))
26492 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
26493 (while (string-match re string)
26494 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
26495 (cdr e)))
26496 (setq string (replace-match rpl t t string))))
26497 string))
26500 (defun org-sublist (list start end)
26501 "Return a section of LIST, from START to END.
26502 Counting starts at 1."
26503 (let (rtn (c start))
26504 (setq list (nthcdr (1- start) list))
26505 (while (and list (<= c end))
26506 (push (pop list) rtn)
26507 (setq c (1+ c)))
26508 (nreverse rtn)))
26510 (defun org-find-base-buffer-visiting (file)
26511 "Like `find-buffer-visiting' but alway return the base buffer and
26512 not an indirect buffer"
26513 (let ((buf (find-buffer-visiting file)))
26514 (if buf
26515 (or (buffer-base-buffer buf) buf)
26516 nil)))
26518 (defun org-image-file-name-regexp ()
26519 "Return regexp matching the file names of images."
26520 (if (fboundp 'image-file-name-regexp)
26521 (image-file-name-regexp)
26522 (let ((image-file-name-extensions
26523 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
26524 "xbm" "xpm" "pbm" "pgm" "ppm")))
26525 (concat "\\."
26526 (regexp-opt (nconc (mapcar 'upcase
26527 image-file-name-extensions)
26528 image-file-name-extensions)
26530 "\\'"))))
26532 (defun org-file-image-p (file)
26533 "Return non-nil if FILE is an image."
26534 (save-match-data
26535 (string-match (org-image-file-name-regexp) file)))
26537 ;;; Paragraph filling stuff.
26538 ;; We want this to be just right, so use the full arsenal.
26540 (defun org-indent-line-function ()
26541 "Indent line like previous, but further if previous was headline or item."
26542 (interactive)
26543 (let* ((pos (point))
26544 (itemp (org-at-item-p))
26545 column bpos bcol tpos tcol bullet btype bullet-type)
26546 ;; Find the previous relevant line
26547 (beginning-of-line 1)
26548 (cond
26549 ((looking-at "#") (setq column 0))
26550 ((looking-at "\\*+ ") (setq column 0))
26552 (beginning-of-line 0)
26553 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
26554 (beginning-of-line 0))
26555 (cond
26556 ((looking-at "\\*+[ \t]+")
26557 (goto-char (match-end 0))
26558 (setq column (current-column)))
26559 ((org-in-item-p)
26560 (org-beginning-of-item)
26561 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26562 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
26563 (setq bpos (match-beginning 1) tpos (match-end 0)
26564 bcol (progn (goto-char bpos) (current-column))
26565 tcol (progn (goto-char tpos) (current-column))
26566 bullet (match-string 1)
26567 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
26568 (if (not itemp)
26569 (setq column tcol)
26570 (goto-char pos)
26571 (beginning-of-line 1)
26572 (if (looking-at "\\S-")
26573 (progn
26574 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
26575 (setq bullet (match-string 1)
26576 btype (if (string-match "[0-9]" bullet) "n" bullet))
26577 (setq column (if (equal btype bullet-type) bcol tcol)))
26578 (setq column (org-get-indentation)))))
26579 (t (setq column (org-get-indentation))))))
26580 (goto-char pos)
26581 (if (<= (current-column) (current-indentation))
26582 (indent-line-to column)
26583 (save-excursion (indent-line-to column)))
26584 (setq column (current-column))
26585 (beginning-of-line 1)
26586 (if (looking-at
26587 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
26588 (replace-match (concat "\\1" (format org-property-format
26589 (match-string 2) (match-string 3)))
26590 t nil))
26591 (move-to-column column)))
26593 (defun org-set-autofill-regexps ()
26594 (interactive)
26595 ;; In the paragraph separator we include headlines, because filling
26596 ;; text in a line directly attached to a headline would otherwise
26597 ;; fill the headline as well.
26598 (org-set-local 'comment-start-skip "^#+[ \t]*")
26599 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
26600 ;; The paragraph starter includes hand-formatted lists.
26601 (org-set-local 'paragraph-start
26602 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
26603 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
26604 ;; But only if the user has not turned off tables or fixed-width regions
26605 (org-set-local
26606 'auto-fill-inhibit-regexp
26607 (concat "\\*+ \\|#\\+"
26608 "\\|[ \t]*" org-keyword-time-regexp
26609 (if (or org-enable-table-editor org-enable-fixed-width-editor)
26610 (concat
26611 "\\|[ \t]*["
26612 (if org-enable-table-editor "|" "")
26613 (if org-enable-fixed-width-editor ":" "")
26614 "]"))))
26615 ;; We use our own fill-paragraph function, to make sure that tables
26616 ;; and fixed-width regions are not wrapped. That function will pass
26617 ;; through to `fill-paragraph' when appropriate.
26618 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
26619 ; Adaptive filling: To get full control, first make sure that
26620 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
26621 (org-set-local 'adaptive-fill-regexp "\000")
26622 (org-set-local 'adaptive-fill-function
26623 'org-adaptive-fill-function))
26625 (defun org-fill-paragraph (&optional justify)
26626 "Re-align a table, pass through to fill-paragraph if no table."
26627 (let ((table-p (org-at-table-p))
26628 (table.el-p (org-at-table.el-p)))
26629 (cond ((and (equal (char-after (point-at-bol)) ?*)
26630 (save-excursion (goto-char (point-at-bol))
26631 (looking-at outline-regexp)))
26632 t) ; skip headlines
26633 (table.el-p t) ; skip table.el tables
26634 (table-p (org-table-align) t) ; align org-mode tables
26635 (t nil)))) ; call paragraph-fill
26637 ;; For reference, this is the default value of adaptive-fill-regexp
26638 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
26640 (defun org-adaptive-fill-function ()
26641 "Return a fill prefix for org-mode files.
26642 In particular, this makes sure hanging paragraphs for hand-formatted lists
26643 work correctly."
26644 (cond ((looking-at "#[ \t]+")
26645 (match-string 0))
26646 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
26647 (save-excursion
26648 (goto-char (match-end 0))
26649 (make-string (current-column) ?\ )))
26650 (t nil)))
26652 ;;;; Functions extending outline functionality
26654 (defun org-beginning-of-line (&optional arg)
26655 "Go to the beginning of the current line. If that is invisible, continue
26656 to a visible line beginning. This makes the function of C-a more intuitive.
26657 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26658 first attempt, and only move to after the tags when the cursor is already
26659 beyond the end of the headline."
26660 (interactive "P")
26661 (let ((pos (point)))
26662 (beginning-of-line 1)
26663 (if (bobp)
26665 (backward-char 1)
26666 (if (org-invisible-p)
26667 (while (and (not (bobp)) (org-invisible-p))
26668 (backward-char 1)
26669 (beginning-of-line 1))
26670 (forward-char 1)))
26671 (when org-special-ctrl-a/e
26672 (cond
26673 ((and (looking-at org-todo-line-regexp)
26674 (= (char-after (match-end 1)) ?\ ))
26675 (goto-char
26676 (if (eq org-special-ctrl-a/e t)
26677 (cond ((> pos (match-beginning 3)) (match-beginning 3))
26678 ((= pos (point)) (match-beginning 3))
26679 (t (point)))
26680 (cond ((> pos (point)) (point))
26681 ((not (eq last-command this-command)) (point))
26682 (t (match-beginning 3))))))
26683 ((org-at-item-p)
26684 (goto-char
26685 (if (eq org-special-ctrl-a/e t)
26686 (cond ((> pos (match-end 4)) (match-end 4))
26687 ((= pos (point)) (match-end 4))
26688 (t (point)))
26689 (cond ((> pos (point)) (point))
26690 ((not (eq last-command this-command)) (point))
26691 (t (match-end 4))))))))))
26693 (defun org-end-of-line (&optional arg)
26694 "Go to the end of the line.
26695 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
26696 first attempt, and only move to after the tags when the cursor is already
26697 beyond the end of the headline."
26698 (interactive "P")
26699 (if (or (not org-special-ctrl-a/e)
26700 (not (org-on-heading-p)))
26701 (end-of-line arg)
26702 (let ((pos (point)))
26703 (beginning-of-line 1)
26704 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
26705 (if (eq org-special-ctrl-a/e t)
26706 (if (or (< pos (match-beginning 1))
26707 (= pos (match-end 0)))
26708 (goto-char (match-beginning 1))
26709 (goto-char (match-end 0)))
26710 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
26711 (goto-char (match-end 0))
26712 (goto-char (match-beginning 1))))
26713 (end-of-line arg)))))
26715 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
26716 (define-key org-mode-map "\C-e" 'org-end-of-line)
26718 (defun org-invisible-p ()
26719 "Check if point is at a character currently not visible."
26720 ;; Early versions of noutline don't have `outline-invisible-p'.
26721 (if (fboundp 'outline-invisible-p)
26722 (outline-invisible-p)
26723 (get-char-property (point) 'invisible)))
26725 (defun org-invisible-p2 ()
26726 "Check if point is at a character currently not visible."
26727 (save-excursion
26728 (if (and (eolp) (not (bobp))) (backward-char 1))
26729 ;; Early versions of noutline don't have `outline-invisible-p'.
26730 (if (fboundp 'outline-invisible-p)
26731 (outline-invisible-p)
26732 (get-char-property (point) 'invisible))))
26734 (defalias 'org-back-to-heading 'outline-back-to-heading)
26735 (defalias 'org-on-heading-p 'outline-on-heading-p)
26736 (defalias 'org-at-heading-p 'outline-on-heading-p)
26737 (defun org-at-heading-or-item-p ()
26738 (or (org-on-heading-p) (org-at-item-p)))
26740 (defun org-on-target-p ()
26741 (or (org-in-regexp org-radio-target-regexp)
26742 (org-in-regexp org-target-regexp)))
26744 (defun org-up-heading-all (arg)
26745 "Move to the heading line of which the present line is a subheading.
26746 This function considers both visible and invisible heading lines.
26747 With argument, move up ARG levels."
26748 (if (fboundp 'outline-up-heading-all)
26749 (outline-up-heading-all arg) ; emacs 21 version of outline.el
26750 (outline-up-heading arg t))) ; emacs 22 version of outline.el
26752 (defun org-up-heading-safe ()
26753 "Move to the heading line of which the present line is a subheading.
26754 This version will not throw an error. It will return the level of the
26755 headline found, or nil if no higher level is found."
26756 (let ((pos (point)) start-level level
26757 (re (concat "^" outline-regexp)))
26758 (catch 'exit
26759 (outline-back-to-heading t)
26760 (setq start-level (funcall outline-level))
26761 (if (equal start-level 1) (throw 'exit nil))
26762 (while (re-search-backward re nil t)
26763 (setq level (funcall outline-level))
26764 (if (< level start-level) (throw 'exit level)))
26765 nil)))
26767 (defun org-goto-sibling (&optional previous)
26768 "Goto the next sibling, even if it is invisible.
26769 When PREVIOUS is set, go to the previous sibling instead. Returns t
26770 when a sibling was found. When none is found, return nil and don't
26771 move point."
26772 (let ((fun (if previous 're-search-backward 're-search-forward))
26773 (pos (point))
26774 (re (concat "^" outline-regexp))
26775 level l)
26776 (when (condition-case nil (org-back-to-heading t) (error nil))
26777 (setq level (funcall outline-level))
26778 (catch 'exit
26779 (or previous (forward-char 1))
26780 (while (funcall fun re nil t)
26781 (setq l (funcall outline-level))
26782 (when (< l level) (goto-char pos) (throw 'exit nil))
26783 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
26784 (goto-char pos)
26785 nil))))
26787 (defun org-show-siblings ()
26788 "Show all siblings of the current headline."
26789 (save-excursion
26790 (while (org-goto-sibling) (org-flag-heading nil)))
26791 (save-excursion
26792 (while (org-goto-sibling 'previous)
26793 (org-flag-heading nil))))
26795 (defun org-show-hidden-entry ()
26796 "Show an entry where even the heading is hidden."
26797 (save-excursion
26798 (org-show-entry)))
26800 (defun org-flag-heading (flag &optional entry)
26801 "Flag the current heading. FLAG non-nil means make invisible.
26802 When ENTRY is non-nil, show the entire entry."
26803 (save-excursion
26804 (org-back-to-heading t)
26805 ;; Check if we should show the entire entry
26806 (if entry
26807 (progn
26808 (org-show-entry)
26809 (save-excursion
26810 (and (outline-next-heading)
26811 (org-flag-heading nil))))
26812 (outline-flag-region (max (point-min) (1- (point)))
26813 (save-excursion (outline-end-of-heading) (point))
26814 flag))))
26816 (defun org-end-of-subtree (&optional invisible-OK to-heading)
26817 ;; This is an exact copy of the original function, but it uses
26818 ;; `org-back-to-heading', to make it work also in invisible
26819 ;; trees. And is uses an invisible-OK argument.
26820 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
26821 (org-back-to-heading invisible-OK)
26822 (let ((first t)
26823 (level (funcall outline-level)))
26824 (while (and (not (eobp))
26825 (or first (> (funcall outline-level) level)))
26826 (setq first nil)
26827 (outline-next-heading))
26828 (unless to-heading
26829 (if (memq (preceding-char) '(?\n ?\^M))
26830 (progn
26831 ;; Go to end of line before heading
26832 (forward-char -1)
26833 (if (memq (preceding-char) '(?\n ?\^M))
26834 ;; leave blank line before heading
26835 (forward-char -1))))))
26836 (point))
26838 (defun org-show-subtree ()
26839 "Show everything after this heading at deeper levels."
26840 (outline-flag-region
26841 (point)
26842 (save-excursion
26843 (outline-end-of-subtree) (outline-next-heading) (point))
26844 nil))
26846 (defun org-show-entry ()
26847 "Show the body directly following this heading.
26848 Show the heading too, if it is currently invisible."
26849 (interactive)
26850 (save-excursion
26851 (condition-case nil
26852 (progn
26853 (org-back-to-heading t)
26854 (outline-flag-region
26855 (max (point-min) (1- (point)))
26856 (save-excursion
26857 (re-search-forward
26858 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
26859 (or (match-beginning 1) (point-max)))
26860 nil))
26861 (error nil))))
26863 (defun org-make-options-regexp (kwds)
26864 "Make a regular expression for keyword lines."
26865 (concat
26867 "#?[ \t]*\\+\\("
26868 (mapconcat 'regexp-quote kwds "\\|")
26869 "\\):[ \t]*"
26870 "\\(.+\\)"))
26872 ;; Make isearch reveal the necessary context
26873 (defun org-isearch-end ()
26874 "Reveal context after isearch exits."
26875 (when isearch-success ; only if search was successful
26876 (if (featurep 'xemacs)
26877 ;; Under XEmacs, the hook is run in the correct place,
26878 ;; we directly show the context.
26879 (org-show-context 'isearch)
26880 ;; In Emacs the hook runs *before* restoring the overlays.
26881 ;; So we have to use a one-time post-command-hook to do this.
26882 ;; (Emacs 22 has a special variable, see function `org-mode')
26883 (unless (and (boundp 'isearch-mode-end-hook-quit)
26884 isearch-mode-end-hook-quit)
26885 ;; Only when the isearch was not quitted.
26886 (org-add-hook 'post-command-hook 'org-isearch-post-command
26887 'append 'local)))))
26889 (defun org-isearch-post-command ()
26890 "Remove self from hook, and show context."
26891 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
26892 (org-show-context 'isearch))
26895 ;;;; Address problems with some other packages
26897 ;; Make flyspell not check words in links, to not mess up our keymap
26898 (defun org-mode-flyspell-verify ()
26899 "Don't let flyspell put overlays at active buttons."
26900 (not (get-text-property (point) 'keymap)))
26902 ;; Make `bookmark-jump' show the jump location if it was hidden.
26903 (eval-after-load "bookmark"
26904 '(if (boundp 'bookmark-after-jump-hook)
26905 ;; We can use the hook
26906 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
26907 ;; Hook not available, use advice
26908 (defadvice bookmark-jump (after org-make-visible activate)
26909 "Make the position visible."
26910 (org-bookmark-jump-unhide))))
26912 (defun org-bookmark-jump-unhide ()
26913 "Unhide the current position, to show the bookmark location."
26914 (and (org-mode-p)
26915 (or (org-invisible-p)
26916 (save-excursion (goto-char (max (point-min) (1- (point))))
26917 (org-invisible-p)))
26918 (org-show-context 'bookmark-jump)))
26920 ;; Fix a bug in htmlize where there are text properties (face nil)
26921 (eval-after-load "htmlize"
26922 '(progn
26923 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
26924 "Make sure there are no nil faces"
26925 (setq ad-return-value (delq nil ad-return-value)))))
26927 ;; Make session.el ignore our circular variable
26928 (eval-after-load "session"
26929 '(add-to-list 'session-globals-exclude 'org-mark-ring))
26931 ;;;; Experimental code
26933 (defun org-closed-in-range ()
26934 "Sparse tree of items closed in a certain time range.
26935 Still experimental, may disappear in the future."
26936 (interactive)
26937 ;; Get the time interval from the user.
26938 (let* ((time1 (time-to-seconds
26939 (org-read-date nil 'to-time nil "Starting date: ")))
26940 (time2 (time-to-seconds
26941 (org-read-date nil 'to-time nil "End date:")))
26942 ;; callback function
26943 (callback (lambda ()
26944 (let ((time
26945 (time-to-seconds
26946 (apply 'encode-time
26947 (org-parse-time-string
26948 (match-string 1))))))
26949 ;; check if time in interval
26950 (and (>= time time1) (<= time time2))))))
26951 ;; make tree, check each match with the callback
26952 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
26954 (defun org-fill-paragraph-experimental (&optional justify)
26955 "Re-align a table, pass through to fill-paragraph if no table."
26956 (let ((table-p (org-at-table-p))
26957 (table.el-p (org-at-table.el-p)))
26958 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
26959 (table.el-p t) ; skip table.el tables
26960 (table-p (org-table-align) t) ; align org-mode tables
26961 ((save-excursion
26962 (let ((pos (1+ (point-at-eol))))
26963 (backward-paragraph 1)
26964 (re-search-forward "\\\\\\\\[ \t]*$" pos t)))
26965 (save-excursion
26966 (save-restriction
26967 (narrow-to-region (1+ (match-end 0)) (point-max))
26968 (fill-paragraph nil)
26969 t)))
26970 (t nil)))) ; call paragraph-fill
26972 ;; FIXME: this needs a much better algorithm
26973 (defun org-assign-fast-keys (alist)
26974 "Assign fast keys to a keyword-key alist.
26975 Respect keys that are already there."
26976 (let (new e k c c1 c2 (char ?a))
26977 (while (setq e (pop alist))
26978 (cond
26979 ((equal e '(:startgroup)) (push e new))
26980 ((equal e '(:endgroup)) (push e new))
26982 (setq k (car e) c2 nil)
26983 (if (cdr e)
26984 (setq c (cdr e))
26985 ;; automatically assign a character.
26986 (setq c1 (string-to-char
26987 (downcase (substring
26988 k (if (= (string-to-char k) ?@) 1 0)))))
26989 (if (or (rassoc c1 new) (rassoc c1 alist))
26990 (while (or (rassoc char new) (rassoc char alist))
26991 (setq char (1+ char)))
26992 (setq c2 c1))
26993 (setq c (or c2 char)))
26994 (push (cons k c) new))))
26995 (nreverse new)))
26997 (defcustom org-refile-targets '((nil . (:level . 1)))
26998 "Targets for refiling entries with \\[org-refile].
26999 This is list of cons cells. Each cell contains:
27000 - a specification of the files to be considered, either a list of files,
27001 or a symbol whose function or value fields will be used to retrieve
27002 a file name or a list of file names. Nil means, refile to a different
27003 heading in the current buffer.
27004 - A specification of how to find candidate refile targets. This may be
27005 any of
27006 - a cons cell (:tag . \"TAG\") to identify refile targes by a tag.
27007 This tag has to be present in all target headlines, inheritance will
27008 not be considered.
27009 - a cons cell (:todo . \"KEYWORD\" to identify refile targets by
27010 todo keyword.
27011 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
27012 headlines that are refiling targets.
27013 - a cons cell (:level . N). Any headline of level N is considered a target."
27014 ;; FIXME: what if there are a var and func with same name???
27015 :group 'org
27016 :type '(repeat
27017 (cons
27018 (choice :value org-agenda-files
27019 (const :tag "All agenda files" org-agenda-files)
27020 (const :tag "Current buffer" nil)
27021 (function) (variable) (file))
27022 (choice :tag "Identify target headline by"
27023 (cons :tag "Specific tag" (const :tag) (string))
27024 (cons :tag "TODO keyword" (const :todo) (string))
27025 (cons :tag "Regular expression" (const :regexp) (regexp))
27026 (cons :tag "Level number" (const :level) (integer))))))
27028 (defvar org-refile-target-table nil
27029 "The list of refile targets, created by `org-refile'.")
27031 (defun org-get-refile-targets ()
27032 "Produce a table with refile targets."
27033 ;; FIXME: interpret the different specs for refile targets.
27034 (put 'org-agenda-files 'org-restrict nil)
27035 (let ((entries org-refile-targets)
27036 org-agenda-new-files targets txt re files f desc descre)
27037 (while (setq entry (pop entries))
27038 (setq files (car entry) desc (cdr entry))
27039 (cond
27040 ((null files) (setq files (list (current-buffer))))
27041 ((and (symbolp files) (fboundp files))
27042 (setq files (funcall files)))
27043 ((and (symbolp files) (boundp files))
27044 (setq files (symbol-value files))))
27045 (if (stringp files) (setq files (list files)))
27046 (cond
27047 ((eq (car desc) :tag)
27048 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
27049 ((eq (car desc) :todo)
27050 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
27051 ((eq (car desc) :regexp)
27052 (setq descre (cdr desc)))
27053 ((eq (car desc) :level)
27054 (setq descre (concat "^\\*\\{" (number-to-string
27055 (if org-odd-levels-only
27056 (1- (* 2 (cdr desc)))
27057 (cdr desc)))
27058 "\\}[ \t]")))
27059 (t (error "Bad refiling target description %s" desc)))
27060 (while (setq f (pop files))
27061 (save-excursion
27062 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
27063 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
27064 (save-excursion
27065 (save-restriction
27066 (widen)
27067 (goto-char (point-min))
27068 (while (re-search-forward descre nil t)
27069 (goto-char (point-at-bol))
27070 (when (looking-at org-complex-heading-regexp)
27071 (setq txt (match-string 4)
27072 re (concat "^" (regexp-quote
27073 (buffer-substring (match-beginning 1)
27074 (match-end 4)))))
27075 (if (match-end 5) (setq re (concat re "[ \t]+"
27076 (regexp-quote
27077 (match-string 5)))))
27078 (setq re (concat re "[ \t]*$"))
27079 (push (list txt f re (point)) targets))
27080 (goto-char (point-at-eol))))))))
27081 (org-release-buffers org-agenda-new-buffers)
27082 (nreverse targets)))
27084 (defun org-refile (&optional reversed-or-update)
27085 "Move the entry at point to another heading.
27086 The list of target headings is compiled using the information in
27087 `org-refile-targets', which see. This list is created upon first use, and
27088 you can update it by calling this command with a double prefix (`C-u C-u').
27090 At the target location, the entry is filed as a subitem of the target heading.
27091 Depending on `org-reverse-note-order', the new subitem will either be the
27092 first of the last subitem. A single C-u prefix will toggle the value of this
27093 variable for the duration of the command."
27094 (interactive "P")
27095 (if (equal reversed-or-update '(16))
27096 (progn
27097 (setq org-refile-target-table (org-get-refile-targets))
27098 (message "Refile targets updated (%d targets)"
27099 (length org-refile-target-table)))
27100 (when (or (not org-refile-target-table)
27101 (and (= (length org-refile-targets) 1)
27102 (not (caar org-refile-targets))))
27103 (setq org-refile-target-table (org-get-refile-targets)))
27104 (unless org-refile-target-table
27105 (error "No refile targets"))
27106 (let* ((cbuf (current-buffer))
27107 (filename (buffer-file-name (buffer-base-buffer cbuf)))
27108 (fname (and filename (file-truename filename)))
27109 (tbl (mapcar
27110 (lambda (x)
27111 (if (not (equal fname (file-truename (nth 1 x))))
27112 (cons (concat (car x) " (" (file-name-nondirectory
27113 (nth 1 x)) ")")
27114 (cdr x))
27116 org-refile-target-table))
27117 (completion-ignore-case t)
27118 pos it nbuf file re level reversed)
27119 (when (setq it (completing-read "Refile to: " tbl
27120 nil t nil 'org-refile-history))
27121 (setq it (assoc it tbl)
27122 file (nth 1 it)
27123 re (nth 2 it))
27124 (org-copy-special)
27125 (save-excursion
27126 (set-buffer (setq nbuf (or (find-buffer-visiting file)
27127 (find-file-noselect file))))
27128 (setq reversed (org-notes-order-reversed-p))
27129 (if (equal reversed-or-update '(16)) (setq reversed (not reversed)))
27130 (save-excursion
27131 (save-restriction
27132 (widen)
27133 (goto-char (point-min))
27134 (unless (re-search-forward re nil t)
27135 (error "Cannot find target location - try again with `C-u' prefix."))
27136 (goto-char (match-beginning 0))
27137 (looking-at outline-regexp)
27138 (setq level (org-get-legal-level (funcall outline-level) 1))
27139 (goto-char (or (save-excursion
27140 (if reversed
27141 (outline-next-heading)
27142 (outline-get-next-sibling)))
27143 (point-max)))
27144 (org-paste-subtree level))))
27145 (org-cut-special)
27146 (message "Entry refiled to \"%s\"" (car it))))))
27148 (defcustom org-highlight-latex-fragments-and-specials nil
27149 "Non-nil means, fontify what is treated specially by the exporters."
27150 :group 'org-font-lock
27151 :type 'boolean)
27153 (defvar org-latex-and-specials-regexp nil
27154 "Regular expression for highlighting export special stuff.")
27156 (defun org-compute-latex-and-specials-regexp ()
27157 "Compute regular expression for stuff treated specially by exporters."
27158 (if (not org-highlight-latex-fragments-and-specials)
27159 (org-set-local 'org-latex-and-specials-regexp nil)
27160 (let*
27161 ((matchers (plist-get org-format-latex-options :matchers))
27162 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
27163 org-latex-regexps)))
27164 (options (org-combine-plists (org-default-export-plist)
27165 (org-infile-export-plist)))
27166 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
27167 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
27168 (org-export-with-TeX-macros (plist-get options :TeX-macros))
27169 (org-export-html-expand (plist-get options :expand-quoted-html))
27170 (org-export-with-special-strings (plist-get options :special-strings))
27171 (re-sub
27172 (cond
27173 ((equal org-export-with-sub-superscripts '{})
27174 (list org-match-substring-with-braces-regexp))
27175 (org-export-with-sub-superscripts
27176 (list org-match-substring-regexp))
27177 (t nil)))
27178 (re-latex
27179 (if org-export-with-LaTeX-fragments
27180 (mapcar (lambda (x) (nth 1 x)) latexs)))
27181 (re-macros
27182 (if org-export-with-TeX-macros
27183 (list (concat "\\\\"
27184 (regexp-opt
27185 (append (mapcar 'car org-html-entities)
27186 (if (boundp 'org-latex-entities)
27187 org-latex-entities nil))
27188 'words))) ; FIXME
27190 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
27191 (re-special (if org-export-with-special-strings
27192 (mapcar (lambda (x) (car x))
27193 org-export-html-special-string-regexps)))
27194 (re-rest
27195 (delq nil
27196 (list
27197 (if org-export-html-expand "@<[^>\n]+>")
27198 ))))
27199 (org-set-local
27200 'org-latex-and-specials-regexp
27201 (mapconcat 'identity (append re-latex re-sub re-macros re-special re-rest) "\\|")))))
27203 (defface org-latex-and-export-specials
27204 (let ((font (cond ((assq :inherit custom-face-attributes)
27205 '(:inherit underline))
27206 (t '(:underline t)))))
27207 `((((class grayscale) (background light))
27208 (:foreground "DimGray" ,@font))
27209 (((class grayscale) (background dark))
27210 (:foreground "LightGray" ,@font))
27211 (((class color) (background light))
27212 (:foreground "SaddleBrown"))
27213 (((class color) (background dark))
27214 (:foreground "burlywood"))
27215 (t (,@font))))
27216 "Face used to highlight math latex and other special exporter stuff."
27217 :group 'org-faces)
27219 (defun org-do-latex-and-special-faces (limit)
27220 "Run through the buffer and add overlays to links."
27221 (when org-latex-and-specials-regexp
27222 (let (rtn d)
27223 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
27224 limit t))
27225 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0)) 'face))
27226 '(org-code org-verbatim underline)))
27227 (progn
27228 (setq rtn t
27229 d (cond ((member (char-after (1+ (match-beginning 0))) '(?_ ?^)) 1)
27230 (t 0)))
27231 (font-lock-prepend-text-property
27232 (+ d (match-beginning 0)) (match-end 0)
27233 'face 'org-latex-and-export-specials)
27234 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
27235 '(font-lock-multiline t)))))
27236 rtn)))
27238 (defun org-find-first-timestamp (keyword inactive end)
27239 "Return location of first timestamp matching KEYWORD and INACTIVE.
27240 KEYWORD may be any of the timestamp keywords, or nil.
27241 INACTIVE means it should be an inactive timestamp.
27242 If there is no such time stamp, return nil."
27243 (catch 'exit
27244 (let (key ia)
27245 (setq inactive (and inactive t))
27246 (while (re-search-forward org-maybe-keyword-time-regexp end t)
27247 (setq key (and (match-end 1) (substring (match-string 1) 0 -1))
27248 (equal (char-after (match-beginning 3)) ?\[))
27249 (when (and (equal keyword key)
27250 (equal inactive ia))
27251 (throw 'exit (match-beginning 3)))))))
27253 ;;;; Finish up
27255 (provide 'org)
27257 (run-hooks 'org-load-hook)
27259 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
27260 ;;; org.el ends here