Small fixes.
[org-mode.git] / org.el
blobd880937953fd9d823223c2e92d9b84efc87e81dd
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, 2008 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.22a+
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 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
81 (require 'easymenu)
83 ;;;; Customization variables
85 ;;; Version
87 (defconst org-version "5.22a+"
88 "The version number of the file org.el.")
90 (defun org-version (&optional here)
91 "Show the org-mode version in the echo area.
92 With prefix arg HERE, insert it at point."
93 (interactive "P")
94 (let ((version (format "Org-mode version %s" org-version)))
95 (message version)
96 (if here
97 (insert version))))
99 ;;; Compatibility constants
100 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
101 (defconst org-format-transports-properties-p
102 (let ((x "a"))
103 (add-text-properties 0 1 '(test t) x)
104 (get-text-property 0 'test (format "%s" x)))
105 "Does format transport text properties?")
107 (defmacro org-bound-and-true-p (var)
108 "Return the value of symbol VAR if it is bound, else nil."
109 `(and (boundp (quote ,var)) ,var))
111 (defmacro org-unmodified (&rest body)
112 "Execute body without changing `buffer-modified-p'."
113 `(set-buffer-modified-p
114 (prog1 (buffer-modified-p) ,@body)))
116 (defmacro org-re (s)
117 "Replace posix classes in regular expression."
118 (if (featurep 'xemacs)
119 (let ((ss s))
120 (save-match-data
121 (while (string-match "\\[:alnum:\\]" ss)
122 (setq ss (replace-match "a-zA-Z0-9" t t ss)))
123 (while (string-match "\\[:alpha:\\]" ss)
124 (setq ss (replace-match "a-zA-Z" t t ss)))
125 ss))
128 (defmacro org-preserve-lc (&rest body)
129 `(let ((_line (org-current-line))
130 (_col (current-column)))
131 (unwind-protect
132 (progn ,@body)
133 (goto-line _line)
134 (move-to-column _col))))
136 (defmacro org-without-partial-completion (&rest body)
137 `(let ((pc-mode (and (boundp 'partial-completion-mode)
138 partial-completion-mode)))
139 (unwind-protect
140 (progn
141 (if pc-mode (partial-completion-mode -1))
142 ,@body)
143 (if pc-mode (partial-completion-mode 1)))))
145 ;;; The custom variables
147 (defgroup org nil
148 "Outline-based notes management and organizer."
149 :tag "Org"
150 :group 'outlines
151 :group 'hypermedia
152 :group 'calendar)
154 (eval-after-load "org" '(org-load-default-extensions))
155 (defcustom org-load-hook nil
156 "Hook that is run after org.el has been loaded."
157 :group 'org
158 :type 'hook)
160 (defcustom org-default-extensions '(org-irc)
161 "Extensions that should always be loaded together with org.el.
162 If the description starts with <A>, this means the extension
163 will be autoloaded when needed, preloading is not necessary."
164 :group 'org
165 :type
166 '(set :greedy t
167 (const :tag " Mouse support (org-mouse.el)" org-mouse)
168 (const :tag "<A> Publishing (org-publish.el)" org-publish)
169 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
170 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
171 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
173 (defun org-load-default-extensions ()
174 "Load all extensions listed in `org-default-extensions'."
175 (mapc (lambda (ext)
176 (condition-case nil (require ext)
177 (error (message "Problems while trying to load feature `%s'" ext))))
178 org-default-extensions))
180 ;; FIXME: Needs a separate group...
181 (defcustom org-completion-fallback-command 'hippie-expand
182 "The expansion command called by \\[org-complete] in normal context.
183 Normal means, no org-mode-specific context."
184 :group 'org
185 :type 'function)
187 (defgroup org-startup nil
188 "Options concerning startup of Org-mode."
189 :tag "Org Startup"
190 :group 'org)
192 (defcustom org-startup-folded t
193 "Non-nil means, entering Org-mode will switch to OVERVIEW.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
197 #+STARTUP: fold
198 #+STARTUP: nofold
199 #+STARTUP: content"
200 :group 'org-startup
201 :type '(choice
202 (const :tag "nofold: show all" nil)
203 (const :tag "fold: overview" t)
204 (const :tag "content: all headlines" content)))
206 (defcustom org-startup-truncated t
207 "Non-nil means, entering Org-mode will set `truncate-lines'.
208 This is useful since some lines containing links can be very long and
209 uninteresting. Also tables look terrible when wrapped."
210 :group 'org-startup
211 :type 'boolean)
213 (defcustom org-startup-align-all-tables nil
214 "Non-nil means, align all tables when visiting a file.
215 This is useful when the column width in tables is forced with <N> cookies
216 in table fields. Such tables will look correct only after the first re-align.
217 This can also be configured on a per-file basis by adding one of
218 the following lines anywhere in the buffer:
219 #+STARTUP: align
220 #+STARTUP: noalign"
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-insert-mode-line-in-empty-file nil
225 "Non-nil means insert the first line setting Org-mode in empty files.
226 When the function `org-mode' is called interactively in an empty file, this
227 normally means that the file name does not automatically trigger Org-mode.
228 To ensure that the file will always be in Org-mode in the future, a
229 line enforcing Org-mode will be inserted into the buffer, if this option
230 has been set."
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-replace-disputed-keys nil
235 "Non-nil means use alternative key bindings for some keys.
236 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
237 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
238 If you want to use Org-mode together with one of these other modes,
239 or more generally if you would like to move some Org-mode commands to
240 other keys, set this variable and configure the keys with the variable
241 `org-disputed-keys'.
243 This option is only relevant at load-time of Org-mode, and must be set
244 *before* org.el is loaded. Changing it requires a restart of Emacs to
245 become effective."
246 :group 'org-startup
247 :type 'boolean)
249 (if (fboundp 'defvaralias)
250 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
252 (defcustom org-disputed-keys
253 '(([(shift up)] . [(meta p)])
254 ([(shift down)] . [(meta n)])
255 ([(shift left)] . [(meta -)])
256 ([(shift right)] . [(meta +)])
257 ([(control shift right)] . [(meta shift +)])
258 ([(control shift left)] . [(meta shift -)]))
259 "Keys for which Org-mode and other modes compete.
260 This is an alist, cars are the default keys, second element specifies
261 the alternative to use when `org-replace-disputed-keys' is t.
263 Keys can be specified in any syntax supported by `define-key'.
264 The value of this option takes effect only at Org-mode's startup,
265 therefore you'll have to restart Emacs to apply it after changing."
266 :group 'org-startup
267 :type 'alist)
269 (defun org-key (key)
270 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
271 Or return the original if not disputed."
272 (if org-replace-disputed-keys
273 (let* ((nkey (key-description key))
274 (x (org-find-if (lambda (x)
275 (equal (key-description (car x)) nkey))
276 org-disputed-keys)))
277 (if x (cdr x) key))
278 key))
280 (defun org-find-if (predicate seq)
281 (catch 'exit
282 (while seq
283 (if (funcall predicate (car seq))
284 (throw 'exit (car seq))
285 (pop seq)))))
287 (defun org-defkey (keymap key def)
288 "Define a key, possibly translated, as returned by `org-key'."
289 (define-key keymap (org-key key) def))
291 (defcustom org-ellipsis nil
292 "The ellipsis to use in the Org-mode outline.
293 When nil, just use the standard three dots. When a string, use that instead,
294 When a face, use the standart 3 dots, but with the specified face.
295 The change affects only Org-mode (which will then use its own display table).
296 Changing this requires executing `M-x org-mode' in a buffer to become
297 effective."
298 :group 'org-startup
299 :type '(choice (const :tag "Default" nil)
300 (face :tag "Face" :value org-warning)
301 (string :tag "String" :value "...#")))
303 (defvar org-display-table nil
304 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
306 (defgroup org-keywords nil
307 "Keywords in Org-mode."
308 :tag "Org Keywords"
309 :group 'org)
311 (defcustom org-deadline-string "DEADLINE:"
312 "String to mark deadline entries.
313 A deadline is this string, followed by a time stamp. Should be a word,
314 terminated by a colon. You can insert a schedule keyword and
315 a timestamp with \\[org-deadline].
316 Changes become only effective after restarting Emacs."
317 :group 'org-keywords
318 :type 'string)
320 (defcustom org-scheduled-string "SCHEDULED:"
321 "String to mark scheduled TODO entries.
322 A schedule is this string, followed by a time stamp. Should be a word,
323 terminated by a colon. You can insert a schedule keyword and
324 a timestamp with \\[org-schedule].
325 Changes become only effective after restarting Emacs."
326 :group 'org-keywords
327 :type 'string)
329 (defcustom org-closed-string "CLOSED:"
330 "String used as the prefix for timestamps logging closing a TODO entry."
331 :group 'org-keywords
332 :type 'string)
334 (defcustom org-clock-string "CLOCK:"
335 "String used as prefix for timestamps clocking work hours on an item."
336 :group 'org-keywords
337 :type 'string)
339 (defcustom org-comment-string "COMMENT"
340 "Entries starting with this keyword will never be exported.
341 An entry can be toggled between COMMENT and normal with
342 \\[org-toggle-comment].
343 Changes become only effective after restarting Emacs."
344 :group 'org-keywords
345 :type 'string)
347 (defcustom org-quote-string "QUOTE"
348 "Entries starting with this keyword will be exported in fixed-width font.
349 Quoting applies only to the text in the entry following the headline, and does
350 not extend beyond the next headline, even if that is lower level.
351 An entry can be toggled between QUOTE and normal with
352 \\[org-toggle-fixed-width-section]."
353 :group 'org-keywords
354 :type 'string)
356 (defconst org-repeat-re
357 ; (concat "\\(?:\\<\\(?:" org-scheduled-string "\\|" org-deadline-string "\\)"
358 ; " +<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\)\\(\\+[0-9]+[dwmy]\\)")
359 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\(\\+[0-9]+[dwmy]\\)"
360 "Regular expression for specifying repeated events.
361 After a match, group 1 contains the repeat expression.")
363 (defgroup org-structure nil
364 "Options concerning the general structure of Org-mode files."
365 :tag "Org Structure"
366 :group 'org)
368 (defgroup org-reveal-location nil
369 "Options about how to make context of a location visible."
370 :tag "Org Reveal Location"
371 :group 'org-structure)
373 (defconst org-context-choice
374 '(choice
375 (const :tag "Always" t)
376 (const :tag "Never" nil)
377 (repeat :greedy t :tag "Individual contexts"
378 (cons
379 (choice :tag "Context"
380 (const agenda)
381 (const org-goto)
382 (const occur-tree)
383 (const tags-tree)
384 (const link-search)
385 (const mark-goto)
386 (const bookmark-jump)
387 (const isearch)
388 (const default))
389 (boolean))))
390 "Contexts for the reveal options.")
392 (defcustom org-show-hierarchy-above '((default . t))
393 "Non-nil means, show full hierarchy when revealing a location.
394 Org-mode often shows locations in an org-mode file which might have
395 been invisible before. When this is set, the hierarchy of headings
396 above the exposed location is shown.
397 Turning this off for example for sparse trees makes them very compact.
398 Instead of t, this can also be an alist specifying this option for different
399 contexts. Valid contexts are
400 agenda when exposing an entry from the agenda
401 org-goto when using the command `org-goto' on key C-c C-j
402 occur-tree when using the command `org-occur' on key C-c /
403 tags-tree when constructing a sparse tree based on tags matches
404 link-search when exposing search matches associated with a link
405 mark-goto when exposing the jump goal of a mark
406 bookmark-jump when exposing a bookmark location
407 isearch when exiting from an incremental search
408 default default for all contexts not set explicitly"
409 :group 'org-reveal-location
410 :type org-context-choice)
412 (defcustom org-show-following-heading '((default . nil))
413 "Non-nil means, show following heading when revealing a location.
414 Org-mode often shows locations in an org-mode file which might have
415 been invisible before. When this is set, the heading following the
416 match is shown.
417 Turning this off for example for sparse trees makes them very compact,
418 but makes it harder to edit the location of the match. In such a case,
419 use the command \\[org-reveal] to show more context.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. See `org-show-hierarchy-above' for valid contexts."
422 :group 'org-reveal-location
423 :type org-context-choice)
425 (defcustom org-show-siblings '((default . nil) (isearch t))
426 "Non-nil means, show all sibling heading when revealing a location.
427 Org-mode often shows locations in an org-mode file which might have
428 been invisible before. When this is set, the sibling of the current entry
429 heading are all made visible. If `org-show-hierarchy-above' is t,
430 the same happens on each level of the hierarchy above the current entry.
432 By default this is on for the isearch context, off for all other contexts.
433 Turning this off for example for sparse trees makes them very compact,
434 but makes it harder to edit the location of the match. In such a case,
435 use the command \\[org-reveal] to show more context.
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 org-context-choice)
441 (defcustom org-show-entry-below '((default . nil))
442 "Non-nil means, show the entry below a headline when revealing a location.
443 Org-mode often shows locations in an org-mode file which might have
444 been invisible before. When this is set, the text below the headline that is
445 exposed is also shown.
447 By default this is off for all contexts.
448 Instead of t, this can also be an alist specifying this option for different
449 contexts. See `org-show-hierarchy-above' for valid contexts."
450 :group 'org-reveal-location
451 :type org-context-choice)
453 (defgroup org-cycle nil
454 "Options concerning visibility cycling in Org-mode."
455 :tag "Org Cycle"
456 :group 'org-structure)
458 (defcustom org-drawers '("PROPERTIES" "CLOCK")
459 "Names of drawers. Drawers are not opened by cycling on the headline above.
460 Drawers only open with a TAB on the drawer line itself. A drawer looks like
461 this:
462 :DRAWERNAME:
463 .....
464 :END:
465 The drawer \"PROPERTIES\" is special for capturing properties through
466 the property API.
468 Drawers can be defined on the per-file basis with a line like:
470 #+DRAWERS: HIDDEN STATE PROPERTIES"
471 :group 'org-structure
472 :type '(repeat (string :tag "Drawer Name")))
474 (defcustom org-cycle-global-at-bob nil
475 "Cycle globally if cursor is at beginning of buffer and not at a headline.
476 This makes it possible to do global cycling without having to use S-TAB or
477 C-u TAB. For this special case to work, the first line of the buffer
478 must not be a headline - it may be empty ot some other text. When used in
479 this way, `org-cycle-hook' is disables temporarily, to make sure the
480 cursor stays at the beginning of the buffer.
481 When this option is nil, don't do anything special at the beginning
482 of the buffer."
483 :group 'org-cycle
484 :type 'boolean)
486 (defcustom org-cycle-emulate-tab t
487 "Where should `org-cycle' emulate TAB.
488 nil Never
489 white Only in completely white lines
490 whitestart Only at the beginning of lines, before the first non-white char
491 t Everywhere except in headlines
492 exc-hl-bol Everywhere except at the start of a headline
493 If TAB is used in a place where it does not emulate TAB, the current subtree
494 visibility is cycled."
495 :group 'org-cycle
496 :type '(choice (const :tag "Never" nil)
497 (const :tag "Only in completely white lines" white)
498 (const :tag "Before first char in a line" whitestart)
499 (const :tag "Everywhere except in headlines" t)
500 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
503 (defcustom org-cycle-separator-lines 2
504 "Number of empty lines needed to keep an empty line between collapsed trees.
505 If you leave an empty line between the end of a subtree and the following
506 headline, this empty line is hidden when the subtree is folded.
507 Org-mode will leave (exactly) one empty line visible if the number of
508 empty lines is equal or larger to the number given in this variable.
509 So the default 2 means, at least 2 empty lines after the end of a subtree
510 are needed to produce free space between a collapsed subtree and the
511 following headline.
513 Special case: when 0, never leave empty lines in collapsed view."
514 :group 'org-cycle
515 :type 'integer)
517 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
518 org-cycle-hide-drawers
519 org-cycle-show-empty-lines
520 org-optimize-window-after-visibility-change)
521 "Hook that is run after `org-cycle' has changed the buffer visibility.
522 The function(s) in this hook must accept a single argument which indicates
523 the new state that was set by the most recent `org-cycle' command. The
524 argument is a symbol. After a global state change, it can have the values
525 `overview', `content', or `all'. After a local state change, it can have
526 the values `folded', `children', or `subtree'."
527 :group 'org-cycle
528 :type 'hook)
530 (defgroup org-edit-structure nil
531 "Options concerning structure editing in Org-mode."
532 :tag "Org Edit Structure"
533 :group 'org-structure)
535 (defcustom org-odd-levels-only nil
536 "Non-nil means, skip even levels and only use odd levels for the outline.
537 This has the effect that two stars are being added/taken away in
538 promotion/demotion commands. It also influences how levels are
539 handled by the exporters.
540 Changing it requires restart of `font-lock-mode' to become effective
541 for fontification also in regions already fontified.
542 You may also set this on a per-file basis by adding one of the following
543 lines to the buffer:
545 #+STARTUP: odd
546 #+STARTUP: oddeven"
547 :group 'org-edit-structure
548 :group 'org-font-lock
549 :type 'boolean)
551 (defcustom org-adapt-indentation t
552 "Non-nil means, adapt indentation when promoting and demoting.
553 When this is set and the *entire* text in an entry is indented, the
554 indentation is increased by one space in a demotion command, and
555 decreased by one in a promotion command. If any line in the entry
556 body starts at column 0, indentation is not changed at all."
557 :group 'org-edit-structure
558 :type 'boolean)
560 (defcustom org-special-ctrl-a/e nil
561 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
562 When t, `C-a' will bring back the cursor to the beginning of the
563 headline text, i.e. after the stars and after a possible TODO keyword.
564 In an item, this will be the position after the bullet.
565 When the cursor is already at that position, another `C-a' will bring
566 it to the beginning of the line.
567 `C-e' will jump to the end of the headline, ignoring the presence of tags
568 in the headline. A second `C-e' will then jump to the true end of the
569 line, after any tags.
570 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
571 and only a directly following, identical keypress will bring the cursor
572 to the special positions."
573 :group 'org-edit-structure
574 :type '(choice
575 (const :tag "off" nil)
576 (const :tag "after bullet first" t)
577 (const :tag "border first" reversed)))
579 (if (fboundp 'defvaralias)
580 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
582 (defcustom org-special-ctrl-k nil
583 "Non-nil means `C-k' will behave specially in headlines.
584 When nil, `C-k' will call the default `kill-line' command.
585 When t, the following will happen while the cursor is in the headline:
587 - When the cursor is at the beginning of a headline, kill the entire
588 line and possible the folded subtree below the line.
589 - When in the middle of the headline text, kill the headline up to the tags.
590 - When after the headline text, kill the tags."
591 :group 'org-edit-structure
592 :type 'boolean)
594 (defcustom org-M-RET-may-split-line '((default . t))
595 "Non-nil means, M-RET will split the line at the cursor position.
596 When nil, it will go to the end of the line before making a
597 new line.
598 You may also set this option in a different way for different
599 contexts. Valid contexts are:
601 headline when creating a new headline
602 item when creating a new item
603 table in a table field
604 default the value to be used for all contexts not explicitly
605 customized"
606 :group 'org-structure
607 :group 'org-table
608 :type '(choice
609 (const :tag "Always" t)
610 (const :tag "Never" nil)
611 (repeat :greedy t :tag "Individual contexts"
612 (cons
613 (choice :tag "Context"
614 (const headline)
615 (const item)
616 (const table)
617 (const default))
618 (boolean)))))
621 (defcustom org-blank-before-new-entry '((heading . nil)
622 (plain-list-item . nil))
623 "Should `org-insert-heading' leave a blank line before new heading/item?
624 The value is an alist, with `heading' and `plain-list-item' as car,
625 and a boolean flag as cdr."
626 :group 'org-edit-structure
627 :type '(list
628 (cons (const heading) (boolean))
629 (cons (const plain-list-item) (boolean))))
631 (defcustom org-insert-heading-hook nil
632 "Hook being run after inserting a new heading."
633 :group 'org-edit-structure
634 :type 'hook)
636 (defcustom org-enable-fixed-width-editor t
637 "Non-nil means, lines starting with \":\" are treated as fixed-width.
638 This currently only means, they are never auto-wrapped.
639 When nil, such lines will be treated like ordinary lines.
640 See also the QUOTE keyword."
641 :group 'org-edit-structure
642 :type 'boolean)
644 (defcustom org-goto-auto-isearch t
645 "Non-nil means, typing characters in org-goto starts incremental search."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defgroup org-sparse-trees nil
650 "Options concerning sparse trees in Org-mode."
651 :tag "Org Sparse Trees"
652 :group 'org-structure)
654 (defcustom org-highlight-sparse-tree-matches t
655 "Non-nil means, highlight all matches that define a sparse tree.
656 The highlights will automatically disappear the next time the buffer is
657 changed by an edit command."
658 :group 'org-sparse-trees
659 :type 'boolean)
661 (defcustom org-remove-highlights-with-change t
662 "Non-nil means, any change to the buffer will remove temporary highlights.
663 Such highlights are created by `org-occur' and `org-clock-display'.
664 When nil, `C-c C-c needs to be used to get rid of the highlights.
665 The highlights created by `org-preview-latex-fragment' always need
666 `C-c C-c' to be removed."
667 :group 'org-sparse-trees
668 :group 'org-time
669 :type 'boolean)
672 (defcustom org-occur-hook '(org-first-headline-recenter)
673 "Hook that is run after `org-occur' has constructed a sparse tree.
674 This can be used to recenter the window to show as much of the structure
675 as possible."
676 :group 'org-sparse-trees
677 :type 'hook)
679 (defgroup org-plain-lists nil
680 "Options concerning plain lists in Org-mode."
681 :tag "Org Plain lists"
682 :group 'org-structure)
684 (defcustom org-cycle-include-plain-lists nil
685 "Non-nil means, include plain lists into visibility cycling.
686 This means that during cycling, plain list items will *temporarily* be
687 interpreted as outline headlines with a level given by 1000+i where i is the
688 indentation of the bullet. In all other operations, plain list items are
689 not seen as headlines. For example, you cannot assign a TODO keyword to
690 such an item."
691 :group 'org-plain-lists
692 :type 'boolean)
694 (defcustom org-plain-list-ordered-item-terminator t
695 "The character that makes a line with leading number an ordered list item.
696 Valid values are ?. and ?\). To get both terminators, use t. While
697 ?. may look nicer, it creates the danger that a line with leading
698 number may be incorrectly interpreted as an item. ?\) therefore is
699 the safe choice."
700 :group 'org-plain-lists
701 :type '(choice (const :tag "dot like in \"2.\"" ?.)
702 (const :tag "paren like in \"2)\"" ?\))
703 (const :tab "both" t)))
705 (defcustom org-auto-renumber-ordered-lists t
706 "Non-nil means, automatically renumber ordered plain lists.
707 Renumbering happens when the sequence have been changed with
708 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
709 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
710 :group 'org-plain-lists
711 :type 'boolean)
713 (defcustom org-provide-checkbox-statistics t
714 "Non-nil means, update checkbox statistics after insert and toggle.
715 When this is set, checkbox statistics is updated each time you either insert
716 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
717 with \\[org-ctrl-c-ctrl-c\\]."
718 :group 'org-plain-lists
719 :type 'boolean)
721 (defgroup org-archive nil
722 "Options concerning archiving in Org-mode."
723 :tag "Org Archive"
724 :group 'org-structure)
726 (defcustom org-archive-tag "ARCHIVE"
727 "The tag that marks a subtree as archived.
728 An archived subtree does not open during visibility cycling, and does
729 not contribute to the agenda listings.
730 After changing this, font-lock must be restarted in the relevant buffers to
731 get the proper fontification."
732 :group 'org-archive
733 :group 'org-keywords
734 :type 'string)
736 (defcustom org-agenda-skip-archived-trees t
737 "Non-nil means, the agenda will skip any items located in archived trees.
738 An archived tree is a tree marked with the tag ARCHIVE."
739 :group 'org-archive
740 :group 'org-agenda-skip
741 :type 'boolean)
743 (defcustom org-cycle-open-archived-trees nil
744 "Non-nil means, `org-cycle' will open archived trees.
745 An archived tree is a tree marked with the tag ARCHIVE.
746 When nil, archived trees will stay folded. You can still open them with
747 normal outline commands like `show-all', but not with the cycling commands."
748 :group 'org-archive
749 :group 'org-cycle
750 :type 'boolean)
752 (defcustom org-sparse-tree-open-archived-trees nil
753 "Non-nil means sparse tree construction shows matches in archived trees.
754 When nil, matches in these trees are highlighted, but the trees are kept in
755 collapsed state."
756 :group 'org-archive
757 :group 'org-sparse-trees
758 :type 'boolean)
760 (defcustom org-archive-location "%s_archive::"
761 "The location where subtrees should be archived.
762 This string consists of two parts, separated by a double-colon.
764 The first part is a file name - when omitted, archiving happens in the same
765 file. %s will be replaced by the current file name (without directory part).
766 Archiving to a different file is useful to keep archived entries from
767 contributing to the Org-mode Agenda.
769 The part after the double colon is a headline. The archived entries will be
770 filed under that headline. When omitted, the subtrees are simply filed away
771 at the end of the file, as top-level entries.
773 Here are a few examples:
774 \"%s_archive::\"
775 If the current file is Projects.org, archive in file
776 Projects.org_archive, as top-level trees. This is the default.
778 \"::* Archived Tasks\"
779 Archive in the current file, under the top-level headline
780 \"* Archived Tasks\".
782 \"~/org/archive.org::\"
783 Archive in file ~/org/archive.org (absolute path), as top-level trees.
785 \"basement::** Finished Tasks\"
786 Archive in file ./basement (relative path), as level 3 trees
787 below the level 2 heading \"** Finished Tasks\".
789 You may set this option on a per-file basis by adding to the buffer a
790 line like
792 #+ARCHIVE: basement::** Finished Tasks"
793 :group 'org-archive
794 :type 'string)
796 (defcustom org-archive-mark-done t
797 "Non-nil means, mark entries as DONE when they are moved to the archive file.
798 This can be a string to set the keyword to use. When t, Org-mode will
799 use the first keyword in its list that means done."
800 :group 'org-archive
801 :type '(choice
802 (const :tag "No" nil)
803 (const :tag "Yes" t)
804 (string :tag "Use this keyword")))
806 (defcustom org-archive-stamp-time t
807 "Non-nil means, add a time stamp to entries moved to an archive file.
808 This variable is obsolete and has no effect anymore, instead add ot remove
809 `time' from the variablle `org-archive-save-context-info'."
810 :group 'org-archive
811 :type 'boolean)
813 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
814 "Parts of context info that should be stored as properties when archiving.
815 When a subtree is moved to an archive file, it looses information given by
816 context, like inherited tags, the category, and possibly also the TODO
817 state (depending on the variable `org-archive-mark-done').
818 This variable can be a list of any of the following symbols:
820 time The time of archiving.
821 file The file where the entry originates.
822 itags The local tags, in the headline of the subtree.
823 ltags The tags the subtree inherits from further up the hierarchy.
824 todo The pre-archive TODO state.
825 category The category, taken from file name or #+CATEGORY lines.
826 olpath The outline path to the item. These are all headlines above
827 the current item, separated by /, like a file path.
829 For each symbol present in the list, a property will be created in
830 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
831 information."
832 :group 'org-archive
833 :type '(set :greedy t
834 (const :tag "Time" time)
835 (const :tag "File" file)
836 (const :tag "Category" category)
837 (const :tag "TODO state" todo)
838 (const :tag "TODO state" priority)
839 (const :tag "Inherited tags" itags)
840 (const :tag "Outline path" olpath)
841 (const :tag "Local tags" ltags)))
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
890 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
891 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
892 In the optimized version, the table editor takes over all simple keys that
893 normally just insert a character. In tables, the characters are inserted
894 in a way to minimize disturbing the table structure (i.e. in overwrite mode
895 for empty fields). Outside tables, the correct binding of the keys is
896 restored.
898 The default for this option is t if the optimized version is also used in
899 Org-mode. See the variable `org-enable-table-editor' for details. Changing
900 this variable requires a restart of Emacs to become effective."
901 :group 'org-table
902 :type 'boolean)
904 (defcustom orgtbl-radio-table-templates
905 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
906 % END RECEIVE ORGTBL %n
907 \\begin{comment}
908 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
909 | | |
910 \\end{comment}\n")
911 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
912 @c END RECEIVE ORGTBL %n
913 @ignore
914 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
915 | | |
916 @end ignore\n")
917 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
918 <!-- END RECEIVE ORGTBL %n -->
919 <!--
920 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
921 | | |
922 -->\n"))
923 "Templates for radio tables in different major modes.
924 All occurrences of %n in a template will be replaced with the name of the
925 table, obtained by prompting the user."
926 :group 'org-table
927 :type '(repeat
928 (list (symbol :tag "Major mode")
929 (string :tag "Format"))))
931 (defgroup org-table-settings nil
932 "Settings for tables in Org-mode."
933 :tag "Org Table Settings"
934 :group 'org-table)
936 (defcustom org-table-default-size "5x2"
937 "The default size for newly created tables, Columns x Rows."
938 :group 'org-table-settings
939 :type 'string)
941 (defcustom org-table-number-regexp
942 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
943 "Regular expression for recognizing numbers in table columns.
944 If a table column contains mostly numbers, it will be aligned to the
945 right. If not, it will be aligned to the left.
947 The default value of this option is a regular expression which allows
948 anything which looks remotely like a number as used in scientific
949 context. For example, all of the following will be considered a
950 number:
951 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
953 Other options offered by the customize interface are more restrictive."
954 :group 'org-table-settings
955 :type '(choice
956 (const :tag "Positive Integers"
957 "^[0-9]+$")
958 (const :tag "Integers"
959 "^[-+]?[0-9]+$")
960 (const :tag "Floating Point Numbers"
961 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
962 (const :tag "Floating Point Number or Integer"
963 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
964 (const :tag "Exponential, Floating point, Integer"
965 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
966 (const :tag "Very General Number-Like, including hex"
967 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
968 (string :tag "Regexp:")))
970 (defcustom org-table-number-fraction 0.5
971 "Fraction of numbers in a column required to make the column align right.
972 In a column all non-white fields are considered. If at least this
973 fraction of fields is matched by `org-table-number-fraction',
974 alignment to the right border applies."
975 :group 'org-table-settings
976 :type 'number)
978 (defgroup org-table-editing nil
979 "Behavior of tables during editing in Org-mode."
980 :tag "Org Table Editing"
981 :group 'org-table)
983 (defcustom org-table-automatic-realign t
984 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
985 When nil, aligning is only done with \\[org-table-align], or after column
986 removal/insertion."
987 :group 'org-table-editing
988 :type 'boolean)
990 (defcustom org-table-auto-blank-field t
991 "Non-nil means, automatically blank table field when starting to type into it.
992 This only happens when typing immediately after a field motion
993 command (TAB, S-TAB or RET).
994 Only relevant when `org-enable-table-editor' is equal to `optimized'."
995 :group 'org-table-editing
996 :type 'boolean)
998 (defcustom org-table-tab-jumps-over-hlines t
999 "Non-nil means, tab in the last column of a table with jump over a hline.
1000 If a horizontal separator line is following the current line,
1001 `org-table-next-field' can either create a new row before that line, or jump
1002 over the line. When this option is nil, a new line will be created before
1003 this line."
1004 :group 'org-table-editing
1005 :type 'boolean)
1007 (defcustom org-table-tab-recognizes-table.el t
1008 "Non-nil means, TAB will automatically notice a table.el table.
1009 When it sees such a table, it moves point into it and - if necessary -
1010 calls `table-recognize-table'."
1011 :group 'org-table-editing
1012 :type 'boolean)
1014 (defgroup org-table-calculation nil
1015 "Options concerning tables in Org-mode."
1016 :tag "Org Table Calculation"
1017 :group 'org-table)
1019 (defcustom org-table-use-standard-references t
1020 "Should org-mode work with table refrences like B3 instead of @3$2?
1021 Possible values are:
1022 nil never use them
1023 from accept as input, do not present for editing
1024 t: accept as input and present for editing"
1025 :group 'org-table-calculation
1026 :type '(choice
1027 (const :tag "Never, don't even check unser input for them" nil)
1028 (const :tag "Always, both as user input, and when editing" t)
1029 (const :tag "Convert user input, don't offer during editing" 'from)))
1031 (defcustom org-table-copy-increment t
1032 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1033 :group 'org-table-calculation
1034 :type 'boolean)
1036 (defcustom org-calc-default-modes
1037 '(calc-internal-prec 12
1038 calc-float-format (float 5)
1039 calc-angle-mode deg
1040 calc-prefer-frac nil
1041 calc-symbolic-mode nil
1042 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1043 calc-display-working-message t
1045 "List with Calc mode settings for use in calc-eval for table formulas.
1046 The list must contain alternating symbols (Calc modes variables and values).
1047 Don't remove any of the default settings, just change the values. Org-mode
1048 relies on the variables to be present in the list."
1049 :group 'org-table-calculation
1050 :type 'plist)
1052 (defcustom org-table-formula-evaluate-inline t
1053 "Non-nil means, TAB and RET evaluate a formula in current table field.
1054 If the current field starts with an equal sign, it is assumed to be a formula
1055 which should be evaluated as described in the manual and in the documentation
1056 string of the command `org-table-eval-formula'. This feature requires the
1057 Emacs calc package.
1058 When this variable is nil, formula calculation is only available through
1059 the command \\[org-table-eval-formula]."
1060 :group 'org-table-calculation
1061 :type 'boolean)
1063 (defcustom org-table-formula-use-constants t
1064 "Non-nil means, interpret constants in formulas in tables.
1065 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1066 by the value given in `org-table-formula-constants', or by a value obtained
1067 from the `constants.el' package."
1068 :group 'org-table-calculation
1069 :type 'boolean)
1071 (defcustom org-table-formula-constants nil
1072 "Alist with constant names and values, for use in table formulas.
1073 The car of each element is a name of a constant, without the `$' before it.
1074 The cdr is the value as a string. For example, if you'd like to use the
1075 speed of light in a formula, you would configure
1077 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1079 and then use it in an equation like `$1*$c'.
1081 Constants can also be defined on a per-file basis using a line like
1083 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1084 :group 'org-table-calculation
1085 :type '(repeat
1086 (cons (string :tag "name")
1087 (string :tag "value"))))
1089 (defvar org-table-formula-constants-local nil
1090 "Local version of `org-table-formula-constants'.")
1091 (make-variable-buffer-local 'org-table-formula-constants-local)
1093 (defcustom org-table-allow-automatic-line-recalculation t
1094 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1095 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1096 :group 'org-table-calculation
1097 :type 'boolean)
1099 (defgroup org-link nil
1100 "Options concerning links in Org-mode."
1101 :tag "Org Link"
1102 :group 'org)
1104 (defvar org-link-abbrev-alist-local nil
1105 "Buffer-local version of `org-link-abbrev-alist', which see.
1106 The value of this is taken from the #+LINK lines.")
1107 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1109 (defcustom org-link-abbrev-alist nil
1110 "Alist of link abbreviations.
1111 The car of each element is a string, to be replaced at the start of a link.
1112 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1113 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1115 [[linkkey:tag][description]]
1117 If REPLACE is a string, the tag will simply be appended to create the link.
1118 If the string contains \"%s\", the tag will be inserted there.
1120 REPLACE may also be a function that will be called with the tag as the
1121 only argument to create the link, which should be returned as a string.
1123 See the manual for examples."
1124 :group 'org-link
1125 :type 'alist)
1127 (defcustom org-descriptive-links t
1128 "Non-nil means, hide link part and only show description of bracket links.
1129 Bracket links are like [[link][descritpion]]. This variable sets the initial
1130 state in new org-mode buffers. The setting can then be toggled on a
1131 per-buffer basis from the Org->Hyperlinks menu."
1132 :group 'org-link
1133 :type 'boolean)
1135 (defcustom org-link-file-path-type 'adaptive
1136 "How the path name in file links should be stored.
1137 Valid values are:
1139 relative Relative to the current directory, i.e. the directory of the file
1140 into which the link is being inserted.
1141 absolute Absolute path, if possible with ~ for home directory.
1142 noabbrev Absolute path, no abbreviation of home directory.
1143 adaptive Use relative path for files in the current directory and sub-
1144 directories of it. For other files, use an absolute path."
1145 :group 'org-link
1146 :type '(choice
1147 (const relative)
1148 (const absolute)
1149 (const noabbrev)
1150 (const adaptive)))
1152 (defcustom org-activate-links '(bracket angle plain radio tag date)
1153 "Types of links that should be activated in Org-mode files.
1154 This is a list of symbols, each leading to the activation of a certain link
1155 type. In principle, it does not hurt to turn on most link types - there may
1156 be a small gain when turning off unused link types. The types are:
1158 bracket The recommended [[link][description]] or [[link]] links with hiding.
1159 angular Links in angular brackes that may contain whitespace like
1160 <bbdb:Carsten Dominik>.
1161 plain Plain links in normal text, no whitespace, like http://google.com.
1162 radio Text that is matched by a radio target, see manual for details.
1163 tag Tag settings in a headline (link to tag search).
1164 date Time stamps (link to calendar).
1166 Changing this variable requires a restart of Emacs to become effective."
1167 :group 'org-link
1168 :type '(set (const :tag "Double bracket links (new style)" bracket)
1169 (const :tag "Angular bracket links (old style)" angular)
1170 (const :tag "Plain text links" plain)
1171 (const :tag "Radio target matches" radio)
1172 (const :tag "Tags" tag)
1173 (const :tag "Timestamps" date)))
1175 (defgroup org-link-store nil
1176 "Options concerning storing links in Org-mode"
1177 :tag "Org Store Link"
1178 :group 'org-link)
1180 (defcustom org-email-link-description-format "Email %c: %.30s"
1181 "Format of the description part of a link to an email or usenet message.
1182 The following %-excapes will be replaced by corresponding information:
1184 %F full \"From\" field
1185 %f name, taken from \"From\" field, address if no name
1186 %T full \"To\" field
1187 %t first name in \"To\" field, address if no name
1188 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1189 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1190 %s subject
1191 %m message-id.
1193 You may use normal field width specification between the % and the letter.
1194 This is for example useful to limit the length of the subject.
1196 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1197 :group 'org-link-store
1198 :type 'string)
1200 (defcustom org-from-is-user-regexp
1201 (let (r1 r2)
1202 (when (and user-mail-address (not (string= user-mail-address "")))
1203 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1204 (when (and user-full-name (not (string= user-full-name "")))
1205 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1206 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1207 "Regexp mached against the \"From:\" header of an email or usenet message.
1208 It should match if the message is from the user him/herself."
1209 :group 'org-link-store
1210 :type 'regexp)
1212 (defcustom org-context-in-file-links t
1213 "Non-nil means, file links from `org-store-link' contain context.
1214 A search string will be added to the file name with :: as separator and
1215 used to find the context when the link is activated by the command
1216 `org-open-at-point'.
1217 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1218 negates this setting for the duration of the command."
1219 :group 'org-link-store
1220 :type 'boolean)
1222 (defcustom org-keep-stored-link-after-insertion nil
1223 "Non-nil means, keep link in list for entire session.
1225 The command `org-store-link' adds a link pointing to the current
1226 location to an internal list. These links accumulate during a session.
1227 The command `org-insert-link' can be used to insert links into any
1228 Org-mode file (offering completion for all stored links). When this
1229 option is nil, every link which has been inserted once using \\[org-insert-link]
1230 will be removed from the list, to make completing the unused links
1231 more efficient."
1232 :group 'org-link-store
1233 :type 'boolean)
1235 (defcustom org-usenet-links-prefer-google nil
1236 "Non-nil means, `org-store-link' will create web links to Google groups.
1237 When nil, Gnus will be used for such links.
1238 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1239 negates this setting for the duration of the command."
1240 :group 'org-link-store
1241 :type 'boolean)
1243 (defgroup org-link-follow nil
1244 "Options concerning following links in Org-mode"
1245 :tag "Org Follow Link"
1246 :group 'org-link)
1248 (defcustom org-tab-follows-link nil
1249 "Non-nil means, on links TAB will follow the link.
1250 Needs to be set before org.el is loaded."
1251 :group 'org-link-follow
1252 :type 'boolean)
1254 (defcustom org-return-follows-link nil
1255 "Non-nil means, on links RET will follow the link.
1256 Needs to be set before org.el is loaded."
1257 :group 'org-link-follow
1258 :type 'boolean)
1260 (defcustom org-mouse-1-follows-link
1261 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1262 "Non-nil means, mouse-1 on a link will follow the link.
1263 A longer mouse click will still set point. Does not work on XEmacs.
1264 Needs to be set before org.el is loaded."
1265 :group 'org-link-follow
1266 :type 'boolean)
1268 (defcustom org-mark-ring-length 4
1269 "Number of different positions to be recorded in the ring
1270 Changing this requires a restart of Emacs to work correctly."
1271 :group 'org-link-follow
1272 :type 'interger)
1274 (defcustom org-link-frame-setup
1275 '((vm . vm-visit-folder-other-frame)
1276 (gnus . gnus-other-frame)
1277 (file . find-file-other-window))
1278 "Setup the frame configuration for following links.
1279 When following a link with Emacs, it may often be useful to display
1280 this link in another window or frame. This variable can be used to
1281 set this up for the different types of links.
1282 For VM, use any of
1283 `vm-visit-folder'
1284 `vm-visit-folder-other-frame'
1285 For Gnus, use any of
1286 `gnus'
1287 `gnus-other-frame'
1288 For FILE, use any of
1289 `find-file'
1290 `find-file-other-window'
1291 `find-file-other-frame'
1292 For the calendar, use the variable `calendar-setup'.
1293 For BBDB, it is currently only possible to display the matches in
1294 another window."
1295 :group 'org-link-follow
1296 :type '(list
1297 (cons (const vm)
1298 (choice
1299 (const vm-visit-folder)
1300 (const vm-visit-folder-other-window)
1301 (const vm-visit-folder-other-frame)))
1302 (cons (const gnus)
1303 (choice
1304 (const gnus)
1305 (const gnus-other-frame)))
1306 (cons (const file)
1307 (choice
1308 (const find-file)
1309 (const find-file-other-window)
1310 (const find-file-other-frame)))))
1312 (defcustom org-display-internal-link-with-indirect-buffer nil
1313 "Non-nil means, use indirect buffer to display infile links.
1314 Activating internal links (from one location in a file to another location
1315 in the same file) normally just jumps to the location. When the link is
1316 activated with a C-u prefix (or with mouse-3), the link is displayed in
1317 another window. When this option is set, the other window actually displays
1318 an indirect buffer clone of the current buffer, to avoid any visibility
1319 changes to the current buffer."
1320 :group 'org-link-follow
1321 :type 'boolean)
1323 (defcustom org-open-non-existing-files nil
1324 "Non-nil means, `org-open-file' will open non-existing files.
1325 When nil, an error will be generated."
1326 :group 'org-link-follow
1327 :type 'boolean)
1329 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1330 "Function and arguments to call for following mailto links.
1331 This is a list with the first element being a lisp function, and the
1332 remaining elements being arguments to the function. In string arguments,
1333 %a will be replaced by the address, and %s will be replaced by the subject
1334 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1335 :group 'org-link-follow
1336 :type '(choice
1337 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1338 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1339 (const :tag "message-mail" (message-mail "%a" "%s"))
1340 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1342 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1343 "Non-nil means, ask for confirmation before executing shell links.
1344 Shell links can be dangerous: just think about a link
1346 [[shell:rm -rf ~/*][Google Search]]
1348 This link would show up in your Org-mode document as \"Google Search\",
1349 but really it would remove your entire home directory.
1350 Therefore we advise against setting this variable to nil.
1351 Just change it to `y-or-n-p' of you want to confirm with a
1352 single keystroke rather than having to type \"yes\"."
1353 :group 'org-link-follow
1354 :type '(choice
1355 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1356 (const :tag "with y-or-n (faster)" y-or-n-p)
1357 (const :tag "no confirmation (dangerous)" nil)))
1359 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1360 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1361 Elisp links can be dangerous: just think about a link
1363 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1365 This link would show up in your Org-mode document as \"Google Search\",
1366 but really it would remove your entire home directory.
1367 Therefore we advise against setting this variable to nil.
1368 Just change it to `y-or-n-p' of you want to confirm with a
1369 single keystroke rather than having to type \"yes\"."
1370 :group 'org-link-follow
1371 :type '(choice
1372 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1373 (const :tag "with y-or-n (faster)" y-or-n-p)
1374 (const :tag "no confirmation (dangerous)" nil)))
1376 (defconst org-file-apps-defaults-gnu
1377 '((remote . emacs)
1378 (t . mailcap))
1379 "Default file applications on a UNIX or GNU/Linux system.
1380 See `org-file-apps'.")
1382 (defconst org-file-apps-defaults-macosx
1383 '((remote . emacs)
1384 (t . "open %s")
1385 ("ps" . "gv %s")
1386 ("ps.gz" . "gv %s")
1387 ("eps" . "gv %s")
1388 ("eps.gz" . "gv %s")
1389 ("dvi" . "xdvi %s")
1390 ("fig" . "xfig %s"))
1391 "Default file applications on a MacOS X system.
1392 The system \"open\" is known as a default, but we use X11 applications
1393 for some files for which the OS does not have a good default.
1394 See `org-file-apps'.")
1396 (defconst org-file-apps-defaults-windowsnt
1397 (list
1398 '(remote . emacs)
1399 (cons t
1400 (list (if (featurep 'xemacs)
1401 'mswindows-shell-execute
1402 'w32-shell-execute)
1403 "open" 'file)))
1404 "Default file applications on a Windows NT system.
1405 The system \"open\" is used for most files.
1406 See `org-file-apps'.")
1408 (defcustom org-file-apps
1410 ("txt" . emacs)
1411 ("tex" . emacs)
1412 ("ltx" . emacs)
1413 ("org" . emacs)
1414 ("el" . emacs)
1415 ("bib" . emacs)
1417 "External applications for opening `file:path' items in a document.
1418 Org-mode uses system defaults for different file types, but
1419 you can use this variable to set the application for a given file
1420 extension. The entries in this list are cons cells where the car identifies
1421 files and the cdr the corresponding command. Possible values for the
1422 file identifier are
1423 \"ext\" A string identifying an extension
1424 `directory' Matches a directory
1425 `remote' Matches a remote file, accessible through tramp or efs.
1426 Remote files most likely should be visited through Emacs
1427 because external applications cannot handle such paths.
1428 t Default for all remaining files
1430 Possible values for the command are:
1431 `emacs' The file will be visited by the current Emacs process.
1432 `default' Use the default application for this file type.
1433 string A command to be executed by a shell; %s will be replaced
1434 by the path to the file.
1435 sexp A Lisp form which will be evaluated. The file path will
1436 be available in the Lisp variable `file'.
1437 For more examples, see the system specific constants
1438 `org-file-apps-defaults-macosx'
1439 `org-file-apps-defaults-windowsnt'
1440 `org-file-apps-defaults-gnu'."
1441 :group 'org-link-follow
1442 :type '(repeat
1443 (cons (choice :value ""
1444 (string :tag "Extension")
1445 (const :tag "Default for unrecognized files" t)
1446 (const :tag "Remote file" remote)
1447 (const :tag "Links to a directory" directory))
1448 (choice :value ""
1449 (const :tag "Visit with Emacs" emacs)
1450 (const :tag "Use system default" default)
1451 (string :tag "Command")
1452 (sexp :tag "Lisp form")))))
1454 (defcustom org-mhe-search-all-folders nil
1455 "Non-nil means, that the search for the mh-message will be extended to
1456 all folders if the message cannot be found in the folder given in the link.
1457 Searching all folders is very efficient with one of the search engines
1458 supported by MH-E, but will be slow with pick."
1459 :group 'org-link-follow
1460 :type 'boolean)
1462 (defgroup org-remember nil
1463 "Options concerning interaction with remember.el."
1464 :tag "Org Remember"
1465 :group 'org)
1467 (defcustom org-directory "~/org"
1468 "Directory with org files.
1469 This directory will be used as default to prompt for org files.
1470 Used by the hooks for remember.el."
1471 :group 'org-remember
1472 :type 'directory)
1474 (defcustom org-default-notes-file "~/.notes"
1475 "Default target for storing notes.
1476 Used by the hooks for remember.el. This can be a string, or nil to mean
1477 the value of `remember-data-file'.
1478 You can set this on a per-template basis with the variable
1479 `org-remember-templates'."
1480 :group 'org-remember
1481 :type '(choice
1482 (const :tag "Default from remember-data-file" nil)
1483 file))
1485 (defcustom org-remember-store-without-prompt t
1486 "Non-nil means, `C-c C-c' stores remember note without further promts.
1487 In this case, you need `C-u C-c C-c' to get the prompts for
1488 note file and headline.
1489 When this variable is nil, `C-c C-c' give you the prompts, and
1490 `C-u C-c C-c' trigger the fasttrack."
1491 :group 'org-remember
1492 :type 'boolean)
1494 (defcustom org-remember-interactive-interface 'refile
1495 "The interface to be used for interactive filing of remember notes.
1496 This is only used when the interactive mode for selecting a filing
1497 location is used (see the variable `org-remember-store-without-prompt').
1498 Allowed vaues are:
1499 outline The interface shows an outline of the relevant file
1500 and the correct heading is found by moving through
1501 the outline or by searching with incremental search.
1502 outline-path-completion Headlines in the current buffer are offered via
1503 completion.
1504 refile Use the refile interface, and offer headlines,
1505 possibly from different buffers."
1506 :group 'org-remember
1507 :type '(choice
1508 (const :tag "Refile" refile)
1509 (const :tag "Outline" outline)
1510 (const :tag "Outline-path-completion" outline-path-completion)))
1512 (defcustom org-goto-interface 'outline
1513 "The default interface to be used for `org-goto'.
1514 Allowed vaues are:
1515 outline The interface shows an outline of the relevant file
1516 and the correct heading is found by moving through
1517 the outline or by searching with incremental search.
1518 outline-path-completion Headlines in the current buffer are offered via
1519 completion."
1520 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1521 :type '(choice
1522 (const :tag "Outline" outline)
1523 (const :tag "Outline-path-completion" outline-path-completion)))
1525 (defcustom org-remember-default-headline ""
1526 "The headline that should be the default location in the notes file.
1527 When filing remember notes, the cursor will start at that position.
1528 You can set this on a per-template basis with the variable
1529 `org-remember-templates'."
1530 :group 'org-remember
1531 :type 'string)
1533 (defcustom org-remember-templates nil
1534 "Templates for the creation of remember buffers.
1535 When nil, just let remember make the buffer.
1536 When not nil, this is a list of 5-element lists. In each entry, the first
1537 element is the name of the template, which should be a single short word.
1538 The second element is a character, a unique key to select this template.
1539 The third element is the template. The fourth element is optional and can
1540 specify a destination file for remember items created with this template.
1541 The default file is given by `org-default-notes-file'. An optional fifth
1542 element can specify the headline in that file that should be offered
1543 first when the user is asked to file the entry. The default headline is
1544 given in the variable `org-remember-default-headline'.
1546 An optional sixth element can specify the context in which the user should
1547 be able to select this template. If this element is a list of major modes,
1548 the template will only be available while invoking `org-remember' from a
1549 buffer in one of these modes. If it is a function, the template will only
1550 be selected if the function returns `t'. A value of `t' means select
1551 this template in any context. When the element is `nil', the template
1552 will be selected by default, i.e. when all contextual checks failed.
1554 The template specifies the structure of the remember buffer. It should have
1555 a first line starting with a star, to act as the org-mode headline.
1556 Furthermore, the following %-escapes will be replaced with content:
1558 %^{prompt} Prompt the user for a string and replace this sequence with it.
1559 A default value and a completion table ca be specified like this:
1560 %^{prompt|default|completion2|completion3|...}
1561 %t time stamp, date only
1562 %T time stamp with date and time
1563 %u, %U like the above, but inactive time stamps
1564 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1565 You may define a prompt like %^{Please specify birthday}t
1566 %n user name (taken from `user-full-name')
1567 %a annotation, normally the link created with org-store-link
1568 %i initial content, the region active. If %i is indented,
1569 the entire inserted text will be indented as well.
1570 %c content of the clipboard, or current kill ring head
1571 %^g prompt for tags, with completion on tags in target file
1572 %^G prompt for tags, with completion all tags in all agenda files
1573 %:keyword specific information for certain link types, see below
1574 %[pathname] insert the contents of the file given by `pathname'
1575 %(sexp) evaluate elisp `(sexp)' and replace with the result
1576 %! Store this note immediately after filling the template
1578 %? After completing the template, position cursor here.
1580 Apart from these general escapes, you can access information specific to the
1581 link type that is created. For example, calling `remember' in emails or gnus
1582 will record the author and the subject of the message, which you can access
1583 with %:author and %:subject, respectively. Here is a complete list of what
1584 is recorded for each link type.
1586 Link type | Available information
1587 -------------------+------------------------------------------------------
1588 bbdb | %:type %:name %:company
1589 vm, wl, mh, rmail | %:type %:subject %:message-id
1590 | %:from %:fromname %:fromaddress
1591 | %:to %:toname %:toaddress
1592 | %:fromto (either \"to NAME\" or \"from NAME\")
1593 gnus | %:group, for messages also all email fields
1594 w3, w3m | %:type %:url
1595 info | %:type %:file %:node
1596 calendar | %:type %:date"
1597 :group 'org-remember
1598 :get (lambda (var) ; Make sure all entries have at least 5 elements
1599 (mapcar (lambda (x)
1600 (if (not (stringp (car x))) (setq x (cons "" x)))
1601 (cond ((= (length x) 4) (append x '("")))
1602 ((= (length x) 3) (append x '("" "")))
1603 (t x)))
1604 (default-value var)))
1605 :type '(repeat
1606 :tag "enabled"
1607 (list :value ("" ?a "\n" nil nil nil)
1608 (string :tag "Name")
1609 (character :tag "Selection Key")
1610 (string :tag "Template")
1611 (choice
1612 (file :tag "Destination file")
1613 (const :tag "Prompt for file" nil))
1614 (choice
1615 (string :tag "Destination headline")
1616 (const :tag "Selection interface for heading"))
1617 (choice
1618 (const :tag "Use by default" nil)
1619 (const :tag "Use in all contexts" t)
1620 (repeat :tag "Use only if in major mode"
1621 (symbol :tag "Major mode"))
1622 (function :tag "Perform a check against function")))))
1624 (defcustom org-reverse-note-order nil
1625 "Non-nil means, store new notes at the beginning of a file or entry.
1626 When nil, new notes will be filed to the end of a file or entry.
1627 This can also be a list with cons cells of regular expressions that
1628 are matched against file names, and values."
1629 :group 'org-remember
1630 :type '(choice
1631 (const :tag "Reverse always" t)
1632 (const :tag "Reverse never" nil)
1633 (repeat :tag "By file name regexp"
1634 (cons regexp boolean))))
1636 (defcustom org-refile-targets nil
1637 "Targets for refiling entries with \\[org-refile].
1638 This is list of cons cells. Each cell contains:
1639 - a specification of the files to be considered, either a list of files,
1640 or a symbol whose function or value fields will be used to retrieve
1641 a file name or a list of file names. Nil means, refile to a different
1642 heading in the current buffer.
1643 - A specification of how to find candidate refile targets. This may be
1644 any of
1645 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1646 This tag has to be present in all target headlines, inheritance will
1647 not be considered.
1648 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1649 todo keyword.
1650 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1651 headlines that are refiling targets.
1652 - a cons cell (:level . N). Any headline of level N is considered a target.
1653 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1654 ;; FIXME: what if there are a var and func with same name???
1655 :group 'org-remember
1656 :type '(repeat
1657 (cons
1658 (choice :value org-agenda-files
1659 (const :tag "All agenda files" org-agenda-files)
1660 (const :tag "Current buffer" nil)
1661 (function) (variable) (file))
1662 (choice :tag "Identify target headline by"
1663 (cons :tag "Specific tag" (const :tag) (string))
1664 (cons :tag "TODO keyword" (const :todo) (string))
1665 (cons :tag "Regular expression" (const :regexp) (regexp))
1666 (cons :tag "Level number" (const :level) (integer))
1667 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1669 (defcustom org-refile-use-outline-path nil
1670 "Non-nil means, provide refile targets as paths.
1671 So a level 3 headline will be available as level1/level2/level3.
1672 When the value is `file', also include the file name (without directory)
1673 into the path. When `full-file-path', include the full file path."
1674 :group 'org-remember
1675 :type '(choice
1676 (const :tag "Not" nil)
1677 (const :tag "Yes" t)
1678 (const :tag "Start with file name" file)
1679 (const :tag "Start with full file path" full-file-path)))
1681 (defgroup org-todo nil
1682 "Options concerning TODO items in Org-mode."
1683 :tag "Org TODO"
1684 :group 'org)
1686 (defgroup org-progress nil
1687 "Options concerning Progress logging in Org-mode."
1688 :tag "Org Progress"
1689 :group 'org-time)
1691 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1692 "List of TODO entry keyword sequences and their interpretation.
1693 \\<org-mode-map>This is a list of sequences.
1695 Each sequence starts with a symbol, either `sequence' or `type',
1696 indicating if the keywords should be interpreted as a sequence of
1697 action steps, or as different types of TODO items. The first
1698 keywords are states requiring action - these states will select a headline
1699 for inclusion into the global TODO list Org-mode produces. If one of
1700 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1701 signify that no further action is necessary. If \"|\" is not found,
1702 the last keyword is treated as the only DONE state of the sequence.
1704 The command \\[org-todo] cycles an entry through these states, and one
1705 additional state where no keyword is present. For details about this
1706 cycling, see the manual.
1708 TODO keywords and interpretation can also be set on a per-file basis with
1709 the special #+SEQ_TODO and #+TYP_TODO lines.
1711 Each keyword can optionally specify a character for fast state selection
1712 \(in combination with the variable `org-use-fast-todo-selection')
1713 and specifiers for state change logging, using the same syntax
1714 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1715 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1716 indicates to record a time stamp each time this state is selected.
1717 \"WAIT(w@)\" says that the user should in addition be prompted for a
1718 note, and \"WAIT(w@/@)\" says that a note should be taken both when
1719 entering and when leaving this state. The last double-setting is
1720 only a backup, to force a note even if the target state has no
1721 logging configured.
1723 For backward compatibility, this variable may also be just a list
1724 of keywords - in this case the interptetation (sequence or type) will be
1725 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1726 :group 'org-todo
1727 :group 'org-keywords
1728 :type '(choice
1729 (repeat :tag "Old syntax, just keywords"
1730 (string :tag "Keyword"))
1731 (repeat :tag "New syntax"
1732 (cons
1733 (choice
1734 :tag "Interpretation"
1735 (const :tag "Sequence (cycling hits every state)" sequence)
1736 (const :tag "Type (cycling directly to DONE)" type))
1737 (repeat
1738 (string :tag "Keyword"))))))
1740 (defvar org-todo-keywords-1 nil
1741 "All TODO and DONE keywords active in a buffer.")
1742 (make-variable-buffer-local 'org-todo-keywords-1)
1743 (defvar org-todo-keywords-for-agenda nil)
1744 (defvar org-done-keywords-for-agenda nil)
1745 (defvar org-not-done-keywords nil)
1746 (make-variable-buffer-local 'org-not-done-keywords)
1747 (defvar org-done-keywords nil)
1748 (make-variable-buffer-local 'org-done-keywords)
1749 (defvar org-todo-heads nil)
1750 (make-variable-buffer-local 'org-todo-heads)
1751 (defvar org-todo-sets nil)
1752 (make-variable-buffer-local 'org-todo-sets)
1753 (defvar org-todo-log-states nil)
1754 (make-variable-buffer-local 'org-todo-log-states)
1755 (defvar org-todo-kwd-alist nil)
1756 (make-variable-buffer-local 'org-todo-kwd-alist)
1757 (defvar org-todo-key-alist nil)
1758 (make-variable-buffer-local 'org-todo-key-alist)
1759 (defvar org-todo-key-trigger nil)
1760 (make-variable-buffer-local 'org-todo-key-trigger)
1762 (defcustom org-todo-interpretation 'sequence
1763 "Controls how TODO keywords are interpreted.
1764 This variable is in principle obsolete and is only used for
1765 backward compatibility, if the interpretation of todo keywords is
1766 not given already in `org-todo-keywords'. See that variable for
1767 more information."
1768 :group 'org-todo
1769 :group 'org-keywords
1770 :type '(choice (const sequence)
1771 (const type)))
1773 (defcustom org-use-fast-todo-selection 'prefix
1774 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1775 This variable describes if and under what circumstances the cycling
1776 mechanism for TODO keywords will be replaced by a single-key, direct
1777 selection scheme.
1779 When nil, fast selection is never used.
1781 When the symbol `prefix', it will be used when `org-todo' is called with
1782 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1783 in an agenda buffer.
1785 When t, fast selection is used by default. In this case, the prefix
1786 argument forces cycling instead.
1788 In all cases, the special interface is only used if access keys have actually
1789 been assigned by the user, i.e. if keywords in the configuration are followed
1790 by a letter in parenthesis, like TODO(t)."
1791 :group 'org-todo
1792 :type '(choice
1793 (const :tag "Never" nil)
1794 (const :tag "By default" t)
1795 (const :tag "Only with C-u C-c C-t" prefix)))
1797 (defcustom org-after-todo-state-change-hook nil
1798 "Hook which is run after the state of a TODO item was changed.
1799 The new state (a string with a TODO keyword, or nil) is available in the
1800 Lisp variable `state'."
1801 :group 'org-todo
1802 :type 'hook)
1804 (defcustom org-log-done nil
1805 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1806 When equal to the list (done), also prompt for a closing note.
1807 This can also be configured on a per-file basis by adding one of
1808 the following lines anywhere in the buffer:
1810 #+STARTUP: logdone
1811 #+STARTUP: lognotedone
1812 #+STARTUP: nologdone"
1813 :group 'org-todo
1814 :group 'org-progress
1815 :type '(choice
1816 (const :tag "No logging" nil)
1817 (const :tag "Record CLOSED timestamp" time)
1818 (const :tag "Record CLOSED timestamp with closing note." note)))
1820 ;; Normalize old uses of org-log-done.
1821 (cond
1822 ((eq org-log-done t) (setq org-log-done 'time))
1823 ((and (listp org-log-done) (memq 'done org-log-done))
1824 (setq org-log-done 'note)))
1826 ;; FIXME: document
1827 (defcustom org-log-note-clock-out nil
1828 "Non-nil means, recored a note when clocking out of an item.
1829 This can also be configured on a per-file basis by adding one of
1830 the following lines anywhere in the buffer:
1832 #+STARTUP: lognoteclock-out
1833 #+STARTUP: nolognoteclock-out"
1834 :group 'org-todo
1835 :group 'org-progress
1836 :type 'boolean)
1838 (defcustom org-log-done-with-time t
1839 "Non-nil means, the CLOSED time stamp will contain date and time.
1840 When nil, only the date will be recorded."
1841 :group 'org-progress
1842 :type 'boolean)
1844 (defcustom org-log-note-headings
1845 '((done . "CLOSING NOTE %t")
1846 (state . "State %-12s %t")
1847 (clock-out . ""))
1848 "Headings for notes added when clocking out or closing TODO items.
1849 The value is an alist, with the car being a symbol indicating the note
1850 context, and the cdr is the heading to be used. The heading may also be the
1851 empty string.
1852 %t in the heading will be replaced by a time stamp.
1853 %s will be replaced by the new TODO state, in double quotes.
1854 %u will be replaced by the user name.
1855 %U will be replaced by the full user name."
1856 :group 'org-todo
1857 :group 'org-progress
1858 :type '(list :greedy t
1859 (cons (const :tag "Heading when closing an item" done) string)
1860 (cons (const :tag
1861 "Heading when changing todo state (todo sequence only)"
1862 state) string)
1863 (cons (const :tag "Heading when clocking out" clock-out) string)))
1865 (defcustom org-log-states-order-reversed t
1866 "Non-nil means, the latest state change note will be directly after heading.
1867 When nil, the notes will be orderer according to time."
1868 :group 'org-todo
1869 :group 'org-progress
1870 :type 'boolean)
1872 (defcustom org-log-repeat 'time
1873 "Non-nil means, record moving through the DONE state when triggering repeat.
1874 An auto-repeating tasks is immediately switched back to TODO when marked
1875 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1876 the TODO keyword definition, or recording a cloing note by setting
1877 `org-log-done', there will be no record of the task moving trhough DONE.
1878 This variable forces taking a note anyway. Possible values are:
1880 nil Don't force a record
1881 time Record a time stamp
1882 note Record a note
1884 This option can also be set with on a per-file-basis with
1886 #+STARTUP: logrepeat
1887 #+STARTUP: lognoterepeat
1888 #+STARTUP: nologrepeat
1890 You can have local logging settings for a subtree by setting the LOGGING
1891 property to one or more of these keywords."
1892 :group 'org-todo
1893 :group 'org-progress
1894 :type '(choice
1895 (const :tag "Don't force a record" nil)
1896 (const :tag "Force recording the DONE state" time)
1897 (const :tag "Force recording a note with the DONE state" note)))
1899 (defcustom org-clock-into-drawer 2
1900 "Should clocking info be wrapped into a drawer?
1901 When t, clocking info will always be inserted into a :CLOCK: drawer.
1902 If necessary, the drawer will be created.
1903 When nil, the drawer will not be created, but used when present.
1904 When an integer and the number of clocking entries in an item
1905 reaches or exceeds this number, a drawer will be created."
1906 :group 'org-todo
1907 :group 'org-progress
1908 :type '(choice
1909 (const :tag "Always" t)
1910 (const :tag "Only when drawer exists" nil)
1911 (integer :tag "When at least N clock entries")))
1913 (defcustom org-clock-out-when-done t
1914 "When t, the clock will be stopped when the relevant entry is marked DONE.
1915 Nil means, clock will keep running until stopped explicitly with
1916 `C-c C-x C-o', or until the clock is started in a different item."
1917 :group 'org-progress
1918 :type 'boolean)
1920 (defcustom org-clock-in-switch-to-state nil
1921 "Set task to a special todo state while clocking it.
1922 The value should be the state to which the entry should be switched."
1923 :group 'org-progress
1924 :group 'org-todo
1925 :type '(choice
1926 (const :tag "Don't force a state" nil)
1927 (string :tag "State")))
1929 (defgroup org-priorities nil
1930 "Priorities in Org-mode."
1931 :tag "Org Priorities"
1932 :group 'org-todo)
1934 (defcustom org-highest-priority ?A
1935 "The highest priority of TODO items. A character like ?A, ?B etc.
1936 Must have a smaller ASCII number than `org-lowest-priority'."
1937 :group 'org-priorities
1938 :type 'character)
1940 (defcustom org-lowest-priority ?C
1941 "The lowest priority of TODO items. A character like ?A, ?B etc.
1942 Must have a larger ASCII number than `org-highest-priority'."
1943 :group 'org-priorities
1944 :type 'character)
1946 (defcustom org-default-priority ?B
1947 "The default priority of TODO items.
1948 This is the priority an item get if no explicit priority is given."
1949 :group 'org-priorities
1950 :type 'character)
1952 (defcustom org-priority-start-cycle-with-default t
1953 "Non-nil means, start with default priority when starting to cycle.
1954 When this is nil, the first step in the cycle will be (depending on the
1955 command used) one higher or lower that the default priority."
1956 :group 'org-priorities
1957 :type 'boolean)
1959 (defgroup org-time nil
1960 "Options concerning time stamps and deadlines in Org-mode."
1961 :tag "Org Time"
1962 :group 'org)
1964 (defcustom org-insert-labeled-timestamps-at-point nil
1965 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1966 When nil, these labeled time stamps are forces into the second line of an
1967 entry, just after the headline. When scheduling from the global TODO list,
1968 the time stamp will always be forced into the second line."
1969 :group 'org-time
1970 :type 'boolean)
1972 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1973 "Formats for `format-time-string' which are used for time stamps.
1974 It is not recommended to change this constant.")
1976 (defcustom org-time-stamp-rounding-minutes '(0 5)
1977 "Number of minutes to round time stamps to.
1978 These are two values, the first applies when first creating a time stamp.
1979 The second applies when changing it with the commands `S-up' and `S-down'.
1980 When changing the time stamp, this means that it will change in steps
1981 of N minues, as given by the second value.
1983 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1984 numbers should be factors of 60, so for example 5, 10, 15.
1986 When this is larger than 1, you can still force an exact time-stamp by using
1987 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1988 and by using a prefix arg to `S-up/down' to specify the exact number
1989 of minutes to shift."
1990 :group 'org-time
1991 :get '(lambda (var) ; Make sure all entries have 5 elements
1992 (if (integerp (default-value var))
1993 (list (default-value var) 5)
1994 (default-value var)))
1995 :type '(list
1996 (integer :tag "when inserting times")
1997 (integer :tag "when modifying times")))
1999 (defcustom org-display-custom-times nil
2000 "Non-nil means, overlay custom formats over all time stamps.
2001 The formats are defined through the variable `org-time-stamp-custom-formats'.
2002 To turn this on on a per-file basis, insert anywhere in the file:
2003 #+STARTUP: customtime"
2004 :group 'org-time
2005 :set 'set-default
2006 :type 'sexp)
2007 (make-variable-buffer-local 'org-display-custom-times)
2009 (defcustom org-time-stamp-custom-formats
2010 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2011 "Custom formats for time stamps. See `format-time-string' for the syntax.
2012 These are overlayed over the default ISO format if the variable
2013 `org-display-custom-times' is set. Time like %H:%M should be at the
2014 end of the second format."
2015 :group 'org-time
2016 :type 'sexp)
2018 (defun org-time-stamp-format (&optional long inactive)
2019 "Get the right format for a time string."
2020 (let ((f (if long (cdr org-time-stamp-formats)
2021 (car org-time-stamp-formats))))
2022 (if inactive
2023 (concat "[" (substring f 1 -1) "]")
2024 f)))
2026 (defcustom org-read-date-prefer-future t
2027 "Non-nil means, assume future for incomplete date input from user.
2028 This affects the following situations:
2029 1. The user gives a day, but no month.
2030 For example, if today is the 15th, and you enter \"3\", Org-mode will
2031 read this as the third of *next* month. However, if you enter \"17\",
2032 it will be considered as *this* month.
2033 2. The user gives a month but not a year.
2034 For example, if it is april and you enter \"feb 2\", this will be read
2035 as feb 2, *next* year. \"May 5\", however, will be this year.
2037 When this option is nil, the current month and year will always be used
2038 as defaults."
2039 :group 'org-time
2040 :type 'boolean)
2042 (defcustom org-read-date-display-live t
2043 "Non-nil means, display current interpretation of date prompt live.
2044 This display will be in an overlay, in the minibuffer."
2045 :group 'org-time
2046 :type 'boolean)
2048 (defcustom org-read-date-popup-calendar t
2049 "Non-nil means, pop up a calendar when prompting for a date.
2050 In the calendar, the date can be selected with mouse-1. However, the
2051 minibuffer will also be active, and you can simply enter the date as well.
2052 When nil, only the minibuffer will be available."
2053 :group 'org-time
2054 :type 'boolean)
2055 (if (fboundp 'defvaralias)
2056 (defvaralias 'org-popup-calendar-for-date-prompt
2057 'org-read-date-popup-calendar))
2059 (defcustom org-extend-today-until 0
2060 "The hour when your day really ends.
2061 This has influence for the following applications:
2062 - When switching the agenda to \"today\". It it is still earlier than
2063 the time given here, the day recognized as TODAY is actually yesterday.
2064 - When a date is read from the user and it is still before the time given
2065 here, the current date and time will be assumed to be yesterday, 23:59.
2067 FIXME:
2068 IMPORTANT: This is still a very experimental feature, it may disappear
2069 again or it may be extended to mean more things."
2070 :group 'org-time
2071 :type 'number)
2073 (defcustom org-edit-timestamp-down-means-later nil
2074 "Non-nil means, S-down will increase the time in a time stamp.
2075 When nil, S-up will increase."
2076 :group 'org-time
2077 :type 'boolean)
2079 (defcustom org-calendar-follow-timestamp-change t
2080 "Non-nil means, make the calendar window follow timestamp changes.
2081 When a timestamp is modified and the calendar window is visible, it will be
2082 moved to the new date."
2083 :group 'org-time
2084 :type 'boolean)
2086 (defcustom org-clock-heading-function nil
2087 "When non-nil, should be a function to create `org-clock-heading'.
2088 This is the string shown in the mode line when a clock is running.
2089 The function is called with point at the beginning of the headline."
2090 :group 'org-time ; FIXME: Should we have a separate group????
2091 :type 'function)
2093 (defgroup org-tags nil
2094 "Options concerning tags in Org-mode."
2095 :tag "Org Tags"
2096 :group 'org)
2098 (defcustom org-tag-alist nil
2099 "List of tags allowed in Org-mode files.
2100 When this list is nil, Org-mode will base TAG input on what is already in the
2101 buffer.
2102 The value of this variable is an alist, the car of each entry must be a
2103 keyword as a string, the cdr may be a character that is used to select
2104 that tag through the fast-tag-selection interface.
2105 See the manual for details."
2106 :group 'org-tags
2107 :type '(repeat
2108 (choice
2109 (cons (string :tag "Tag name")
2110 (character :tag "Access char"))
2111 (const :tag "Start radio group" (:startgroup))
2112 (const :tag "End radio group" (:endgroup)))))
2114 (defcustom org-use-fast-tag-selection 'auto
2115 "Non-nil means, use fast tag selection scheme.
2116 This is a special interface to select and deselect tags with single keys.
2117 When nil, fast selection is never used.
2118 When the symbol `auto', fast selection is used if and only if selection
2119 characters for tags have been configured, either through the variable
2120 `org-tag-alist' or through a #+TAGS line in the buffer.
2121 When t, fast selection is always used and selection keys are assigned
2122 automatically if necessary."
2123 :group 'org-tags
2124 :type '(choice
2125 (const :tag "Always" t)
2126 (const :tag "Never" nil)
2127 (const :tag "When selection characters are configured" 'auto)))
2129 (defcustom org-fast-tag-selection-single-key nil
2130 "Non-nil means, fast tag selection exits after first change.
2131 When nil, you have to press RET to exit it.
2132 During fast tag selection, you can toggle this flag with `C-c'.
2133 This variable can also have the value `expert'. In this case, the window
2134 displaying the tags menu is not even shown, until you press C-c again."
2135 :group 'org-tags
2136 :type '(choice
2137 (const :tag "No" nil)
2138 (const :tag "Yes" t)
2139 (const :tag "Expert" expert)))
2141 (defvar org-fast-tag-selection-include-todo nil
2142 "Non-nil means, fast tags selection interface will also offer TODO states.
2143 This is an undocumented feature, you should not rely on it.")
2145 (defcustom org-tags-column -80
2146 "The column to which tags should be indented in a headline.
2147 If this number is positive, it specifies the column. If it is negative,
2148 it means that the tags should be flushright to that column. For example,
2149 -80 works well for a normal 80 character screen."
2150 :group 'org-tags
2151 :type 'integer)
2153 (defcustom org-auto-align-tags t
2154 "Non-nil means, realign tags after pro/demotion of TODO state change.
2155 These operations change the length of a headline and therefore shift
2156 the tags around. With this options turned on, after each such operation
2157 the tags are again aligned to `org-tags-column'."
2158 :group 'org-tags
2159 :type 'boolean)
2161 (defcustom org-use-tag-inheritance t
2162 "Non-nil means, tags in levels apply also for sublevels.
2163 When nil, only the tags directly given in a specific line apply there.
2164 If you turn off this option, you very likely want to turn on the
2165 companion option `org-tags-match-list-sublevels'."
2166 :group 'org-tags
2167 :type 'boolean)
2169 (defcustom org-tags-match-list-sublevels nil
2170 "Non-nil means list also sublevels of headlines matching tag search.
2171 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2172 the sublevels of a headline matching a tag search often also match
2173 the same search. Listing all of them can create very long lists.
2174 Setting this variable to nil causes subtrees of a match to be skipped.
2175 This option is off by default, because inheritance in on. If you turn
2176 inheritance off, you very likely want to turn this option on.
2178 As a special case, if the tag search is restricted to TODO items, the
2179 value of this variable is ignored and sublevels are always checked, to
2180 make sure all corresponding TODO items find their way into the list."
2181 :group 'org-tags
2182 :type 'boolean)
2184 (defvar org-tags-history nil
2185 "History of minibuffer reads for tags.")
2186 (defvar org-last-tags-completion-table nil
2187 "The last used completion table for tags.")
2188 (defvar org-after-tags-change-hook nil
2189 "Hook that is run after the tags in a line have changed.")
2191 (defgroup org-properties nil
2192 "Options concerning properties in Org-mode."
2193 :tag "Org Properties"
2194 :group 'org)
2196 (defcustom org-property-format "%-10s %s"
2197 "How property key/value pairs should be formatted by `indent-line'.
2198 When `indent-line' hits a property definition, it will format the line
2199 according to this format, mainly to make sure that the values are
2200 lined-up with respect to each other."
2201 :group 'org-properties
2202 :type 'string)
2204 (defcustom org-use-property-inheritance nil
2205 "Non-nil means, properties apply also for sublevels.
2206 This setting is only relevant during property searches, not when querying
2207 an entry with `org-entry-get'. To retrieve a property with inheritance,
2208 you need to call `org-entry-get' with the inheritance flag.
2209 Turning this on can cause significant overhead when doing a search, so
2210 this is turned off by default.
2211 When nil, only the properties directly given in the current entry count.
2212 The value may also be a list of properties that shouldhave inheritance.
2214 However, note that some special properties use inheritance under special
2215 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2216 and the properties ending in \"_ALL\" when they are used as descriptor
2217 for valid values of a property."
2218 :group 'org-properties
2219 :type '(choice
2220 (const :tag "Not" nil)
2221 (const :tag "Always" nil)
2222 (repeat :tag "Specific properties" (string :tag "Property"))))
2224 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2225 "The default column format, if no other format has been defined.
2226 This variable can be set on the per-file basis by inserting a line
2228 #+COLUMNS: %25ITEM ....."
2229 :group 'org-properties
2230 :type 'string)
2232 (defcustom org-global-properties nil
2233 "List of property/value pairs that can be inherited by any entry.
2234 You can set buffer-local values for this by adding lines like
2236 #+PROPERTY: NAME VALUE"
2237 :group 'org-properties
2238 :type '(repeat
2239 (cons (string :tag "Property")
2240 (string :tag "Value"))))
2242 (defvar org-local-properties nil
2243 "List of property/value pairs that can be inherited by any entry.
2244 Valid for the current buffer.
2245 This variable is populated from #+PROPERTY lines.")
2247 (defgroup org-agenda nil
2248 "Options concerning agenda views in Org-mode."
2249 :tag "Org Agenda"
2250 :group 'org)
2252 (defvar org-category nil
2253 "Variable used by org files to set a category for agenda display.
2254 Such files should use a file variable to set it, for example
2256 # -*- mode: org; org-category: \"ELisp\"
2258 or contain a special line
2260 #+CATEGORY: ELisp
2262 If the file does not specify a category, then file's base name
2263 is used instead.")
2264 (make-variable-buffer-local 'org-category)
2266 (defcustom org-agenda-files nil
2267 "The files to be used for agenda display.
2268 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2269 \\[org-remove-file]. You can also use customize to edit the list.
2271 If an entry is a directory, all files in that directory that are matched by
2272 `org-agenda-file-regexp' will be part of the file list.
2274 If the value of the variable is not a list but a single file name, then
2275 the list of agenda files is actually stored and maintained in that file, one
2276 agenda file per line."
2277 :group 'org-agenda
2278 :type '(choice
2279 (repeat :tag "List of files and directories" file)
2280 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2282 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2283 "Regular expression to match files for `org-agenda-files'.
2284 If any element in the list in that variable contains a directory instead
2285 of a normal file, all files in that directory that are matched by this
2286 regular expression will be included."
2287 :group 'org-agenda
2288 :type 'regexp)
2290 (defcustom org-agenda-skip-unavailable-files nil
2291 "t means to just skip non-reachable files in `org-agenda-files'.
2292 Nil means to remove them, after a query, from the list."
2293 :group 'org-agenda
2294 :type 'boolean)
2296 (defcustom org-agenda-text-search-extra-files nil
2297 "List of extra files to be searched by text search commands.
2298 These files will be search in addition to the agenda files bu the
2299 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2300 Note that these files will only be searched for text search commands,
2301 not for the other agenda views like todo lists, tag earches or the weekly
2302 agenda. This variable is intended to list notes and possibly archive files
2303 that should also be searched by these two commands."
2304 :group 'org-agenda
2305 :type '(repeat file))
2307 (if (fboundp 'defvaralias)
2308 (defvaralias 'org-agenda-multi-occur-extra-files
2309 'org-agenda-text-search-extra-files))
2311 (defcustom org-agenda-confirm-kill 1
2312 "When set, remote killing from the agenda buffer needs confirmation.
2313 When t, a confirmation is always needed. When a number N, confirmation is
2314 only needed when the text to be killed contains more than N non-white lines."
2315 :group 'org-agenda
2316 :type '(choice
2317 (const :tag "Never" nil)
2318 (const :tag "Always" t)
2319 (number :tag "When more than N lines")))
2321 (defcustom org-calendar-to-agenda-key [?c]
2322 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2323 The command `org-calendar-goto-agenda' will be bound to this key. The
2324 default is the character `c' because then `c' can be used to switch back and
2325 forth between agenda and calendar."
2326 :group 'org-agenda
2327 :type 'sexp)
2329 (defcustom org-agenda-compact-blocks nil
2330 "Non-nil means, make the block agenda more compact.
2331 This is done by leaving out unnecessary lines."
2332 :group 'org-agenda
2333 :type nil)
2335 (defgroup org-agenda-export nil
2336 "Options concerning exporting agenda views in Org-mode."
2337 :tag "Org Agenda Export"
2338 :group 'org-agenda)
2340 (defcustom org-agenda-with-colors t
2341 "Non-nil means, use colors in agenda views."
2342 :group 'org-agenda-export
2343 :type 'boolean)
2345 (defcustom org-agenda-exporter-settings nil
2346 "Alist of variable/value pairs that should be active during agenda export.
2347 This is a good place to set uptions for ps-print and for htmlize."
2348 :group 'org-agenda-export
2349 :type '(repeat
2350 (list
2351 (variable)
2352 (sexp :tag "Value"))))
2354 (defcustom org-agenda-export-html-style ""
2355 "The style specification for exported HTML Agenda files.
2356 If this variable contains a string, it will replace the default <style>
2357 section as produced by `htmlize'.
2358 Since there are different ways of setting style information, this variable
2359 needs to contain the full HTML structure to provide a style, including the
2360 surrounding HTML tags. The style specifications should include definitions
2361 the fonts used by the agenda, here is an example:
2363 <style type=\"text/css\">
2364 p { font-weight: normal; color: gray; }
2365 .org-agenda-structure {
2366 font-size: 110%;
2367 color: #003399;
2368 font-weight: 600;
2370 .org-todo {
2371 color: #cc6666;Week-agenda:
2372 font-weight: bold;
2374 .org-done {
2375 color: #339933;
2377 .title { text-align: center; }
2378 .todo, .deadline { color: red; }
2379 .done { color: green; }
2380 </style>
2382 or, if you want to keep the style in a file,
2384 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2386 As the value of this option simply gets inserted into the HTML <head> header,
2387 you can \"misuse\" it to also add other text to the header. However,
2388 <style>...</style> is required, if not present the variable will be ignored."
2389 :group 'org-agenda-export
2390 :group 'org-export-html
2391 :type 'string)
2393 (defgroup org-agenda-custom-commands nil
2394 "Options concerning agenda views in Org-mode."
2395 :tag "Org Agenda Custom Commands"
2396 :group 'org-agenda)
2398 (defcustom org-agenda-custom-commands nil
2399 "Custom commands for the agenda.
2400 These commands will be offered on the splash screen displayed by the
2401 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2403 (key desc type match options files)
2405 key The key (one or more characters as a string) to be associated
2406 with the command.
2407 desc A description of the commend, when omitted or nil, a default
2408 description is built using MATCH.
2409 type The command type, any of the following symbols:
2410 agenda The daily/weekly agenda.
2411 todo Entries with a specific TODO keyword, in all agenda files.
2412 search Entries containing search words entry or headline.
2413 tags Tags/Property/TODO match in all agenda files.
2414 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2415 todo-tree Sparse tree of specific TODO keyword in *current* file.
2416 tags-tree Sparse tree with all tags matches in *current* file.
2417 occur-tree Occur sparse tree for *current* file.
2418 ... A user-defined function.
2419 match What to search for:
2420 - a single keyword for TODO keyword searches
2421 - a tags match expression for tags searches
2422 - a regular expression for occur searches
2423 options A list of option settings, similar to that in a let form, so like
2424 this: ((opt1 val1) (opt2 val2) ...)
2425 files A list of files file to write the produced agenda buffer to
2426 with the command `org-store-agenda-views'.
2427 If a file name ends in \".html\", an HTML version of the buffer
2428 is written out. If it ends in \".ps\", a postscript version is
2429 produced. Otherwide, only the plain text is written to the file.
2431 You can also define a set of commands, to create a composite agenda buffer.
2432 In this case, an entry looks like this:
2434 (key desc (cmd1 cmd2 ...) general-options file)
2436 where
2438 desc A description string to be displayed in the dispatcher menu.
2439 cmd An agenda command, similar to the above. However, tree commands
2440 are no allowed, but instead you can get agenda and global todo list.
2441 So valid commands for a set are:
2442 (agenda)
2443 (alltodo)
2444 (stuck)
2445 (todo \"match\" options files)
2446 (search \"match\" options files)
2447 (tags \"match\" options files)
2448 (tags-todo \"match\" options files)
2450 Each command can carry a list of options, and another set of options can be
2451 given for the whole set of commands. Individual command options take
2452 precedence over the general options.
2454 When using several characters as key to a command, the first characters
2455 are prefix commands. For the dispatcher to display useful information, you
2456 should provide a description for the prefix, like
2458 (setq org-agenda-custom-commands
2459 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2460 (\"hl\" tags \"+HOME+Lisa\")
2461 (\"hp\" tags \"+HOME+Peter\")
2462 (\"hk\" tags \"+HOME+Kim\")))"
2463 :group 'org-agenda-custom-commands
2464 :type '(repeat
2465 (choice :value ("a" "" tags "" nil)
2466 (list :tag "Single command"
2467 (string :tag "Access Key(s) ")
2468 (option (string :tag "Description"))
2469 (choice
2470 (const :tag "Agenda" agenda)
2471 (const :tag "TODO list" alltodo)
2472 (const :tag "Search words" search)
2473 (const :tag "Stuck projects" stuck)
2474 (const :tag "Tags search (all agenda files)" tags)
2475 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2476 (const :tag "TODO keyword search (all agenda files)" todo)
2477 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2478 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2479 (const :tag "Occur tree (current buffer)" occur-tree)
2480 (sexp :tag "Other, user-defined function"))
2481 (string :tag "Match")
2482 (repeat :tag "Local options"
2483 (list (variable :tag "Option") (sexp :tag "Value")))
2484 (option (repeat :tag "Export" (file :tag "Export to"))))
2485 (list :tag "Command series, all agenda files"
2486 (string :tag "Access Key(s)")
2487 (string :tag "Description ")
2488 (repeat
2489 (choice
2490 (const :tag "Agenda" (agenda))
2491 (const :tag "TODO list" (alltodo))
2492 (list :tag "Search words"
2493 (const :format "" search)
2494 (string :tag "Match")
2495 (repeat :tag "Local options"
2496 (list (variable :tag "Option")
2497 (sexp :tag "Value"))))
2498 (const :tag "Stuck projects" (stuck))
2499 (list :tag "Tags search"
2500 (const :format "" tags)
2501 (string :tag "Match")
2502 (repeat :tag "Local options"
2503 (list (variable :tag "Option")
2504 (sexp :tag "Value"))))
2506 (list :tag "Tags search, TODO entries only"
2507 (const :format "" tags-todo)
2508 (string :tag "Match")
2509 (repeat :tag "Local options"
2510 (list (variable :tag "Option")
2511 (sexp :tag "Value"))))
2513 (list :tag "TODO keyword search"
2514 (const :format "" todo)
2515 (string :tag "Match")
2516 (repeat :tag "Local options"
2517 (list (variable :tag "Option")
2518 (sexp :tag "Value"))))
2520 (list :tag "Other, user-defined function"
2521 (symbol :tag "function")
2522 (string :tag "Match")
2523 (repeat :tag "Local options"
2524 (list (variable :tag "Option")
2525 (sexp :tag "Value"))))))
2527 (repeat :tag "General options"
2528 (list (variable :tag "Option")
2529 (sexp :tag "Value")))
2530 (option (repeat :tag "Export" (file :tag "Export to"))))
2531 (cons :tag "Prefix key documentation"
2532 (string :tag "Access Key(s)")
2533 (string :tag "Description ")))))
2535 (defcustom org-agenda-query-register ?o
2536 "The register holding the current query string.
2537 The prupose of this is that if you construct a query string interactively,
2538 you can then use it to define a custom command."
2539 :group 'org-agenda-custom-commands
2540 :type 'character)
2542 (defcustom org-stuck-projects
2543 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2544 "How to identify stuck projects.
2545 This is a list of four items:
2546 1. A tags/todo matcher string that is used to identify a project.
2547 The entire tree below a headline matched by this is considered one project.
2548 2. A list of TODO keywords identifying non-stuck projects.
2549 If the project subtree contains any headline with one of these todo
2550 keywords, the project is considered to be not stuck. If you specify
2551 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2552 3. A list of tags identifying non-stuck projects.
2553 If the project subtree contains any headline with one of these tags,
2554 the project is considered to be not stuck. If you specify \"*\" as
2555 a tag, any tag will mark the project unstuck.
2556 4. An arbitrary regular expression matching non-stuck projects.
2558 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2559 or `C-c a #' to produce the list."
2560 :group 'org-agenda-custom-commands
2561 :type '(list
2562 (string :tag "Tags/TODO match to identify a project")
2563 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2564 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2565 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2568 (defgroup org-agenda-skip nil
2569 "Options concerning skipping parts of agenda files."
2570 :tag "Org Agenda Skip"
2571 :group 'org-agenda)
2573 (defcustom org-agenda-todo-list-sublevels t
2574 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2575 When nil, the sublevels of a TODO entry are not checked, resulting in
2576 potentially much shorter TODO lists."
2577 :group 'org-agenda-skip
2578 :group 'org-todo
2579 :type 'boolean)
2581 (defcustom org-agenda-todo-ignore-with-date nil
2582 "Non-nil means, don't show entries with a date in the global todo list.
2583 You can use this if you prefer to mark mere appointments with a TODO keyword,
2584 but don't want them to show up in the TODO list.
2585 When this is set, it also covers deadlines and scheduled items, the settings
2586 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2587 will be ignored."
2588 :group 'org-agenda-skip
2589 :group 'org-todo
2590 :type 'boolean)
2592 (defcustom org-agenda-todo-ignore-scheduled nil
2593 "Non-nil means, don't show scheduled entries in the global todo list.
2594 The idea behind this is that by scheduling it, you have already taken care
2595 of this item.
2596 See also `org-agenda-todo-ignore-with-date'."
2597 :group 'org-agenda-skip
2598 :group 'org-todo
2599 :type 'boolean)
2601 (defcustom org-agenda-todo-ignore-deadlines nil
2602 "Non-nil means, don't show near deadline entries in the global todo list.
2603 Near means closer than `org-deadline-warning-days' days.
2604 The idea behind this is that such items will appear in the agenda anyway.
2605 See also `org-agenda-todo-ignore-with-date'."
2606 :group 'org-agenda-skip
2607 :group 'org-todo
2608 :type 'boolean)
2610 (defcustom org-agenda-skip-scheduled-if-done nil
2611 "Non-nil means don't show scheduled items in agenda when they are done.
2612 This is relevant for the daily/weekly agenda, not for the TODO list. And
2613 it applies only to the actual date of the scheduling. Warnings about
2614 an item with a past scheduling dates are always turned off when the item
2615 is DONE."
2616 :group 'org-agenda-skip
2617 :type 'boolean)
2619 (defcustom org-agenda-skip-deadline-if-done nil
2620 "Non-nil means don't show deadines when the corresponding item is done.
2621 When nil, the deadline is still shown and should give you a happy feeling.
2622 This is relevant for the daily/weekly agenda. And it applied only to the
2623 actualy date of the deadline. Warnings about approching and past-due
2624 deadlines are always turned off when the item is DONE."
2625 :group 'org-agenda-skip
2626 :type 'boolean)
2628 (defcustom org-agenda-skip-timestamp-if-done nil
2629 "Non-nil means don't select item by timestamp or -range if it is DONE."
2630 :group 'org-agenda-skip
2631 :type 'boolean)
2633 (defcustom org-timeline-show-empty-dates 3
2634 "Non-nil means, `org-timeline' also shows dates without an entry.
2635 When nil, only the days which actually have entries are shown.
2636 When t, all days between the first and the last date are shown.
2637 When an integer, show also empty dates, but if there is a gap of more than
2638 N days, just insert a special line indicating the size of the gap."
2639 :group 'org-agenda-skip
2640 :type '(choice
2641 (const :tag "None" nil)
2642 (const :tag "All" t)
2643 (number :tag "at most")))
2646 (defgroup org-agenda-startup nil
2647 "Options concerning initial settings in the Agenda in Org Mode."
2648 :tag "Org Agenda Startup"
2649 :group 'org-agenda)
2651 (defcustom org-finalize-agenda-hook nil
2652 "Hook run just before displaying an agenda buffer."
2653 :group 'org-agenda-startup
2654 :type 'hook)
2656 (defcustom org-agenda-mouse-1-follows-link nil
2657 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2658 A longer mouse click will still set point. Does not work on XEmacs.
2659 Needs to be set before org.el is loaded."
2660 :group 'org-agenda-startup
2661 :type 'boolean)
2663 (defcustom org-agenda-start-with-follow-mode nil
2664 "The initial value of follow-mode in a newly created agenda window."
2665 :group 'org-agenda-startup
2666 :type 'boolean)
2668 (defgroup org-agenda-windows nil
2669 "Options concerning the windows used by the Agenda in Org Mode."
2670 :tag "Org Agenda Windows"
2671 :group 'org-agenda)
2673 (defcustom org-agenda-window-setup 'reorganize-frame
2674 "How the agenda buffer should be displayed.
2675 Possible values for this option are:
2677 current-window Show agenda in the current window, keeping all other windows.
2678 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2679 other-window Use `switch-to-buffer-other-window' to display agenda.
2680 reorganize-frame Show only two windows on the current frame, the current
2681 window and the agenda.
2682 See also the variable `org-agenda-restore-windows-after-quit'."
2683 :group 'org-agenda-windows
2684 :type '(choice
2685 (const current-window)
2686 (const other-frame)
2687 (const other-window)
2688 (const reorganize-frame)))
2690 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2691 "The min and max height of the agenda window as a fraction of frame height.
2692 The value of the variable is a cons cell with two numbers between 0 and 1.
2693 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2694 :group 'org-agenda-windows
2695 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2697 (defcustom org-agenda-restore-windows-after-quit nil
2698 "Non-nil means, restore window configuration open exiting agenda.
2699 Before the window configuration is changed for displaying the agenda,
2700 the current status is recorded. When the agenda is exited with
2701 `q' or `x' and this option is set, the old state is restored. If
2702 `org-agenda-window-setup' is `other-frame', the value of this
2703 option will be ignored.."
2704 :group 'org-agenda-windows
2705 :type 'boolean)
2707 (defcustom org-indirect-buffer-display 'other-window
2708 "How should indirect tree buffers be displayed?
2709 This applies to indirect buffers created with the commands
2710 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2711 Valid values are:
2712 current-window Display in the current window
2713 other-window Just display in another window.
2714 dedicated-frame Create one new frame, and re-use it each time.
2715 new-frame Make a new frame each time. Note that in this case
2716 previously-made indirect buffers are kept, and you need to
2717 kill these buffers yourself."
2718 :group 'org-structure
2719 :group 'org-agenda-windows
2720 :type '(choice
2721 (const :tag "In current window" current-window)
2722 (const :tag "In current frame, other window" other-window)
2723 (const :tag "Each time a new frame" new-frame)
2724 (const :tag "One dedicated frame" dedicated-frame)))
2726 (defgroup org-agenda-daily/weekly nil
2727 "Options concerning the daily/weekly agenda."
2728 :tag "Org Agenda Daily/Weekly"
2729 :group 'org-agenda)
2731 (defcustom org-agenda-ndays 7
2732 "Number of days to include in overview display.
2733 Should be 1 or 7."
2734 :group 'org-agenda-daily/weekly
2735 :type 'number)
2737 (defcustom org-agenda-start-on-weekday 1
2738 "Non-nil means, start the overview always on the specified weekday.
2739 0 denotes Sunday, 1 denotes Monday etc.
2740 When nil, always start on the current day."
2741 :group 'org-agenda-daily/weekly
2742 :type '(choice (const :tag "Today" nil)
2743 (number :tag "Weekday No.")))
2745 (defcustom org-agenda-show-all-dates t
2746 "Non-nil means, `org-agenda' shows every day in the selected range.
2747 When nil, only the days which actually have entries are shown."
2748 :group 'org-agenda-daily/weekly
2749 :type 'boolean)
2751 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2752 "Format string for displaying dates in the agenda.
2753 Used by the daily/weekly agenda and by the timeline. This should be
2754 a format string understood by `format-time-string', or a function returning
2755 the formatted date as a string. The function must take a single argument,
2756 a calendar-style date list like (month day year)."
2757 :group 'org-agenda-daily/weekly
2758 :type '(choice
2759 (string :tag "Format string")
2760 (function :tag "Function")))
2762 (defun org-agenda-format-date-aligned (date)
2763 "Format a date string for display in the daily/weekly agenda, or timeline.
2764 This function makes sure that dates are aligned for easy reading."
2765 (format "%-9s %2d %s %4d"
2766 (calendar-day-name date)
2767 (extract-calendar-day date)
2768 (calendar-month-name (extract-calendar-month date))
2769 (extract-calendar-year date)))
2771 (defcustom org-agenda-include-diary nil
2772 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2773 :group 'org-agenda-daily/weekly
2774 :type 'boolean)
2776 (defcustom org-agenda-include-all-todo nil
2777 "Set means weekly/daily agenda will always contain all TODO entries.
2778 The TODO entries will be listed at the top of the agenda, before
2779 the entries for specific days."
2780 :group 'org-agenda-daily/weekly
2781 :type 'boolean)
2783 (defcustom org-agenda-repeating-timestamp-show-all t
2784 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2785 When nil, only one occurence is shown, either today or the
2786 nearest into the future."
2787 :group 'org-agenda-daily/weekly
2788 :type 'boolean)
2790 (defcustom org-deadline-warning-days 14
2791 "No. of days before expiration during which a deadline becomes active.
2792 This variable governs the display in sparse trees and in the agenda.
2793 When 0 or negative, it means use this number (the absolute value of it)
2794 even if a deadline has a different individual lead time specified."
2795 :group 'org-time
2796 :group 'org-agenda-daily/weekly
2797 :type 'number)
2799 (defcustom org-scheduled-past-days 10000
2800 "No. of days to continue listing scheduled items that are not marked DONE.
2801 When an item is scheduled on a date, it shows up in the agenda on this
2802 day and will be listed until it is marked done for the number of days
2803 given here."
2804 :group 'org-agenda-daily/weekly
2805 :type 'number)
2807 (defgroup org-agenda-time-grid nil
2808 "Options concerning the time grid in the Org-mode Agenda."
2809 :tag "Org Agenda Time Grid"
2810 :group 'org-agenda)
2812 (defcustom org-agenda-use-time-grid t
2813 "Non-nil means, show a time grid in the agenda schedule.
2814 A time grid is a set of lines for specific times (like every two hours between
2815 8:00 and 20:00). The items scheduled for a day at specific times are
2816 sorted in between these lines.
2817 For details about when the grid will be shown, and what it will look like, see
2818 the variable `org-agenda-time-grid'."
2819 :group 'org-agenda-time-grid
2820 :type 'boolean)
2822 (defcustom org-agenda-time-grid
2823 '((daily today require-timed)
2824 "----------------"
2825 (800 1000 1200 1400 1600 1800 2000))
2827 "The settings for time grid for agenda display.
2828 This is a list of three items. The first item is again a list. It contains
2829 symbols specifying conditions when the grid should be displayed:
2831 daily if the agenda shows a single day
2832 weekly if the agenda shows an entire week
2833 today show grid on current date, independent of daily/weekly display
2834 require-timed show grid only if at least one item has a time specification
2836 The second item is a string which will be places behing the grid time.
2838 The third item is a list of integers, indicating the times that should have
2839 a grid line."
2840 :group 'org-agenda-time-grid
2841 :type
2842 '(list
2843 (set :greedy t :tag "Grid Display Options"
2844 (const :tag "Show grid in single day agenda display" daily)
2845 (const :tag "Show grid in weekly agenda display" weekly)
2846 (const :tag "Always show grid for today" today)
2847 (const :tag "Show grid only if any timed entries are present"
2848 require-timed)
2849 (const :tag "Skip grid times already present in an entry"
2850 remove-match))
2851 (string :tag "Grid String")
2852 (repeat :tag "Grid Times" (integer :tag "Time"))))
2854 (defgroup org-agenda-sorting nil
2855 "Options concerning sorting in the Org-mode Agenda."
2856 :tag "Org Agenda Sorting"
2857 :group 'org-agenda)
2859 (defconst org-sorting-choice
2860 '(choice
2861 (const time-up) (const time-down)
2862 (const category-keep) (const category-up) (const category-down)
2863 (const tag-down) (const tag-up)
2864 (const priority-up) (const priority-down))
2865 "Sorting choices.")
2867 (defcustom org-agenda-sorting-strategy
2868 '((agenda time-up category-keep priority-down)
2869 (todo category-keep priority-down)
2870 (tags category-keep priority-down)
2871 (search category-keep))
2872 "Sorting structure for the agenda items of a single day.
2873 This is a list of symbols which will be used in sequence to determine
2874 if an entry should be listed before another entry. The following
2875 symbols are recognized:
2877 time-up Put entries with time-of-day indications first, early first
2878 time-down Put entries with time-of-day indications first, late first
2879 category-keep Keep the default order of categories, corresponding to the
2880 sequence in `org-agenda-files'.
2881 category-up Sort alphabetically by category, A-Z.
2882 category-down Sort alphabetically by category, Z-A.
2883 tag-up Sort alphabetically by last tag, A-Z.
2884 tag-down Sort alphabetically by last tag, Z-A.
2885 priority-up Sort numerically by priority, high priority last.
2886 priority-down Sort numerically by priority, high priority first.
2888 The different possibilities will be tried in sequence, and testing stops
2889 if one comparison returns a \"not-equal\". For example, the default
2890 '(time-up category-keep priority-down)
2891 means: Pull out all entries having a specified time of day and sort them,
2892 in order to make a time schedule for the current day the first thing in the
2893 agenda listing for the day. Of the entries without a time indication, keep
2894 the grouped in categories, don't sort the categories, but keep them in
2895 the sequence given in `org-agenda-files'. Within each category sort by
2896 priority.
2898 Leaving out `category-keep' would mean that items will be sorted across
2899 categories by priority.
2901 Instead of a single list, this can also be a set of list for specific
2902 contents, with a context symbol in the car of the list, any of
2903 `agenda', `todo', `tags' for the corresponding agenda views."
2904 :group 'org-agenda-sorting
2905 :type `(choice
2906 (repeat :tag "General" ,org-sorting-choice)
2907 (list :tag "Individually"
2908 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2909 (repeat ,org-sorting-choice))
2910 (cons (const :tag "Strategy for TODO lists" todo)
2911 (repeat ,org-sorting-choice))
2912 (cons (const :tag "Strategy for Tags matches" tags)
2913 (repeat ,org-sorting-choice)))))
2915 (defcustom org-sort-agenda-notime-is-late t
2916 "Non-nil means, items without time are considered late.
2917 This is only relevant for sorting. When t, items which have no explicit
2918 time like 15:30 will be considered as 99:01, i.e. later than any items which
2919 do have a time. When nil, the default time is before 0:00. You can use this
2920 option to decide if the schedule for today should come before or after timeless
2921 agenda entries."
2922 :group 'org-agenda-sorting
2923 :type 'boolean)
2925 (defgroup org-agenda-line-format nil
2926 "Options concerning the entry prefix in the Org-mode agenda display."
2927 :tag "Org Agenda Line Format"
2928 :group 'org-agenda)
2930 (defcustom org-agenda-prefix-format
2931 '((agenda . " %-12:c%?-12t% s")
2932 (timeline . " % s")
2933 (todo . " %-12:c")
2934 (tags . " %-12:c")
2935 (search . " %-12:c"))
2936 "Format specifications for the prefix of items in the agenda views.
2937 An alist with four entries, for the different agenda types. The keys to the
2938 sublists are `agenda', `timeline', `todo', and `tags'. The values
2939 are format strings.
2940 This format works similar to a printf format, with the following meaning:
2942 %c the category of the item, \"Diary\" for entries from the diary, or
2943 as given by the CATEGORY keyword or derived from the file name.
2944 %T the *last* tag of the item. Last because inherited tags come
2945 first in the list.
2946 %t the time-of-day specification if one applies to the entry, in the
2947 format HH:MM
2948 %s Scheduling/Deadline information, a short string
2950 All specifiers work basically like the standard `%s' of printf, but may
2951 contain two additional characters: A question mark just after the `%' and
2952 a whitespace/punctuation character just before the final letter.
2954 If the first character after `%' is a question mark, the entire field
2955 will only be included if the corresponding value applies to the
2956 current entry. This is useful for fields which should have fixed
2957 width when present, but zero width when absent. For example,
2958 \"%?-12t\" will result in a 12 character time field if a time of the
2959 day is specified, but will completely disappear in entries which do
2960 not contain a time.
2962 If there is punctuation or whitespace character just before the final
2963 format letter, this character will be appended to the field value if
2964 the value is not empty. For example, the format \"%-12:c\" leads to
2965 \"Diary: \" if the category is \"Diary\". If the category were be
2966 empty, no additional colon would be interted.
2968 The default value of this option is \" %-12:c%?-12t% s\", meaning:
2969 - Indent the line with two space characters
2970 - Give the category in a 12 chars wide field, padded with whitespace on
2971 the right (because of `-'). Append a colon if there is a category
2972 (because of `:').
2973 - If there is a time-of-day, put it into a 12 chars wide field. If no
2974 time, don't put in an empty field, just skip it (because of '?').
2975 - Finally, put the scheduling information and append a whitespace.
2977 As another example, if you don't want the time-of-day of entries in
2978 the prefix, you could use:
2980 (setq org-agenda-prefix-format \" %-11:c% s\")
2982 See also the variables `org-agenda-remove-times-when-in-prefix' and
2983 `org-agenda-remove-tags'."
2984 :type '(choice
2985 (string :tag "General format")
2986 (list :greedy t :tag "View dependent"
2987 (cons (const agenda) (string :tag "Format"))
2988 (cons (const timeline) (string :tag "Format"))
2989 (cons (const todo) (string :tag "Format"))
2990 (cons (const tags) (string :tag "Format"))
2991 (cons (const search) (string :tag "Format"))))
2992 :group 'org-agenda-line-format)
2994 (defvar org-prefix-format-compiled nil
2995 "The compiled version of the most recently used prefix format.
2996 See the variable `org-agenda-prefix-format'.")
2998 (defcustom org-agenda-todo-keyword-format "%-1s"
2999 "Format for the TODO keyword in agenda lines.
3000 Set this to something like \"%-12s\" if you want all TODO keywords
3001 to occupy a fixed space in the agenda display."
3002 :group 'org-agenda-line-format
3003 :type 'string)
3005 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3006 "Text preceeding scheduled items in the agenda view.
3007 This is a list with two strings. The first applies when the item is
3008 scheduled on the current day. The second applies when it has been scheduled
3009 previously, it may contain a %d to capture how many days ago the item was
3010 scheduled."
3011 :group 'org-agenda-line-format
3012 :type '(list
3013 (string :tag "Scheduled today ")
3014 (string :tag "Scheduled previously")))
3016 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3017 "Text preceeding deadline items in the agenda view.
3018 This is a list with two strings. The first applies when the item has its
3019 deadline on the current day. The second applies when it is in the past or
3020 in the future, it may contain %d to capture how many days away the deadline
3021 is (was)."
3022 :group 'org-agenda-line-format
3023 :type '(list
3024 (string :tag "Deadline today ")
3025 (string :tag "Deadline relative")))
3027 (defcustom org-agenda-remove-times-when-in-prefix t
3028 "Non-nil means, remove duplicate time specifications in agenda items.
3029 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3030 time-of-day specification in a headline or diary entry is extracted and
3031 placed into the prefix. If this option is non-nil, the original specification
3032 \(a timestamp or -range, or just a plain time(range) specification like
3033 11:30-4pm) will be removed for agenda display. This makes the agenda less
3034 cluttered.
3035 The option can be t or nil. It may also be the symbol `beg', indicating
3036 that the time should only be removed what it is located at the beginning of
3037 the headline/diary entry."
3038 :group 'org-agenda-line-format
3039 :type '(choice
3040 (const :tag "Always" t)
3041 (const :tag "Never" nil)
3042 (const :tag "When at beginning of entry" beg)))
3045 (defcustom org-agenda-default-appointment-duration nil
3046 "Default duration for appointments that only have a starting time.
3047 When nil, no duration is specified in such cases.
3048 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3049 :group 'org-agenda-line-format
3050 :type '(choice
3051 (integer :tag "Minutes")
3052 (const :tag "No default duration")))
3055 (defcustom org-agenda-remove-tags nil
3056 "Non-nil means, remove the tags from the headline copy in the agenda.
3057 When this is the symbol `prefix', only remove tags when
3058 `org-agenda-prefix-format' contains a `%T' specifier."
3059 :group 'org-agenda-line-format
3060 :type '(choice
3061 (const :tag "Always" t)
3062 (const :tag "Never" nil)
3063 (const :tag "When prefix format contains %T" prefix)))
3065 (if (fboundp 'defvaralias)
3066 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3067 'org-agenda-remove-tags))
3069 (defcustom org-agenda-tags-column -80
3070 "Shift tags in agenda items to this column.
3071 If this number is positive, it specifies the column. If it is negative,
3072 it means that the tags should be flushright to that column. For example,
3073 -80 works well for a normal 80 character screen."
3074 :group 'org-agenda-line-format
3075 :type 'integer)
3077 (if (fboundp 'defvaralias)
3078 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3080 (defcustom org-agenda-fontify-priorities t
3081 "Non-nil means, highlight low and high priorities in agenda.
3082 When t, the highest priority entries are bold, lowest priority italic.
3083 This may also be an association list of priority faces. The face may be
3084 a names face, or a list like `(:background \"Red\")'."
3085 :group 'org-agenda-line-format
3086 :type '(choice
3087 (const :tag "Never" nil)
3088 (const :tag "Defaults" t)
3089 (repeat :tag "Specify"
3090 (list (character :tag "Priority" :value ?A)
3091 (sexp :tag "face")))))
3093 (defgroup org-latex nil
3094 "Options for embedding LaTeX code into Org-mode"
3095 :tag "Org LaTeX"
3096 :group 'org)
3098 (defcustom org-format-latex-options
3099 '(:foreground default :background default :scale 1.0
3100 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3101 :matchers ("begin" "$" "$$" "\\(" "\\["))
3102 "Options for creating images from LaTeX fragments.
3103 This is a property list with the following properties:
3104 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3105 `default' means use the forground of the default face.
3106 :background the background color, or \"Transparent\".
3107 `default' means use the background of the default face.
3108 :scale a scaling factor for the size of the images
3109 :html-foreground, :html-background, :html-scale
3110 The same numbers for HTML export.
3111 :matchers a list indicating which matchers should be used to
3112 find LaTeX fragments. Valid members of this list are:
3113 \"begin\" find environments
3114 \"$\" find math expressions surrounded by $...$
3115 \"$$\" find math expressions surrounded by $$....$$
3116 \"\\(\" find math expressions surrounded by \\(...\\)
3117 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3118 :group 'org-latex
3119 :type 'plist)
3121 (defcustom org-format-latex-header "\\documentclass{article}
3122 \\usepackage{fullpage} % do not remove
3123 \\usepackage{amssymb}
3124 \\usepackage[usenames]{color}
3125 \\usepackage{amsmath}
3126 \\usepackage{latexsym}
3127 \\usepackage[mathscr]{eucal}
3128 \\pagestyle{empty} % do not remove"
3129 "The document header used for processing LaTeX fragments."
3130 :group 'org-latex
3131 :type 'string)
3133 (defgroup org-export nil
3134 "Options for exporting org-listings."
3135 :tag "Org Export"
3136 :group 'org)
3138 (defgroup org-export-general nil
3139 "General options for exporting Org-mode files."
3140 :tag "Org Export General"
3141 :group 'org-export)
3143 ;; FIXME
3144 (defvar org-export-publishing-directory nil)
3146 (defcustom org-export-with-special-strings t
3147 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3148 When this option is turned on, these strings will be exported as:
3150 Org HTML LaTeX
3151 -----+----------+--------
3152 \\- &shy; \\-
3153 -- &ndash; --
3154 --- &mdash; ---
3155 ... &hellip; \ldots
3157 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3158 :group 'org-export-translation
3159 :type 'boolean)
3161 (defcustom org-export-language-setup
3162 '(("en" "Author" "Date" "Table of Contents")
3163 ("cs" "Autor" "Datum" "Obsah")
3164 ("da" "Ophavsmand" "Dato" "Indhold")
3165 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3166 ("es" "Autor" "Fecha" "\xcdndice")
3167 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3168 ("it" "Autore" "Data" "Indice")
3169 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3170 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3171 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3172 "Terms used in export text, translated to different languages.
3173 Use the variable `org-export-default-language' to set the language,
3174 or use the +OPTION lines for a per-file setting."
3175 :group 'org-export-general
3176 :type '(repeat
3177 (list
3178 (string :tag "HTML language tag")
3179 (string :tag "Author")
3180 (string :tag "Date")
3181 (string :tag "Table of Contents"))))
3183 (defcustom org-export-default-language "en"
3184 "The default language of HTML export, as a string.
3185 This should have an association in `org-export-language-setup'."
3186 :group 'org-export-general
3187 :type 'string)
3189 (defcustom org-export-skip-text-before-1st-heading t
3190 "Non-nil means, skip all text before the first headline when exporting.
3191 When nil, that text is exported as well."
3192 :group 'org-export-general
3193 :type 'boolean)
3195 (defcustom org-export-headline-levels 3
3196 "The last level which is still exported as a headline.
3197 Inferior levels will produce itemize lists when exported.
3198 Note that a numeric prefix argument to an exporter function overrides
3199 this setting.
3201 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3202 :group 'org-export-general
3203 :type 'number)
3205 (defcustom org-export-with-section-numbers t
3206 "Non-nil means, add section numbers to headlines when exporting.
3208 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3209 :group 'org-export-general
3210 :type 'boolean)
3212 (defcustom org-export-with-toc t
3213 "Non-nil means, create a table of contents in exported files.
3214 The TOC contains headlines with levels up to`org-export-headline-levels'.
3215 When an integer, include levels up to N in the toc, this may then be
3216 different from `org-export-headline-levels', but it will not be allowed
3217 to be larger than the number of headline levels.
3218 When nil, no table of contents is made.
3220 Headlines which contain any TODO items will be marked with \"(*)\" in
3221 ASCII export, and with red color in HTML output, if the option
3222 `org-export-mark-todo-in-toc' is set.
3224 In HTML output, the TOC will be clickable.
3226 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3227 or \"toc:3\"."
3228 :group 'org-export-general
3229 :type '(choice
3230 (const :tag "No Table of Contents" nil)
3231 (const :tag "Full Table of Contents" t)
3232 (integer :tag "TOC to level")))
3234 (defcustom org-export-mark-todo-in-toc nil
3235 "Non-nil means, mark TOC lines that contain any open TODO items."
3236 :group 'org-export-general
3237 :type 'boolean)
3239 (defcustom org-export-preserve-breaks nil
3240 "Non-nil means, preserve all line breaks when exporting.
3241 Normally, in HTML output paragraphs will be reformatted. In ASCII
3242 export, line breaks will always be preserved, regardless of this variable.
3244 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3245 :group 'org-export-general
3246 :type 'boolean)
3248 (defcustom org-export-with-archived-trees 'headline
3249 "Whether subtrees with the ARCHIVE tag should be exported.
3250 This can have three different values
3251 nil Do not export, pretend this tree is not present
3252 t Do export the entire tree
3253 headline Only export the headline, but skip the tree below it."
3254 :group 'org-export-general
3255 :group 'org-archive
3256 :type '(choice
3257 (const :tag "not at all" nil)
3258 (const :tag "headline only" 'headline)
3259 (const :tag "entirely" t)))
3261 (defcustom org-export-author-info t
3262 "Non-nil means, insert author name and email into the exported file.
3264 This option can also be set with the +OPTIONS line,
3265 e.g. \"author-info:nil\"."
3266 :group 'org-export-general
3267 :type 'boolean)
3269 (defcustom org-export-time-stamp-file t
3270 "Non-nil means, insert a time stamp into the exported file.
3271 The time stamp shows when the file was created.
3273 This option can also be set with the +OPTIONS line,
3274 e.g. \"timestamp:nil\"."
3275 :group 'org-export-general
3276 :type 'boolean)
3278 (defcustom org-export-with-timestamps t
3279 "If nil, do not export time stamps and associated keywords."
3280 :group 'org-export-general
3281 :type 'boolean)
3283 (defcustom org-export-remove-timestamps-from-toc t
3284 "If nil, remove timestamps from the table of contents entries."
3285 :group 'org-export-general
3286 :type 'boolean)
3288 (defcustom org-export-with-tags 'not-in-toc
3289 "If nil, do not export tags, just remove them from headlines.
3290 If this is the symbol `not-in-toc', tags will be removed from table of
3291 contents entries, but still be shown in the headlines of the document.
3293 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3294 :group 'org-export-general
3295 :type '(choice
3296 (const :tag "Off" nil)
3297 (const :tag "Not in TOC" not-in-toc)
3298 (const :tag "On" t)))
3300 (defcustom org-export-with-drawers nil
3301 "Non-nil means, export with drawers like the property drawer.
3302 When t, all drawers are exported. This may also be a list of
3303 drawer names to export."
3304 :group 'org-export-general
3305 :type '(choice
3306 (const :tag "All drawers" t)
3307 (const :tag "None" nil)
3308 (repeat :tag "Selected drawers"
3309 (string :tag "Drawer name"))))
3311 (defgroup org-export-translation nil
3312 "Options for translating special ascii sequences for the export backends."
3313 :tag "Org Export Translation"
3314 :group 'org-export)
3316 (defcustom org-export-with-emphasize t
3317 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3318 If the export target supports emphasizing text, the word will be
3319 typeset in bold, italic, or underlined, respectively. Works only for
3320 single words, but you can say: I *really* *mean* *this*.
3321 Not all export backends support this.
3323 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3324 :group 'org-export-translation
3325 :type 'boolean)
3327 (defcustom org-export-with-footnotes t
3328 "If nil, export [1] as a footnote marker.
3329 Lines starting with [1] will be formatted as footnotes.
3331 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3332 :group 'org-export-translation
3333 :type 'boolean)
3335 (defcustom org-export-with-sub-superscripts t
3336 "Non-nil means, interpret \"_\" and \"^\" for export.
3337 When this option is turned on, you can use TeX-like syntax for sub- and
3338 superscripts. Several characters after \"_\" or \"^\" will be
3339 considered as a single item - so grouping with {} is normally not
3340 needed. For example, the following things will be parsed as single
3341 sub- or superscripts.
3343 10^24 or 10^tau several digits will be considered 1 item.
3344 10^-12 or 10^-tau a leading sign with digits or a word
3345 x^2-y^3 will be read as x^2 - y^3, because items are
3346 terminated by almost any nonword/nondigit char.
3347 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3349 Still, ambiguity is possible - so when in doubt use {} to enclose the
3350 sub/superscript. If you set this variable to the symbol `{}',
3351 the braces are *required* in order to trigger interpretations as
3352 sub/superscript. This can be helpful in documents that need \"_\"
3353 frequently in plain text.
3355 Not all export backends support this, but HTML does.
3357 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3358 :group 'org-export-translation
3359 :type '(choice
3360 (const :tag "Always interpret" t)
3361 (const :tag "Only with braces" {})
3362 (const :tag "Never interpret" nil)))
3364 (defcustom org-export-with-special-strings t
3365 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3366 When this option is turned on, these strings will be exported as:
3368 \\- : &shy;
3369 -- : &ndash;
3370 --- : &mdash;
3372 Not all export backends support this, but HTML does.
3374 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3375 :group 'org-export-translation
3376 :type 'boolean)
3378 (defcustom org-export-with-TeX-macros t
3379 "Non-nil means, interpret simple TeX-like macros when exporting.
3380 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3381 No only real TeX macros will work here, but the standard HTML entities
3382 for math can be used as macro names as well. For a list of supported
3383 names in HTML export, see the constant `org-html-entities'.
3384 Not all export backends support this.
3386 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3387 :group 'org-export-translation
3388 :group 'org-export-latex
3389 :type 'boolean)
3391 (defcustom org-export-with-LaTeX-fragments nil
3392 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3393 When set, the exporter will find LaTeX environments if the \\begin line is
3394 the first non-white thing on a line. It will also find the math delimiters
3395 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3396 display math.
3398 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3399 :group 'org-export-translation
3400 :group 'org-export-latex
3401 :type 'boolean)
3403 (defcustom org-export-with-fixed-width t
3404 "Non-nil means, lines starting with \":\" will be in fixed width font.
3405 This can be used to have pre-formatted text, fragments of code etc. For
3406 example:
3407 : ;; Some Lisp examples
3408 : (while (defc cnt)
3409 : (ding))
3410 will be looking just like this in also HTML. See also the QUOTE keyword.
3411 Not all export backends support this.
3413 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3414 :group 'org-export-translation
3415 :type 'boolean)
3417 (defcustom org-match-sexp-depth 3
3418 "Number of stacked braces for sub/superscript matching.
3419 This has to be set before loading org.el to be effective."
3420 :group 'org-export-translation
3421 :type 'integer)
3423 (defgroup org-export-tables nil
3424 "Options for exporting tables in Org-mode."
3425 :tag "Org Export Tables"
3426 :group 'org-export)
3428 (defcustom org-export-with-tables t
3429 "If non-nil, lines starting with \"|\" define a table.
3430 For example:
3432 | Name | Address | Birthday |
3433 |-------------+----------+-----------|
3434 | Arthur Dent | England | 29.2.2100 |
3436 Not all export backends support this.
3438 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3439 :group 'org-export-tables
3440 :type 'boolean)
3442 (defcustom org-export-highlight-first-table-line t
3443 "Non-nil means, highlight the first table line.
3444 In HTML export, this means use <th> instead of <td>.
3445 In tables created with table.el, this applies to the first table line.
3446 In Org-mode tables, all lines before the first horizontal separator
3447 line will be formatted with <th> tags."
3448 :group 'org-export-tables
3449 :type 'boolean)
3451 (defcustom org-export-table-remove-special-lines t
3452 "Remove special lines and marking characters in calculating tables.
3453 This removes the special marking character column from tables that are set
3454 up for spreadsheet calculations. It also removes the entire lines
3455 marked with `!', `_', or `^'. The lines with `$' are kept, because
3456 the values of constants may be useful to have."
3457 :group 'org-export-tables
3458 :type 'boolean)
3460 (defcustom org-export-prefer-native-exporter-for-tables nil
3461 "Non-nil means, always export tables created with table.el natively.
3462 Natively means, use the HTML code generator in table.el.
3463 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3464 the table does not use row- or column-spanning). This has the
3465 advantage, that the automatic HTML conversions for math symbols and
3466 sub/superscripts can be applied. Org-mode's HTML generator is also
3467 much faster."
3468 :group 'org-export-tables
3469 :type 'boolean)
3471 (defgroup org-export-ascii nil
3472 "Options specific for ASCII export of Org-mode files."
3473 :tag "Org Export ASCII"
3474 :group 'org-export)
3476 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3477 "Characters for underlining headings in ASCII export.
3478 In the given sequence, these characters will be used for level 1, 2, ..."
3479 :group 'org-export-ascii
3480 :type '(repeat character))
3482 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3483 "Bullet characters for headlines converted to lists in ASCII export.
3484 The first character is used for the first lest level generated in this
3485 way, and so on. If there are more levels than characters given here,
3486 the list will be repeated.
3487 Note that plain lists will keep the same bullets as the have in the
3488 Org-mode file."
3489 :group 'org-export-ascii
3490 :type '(repeat character))
3492 (defgroup org-export-xml nil
3493 "Options specific for XML export of Org-mode files."
3494 :tag "Org Export XML"
3495 :group 'org-export)
3497 (defgroup org-export-html nil
3498 "Options specific for HTML export of Org-mode files."
3499 :tag "Org Export HTML"
3500 :group 'org-export)
3502 (defcustom org-export-html-coding-system nil
3504 :group 'org-export-html
3505 :type 'coding-system)
3507 (defcustom org-export-html-extension "html"
3508 "The extension for exported HTML files."
3509 :group 'org-export-html
3510 :type 'string)
3512 (defcustom org-export-html-style
3513 "<style type=\"text/css\">
3514 html {
3515 font-family: Times, serif;
3516 font-size: 12pt;
3518 .title { text-align: center; }
3519 .todo { color: red; }
3520 .done { color: green; }
3521 .timestamp { color: grey }
3522 .timestamp-kwd { color: CadetBlue }
3523 .tag { background-color:lightblue; font-weight:normal }
3524 .target { background-color: lavender; }
3525 pre {
3526 border: 1pt solid #AEBDCC;
3527 background-color: #F3F5F7;
3528 padding: 5pt;
3529 font-family: courier, monospace;
3531 table { border-collapse: collapse; }
3532 td, th {
3533 vertical-align: top;
3534 <!--border: 1pt solid #ADB9CC;-->
3536 </style>"
3537 "The default style specification for exported HTML files.
3538 Since there are different ways of setting style information, this variable
3539 needs to contain the full HTML structure to provide a style, including the
3540 surrounding HTML tags. The style specifications should include definitions
3541 for new classes todo, done, title, and deadline. For example, legal values
3542 would be:
3544 <style type=\"text/css\">
3545 p { font-weight: normal; color: gray; }
3546 h1 { color: black; }
3547 .title { text-align: center; }
3548 .todo, .deadline { color: red; }
3549 .done { color: green; }
3550 </style>
3552 or, if you want to keep the style in a file,
3554 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3556 As the value of this option simply gets inserted into the HTML <head> header,
3557 you can \"misuse\" it to add arbitrary text to the header."
3558 :group 'org-export-html
3559 :type 'string)
3562 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3563 "Format for typesetting the document title in HTML export."
3564 :group 'org-export-html
3565 :type 'string)
3567 (defcustom org-export-html-toplevel-hlevel 2
3568 "The <H> level for level 1 headings in HTML export."
3569 :group 'org-export-html
3570 :type 'string)
3572 (defcustom org-export-html-link-org-files-as-html t
3573 "Non-nil means, make file links to `file.org' point to `file.html'.
3574 When org-mode is exporting an org-mode file to HTML, links to
3575 non-html files are directly put into a href tag in HTML.
3576 However, links to other Org-mode files (recognized by the
3577 extension `.org.) should become links to the corresponding html
3578 file, assuming that the linked org-mode file will also be
3579 converted to HTML.
3580 When nil, the links still point to the plain `.org' file."
3581 :group 'org-export-html
3582 :type 'boolean)
3584 (defcustom org-export-html-inline-images 'maybe
3585 "Non-nil means, inline images into exported HTML pages.
3586 This is done using an <img> tag. When nil, an anchor with href is used to
3587 link to the image. If this option is `maybe', then images in links with
3588 an empty description will be inlined, while images with a description will
3589 be linked only."
3590 :group 'org-export-html
3591 :type '(choice (const :tag "Never" nil)
3592 (const :tag "Always" t)
3593 (const :tag "When there is no description" maybe)))
3595 ;; FIXME: rename
3596 (defcustom org-export-html-expand t
3597 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3598 When nil, these tags will be exported as plain text and therefore
3599 not be interpreted by a browser.
3601 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3602 :group 'org-export-html
3603 :type 'boolean)
3605 (defcustom org-export-html-table-tag
3606 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3607 "The HTML tag that is used to start a table.
3608 This must be a <table> tag, but you may change the options like
3609 borders and spacing."
3610 :group 'org-export-html
3611 :type 'string)
3613 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3614 "The opening tag for table header fields.
3615 This is customizable so that alignment options can be specified."
3616 :group 'org-export-tables
3617 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3619 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3620 "The opening tag for table data fields.
3621 This is customizable so that alignment options can be specified."
3622 :group 'org-export-tables
3623 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3625 (defcustom org-export-html-with-timestamp nil
3626 "If non-nil, write `org-export-html-html-helper-timestamp'
3627 into the exported HTML text. Otherwise, the buffer will just be saved
3628 to a file."
3629 :group 'org-export-html
3630 :type 'boolean)
3632 (defcustom org-export-html-html-helper-timestamp
3633 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3634 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3635 :group 'org-export-html
3636 :type 'string)
3638 (defgroup org-export-icalendar nil
3639 "Options specific for iCalendar export of Org-mode files."
3640 :tag "Org Export iCalendar"
3641 :group 'org-export)
3643 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3644 "The file name for the iCalendar file covering all agenda files.
3645 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3646 The file name should be absolute, the file will be overwritten without warning."
3647 :group 'org-export-icalendar
3648 :type 'file)
3650 (defcustom org-icalendar-include-todo nil
3651 "Non-nil means, export to iCalendar files should also cover TODO items."
3652 :group 'org-export-icalendar
3653 :type '(choice
3654 (const :tag "None" nil)
3655 (const :tag "Unfinished" t)
3656 (const :tag "All" all)))
3658 (defcustom org-icalendar-include-sexps t
3659 "Non-nil means, export to iCalendar files should also cover sexp entries.
3660 These are entries like in the diary, but directly in an Org-mode file."
3661 :group 'org-export-icalendar
3662 :type 'boolean)
3664 (defcustom org-icalendar-include-body 100
3665 "Amount of text below headline to be included in iCalendar export.
3666 This is a number of characters that should maximally be included.
3667 Properties, scheduling and clocking lines will always be removed.
3668 The text will be inserted into the DESCRIPTION field."
3669 :group 'org-export-icalendar
3670 :type '(choice
3671 (const :tag "Nothing" nil)
3672 (const :tag "Everything" t)
3673 (integer :tag "Max characters")))
3675 (defcustom org-icalendar-combined-name "OrgMode"
3676 "Calendar name for the combined iCalendar representing all agenda files."
3677 :group 'org-export-icalendar
3678 :type 'string)
3680 (defgroup org-font-lock nil
3681 "Font-lock settings for highlighting in Org-mode."
3682 :tag "Org Font Lock"
3683 :group 'org)
3685 (defcustom org-level-color-stars-only nil
3686 "Non-nil means fontify only the stars in each headline.
3687 When nil, the entire headline is fontified.
3688 Changing it requires restart of `font-lock-mode' to become effective
3689 also in regions already fontified."
3690 :group 'org-font-lock
3691 :type 'boolean)
3693 (defcustom org-hide-leading-stars nil
3694 "Non-nil means, hide the first N-1 stars in a headline.
3695 This works by using the face `org-hide' for these stars. This
3696 face is white for a light background, and black for a dark
3697 background. You may have to customize the face `org-hide' to
3698 make this work.
3699 Changing it requires restart of `font-lock-mode' to become effective
3700 also in regions already fontified.
3701 You may also set this on a per-file basis by adding one of the following
3702 lines to the buffer:
3704 #+STARTUP: hidestars
3705 #+STARTUP: showstars"
3706 :group 'org-font-lock
3707 :type 'boolean)
3709 (defcustom org-fontify-done-headline nil
3710 "Non-nil means, change the face of a headline if it is marked DONE.
3711 Normally, only the TODO/DONE keyword indicates the state of a headline.
3712 When this is non-nil, the headline after the keyword is set to the
3713 `org-headline-done' as an additional indication."
3714 :group 'org-font-lock
3715 :type 'boolean)
3717 (defcustom org-fontify-emphasized-text t
3718 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3719 Changing this variable requires a restart of Emacs to take effect."
3720 :group 'org-font-lock
3721 :type 'boolean)
3723 (defcustom org-highlight-latex-fragments-and-specials nil
3724 "Non-nil means, fontify what is treated specially by the exporters."
3725 :group 'org-font-lock
3726 :type 'boolean)
3728 (defcustom org-hide-emphasis-markers nil
3729 "Non-nil mean font-lock should hide the emphasis marker characters."
3730 :group 'org-font-lock
3731 :type 'boolean)
3733 (defvar org-emph-re nil
3734 "Regular expression for matching emphasis.")
3735 (defvar org-verbatim-re nil
3736 "Regular expression for matching verbatim text.")
3737 (defvar org-emphasis-regexp-components) ; defined just below
3738 (defvar org-emphasis-alist) ; defined just below
3739 (defun org-set-emph-re (var val)
3740 "Set variable and compute the emphasis regular expression."
3741 (set var val)
3742 (when (and (boundp 'org-emphasis-alist)
3743 (boundp 'org-emphasis-regexp-components)
3744 org-emphasis-alist org-emphasis-regexp-components)
3745 (let* ((e org-emphasis-regexp-components)
3746 (pre (car e))
3747 (post (nth 1 e))
3748 (border (nth 2 e))
3749 (body (nth 3 e))
3750 (nl (nth 4 e))
3751 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3752 (body1 (concat body "*?"))
3753 (markers (mapconcat 'car org-emphasis-alist ""))
3754 (vmarkers (mapconcat
3755 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3756 org-emphasis-alist "")))
3757 ;; make sure special characters appear at the right position in the class
3758 (if (string-match "\\^" markers)
3759 (setq markers (concat (replace-match "" t t markers) "^")))
3760 (if (string-match "-" markers)
3761 (setq markers (concat (replace-match "" t t markers) "-")))
3762 (if (string-match "\\^" vmarkers)
3763 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3764 (if (string-match "-" vmarkers)
3765 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3766 (if (> nl 0)
3767 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3768 (int-to-string nl) "\\}")))
3769 ;; Make the regexp
3770 (setq org-emph-re
3771 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3772 "\\("
3773 "\\([" markers "]\\)"
3774 "\\("
3775 "[^" border "]\\|"
3776 "[^" border (if (and nil stacked) markers) "]"
3777 body1
3778 "[^" border (if (and nil stacked) markers) "]"
3779 "\\)"
3780 "\\3\\)"
3781 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3782 (setq org-verbatim-re
3783 (concat "\\([" pre "]\\|^\\)"
3784 "\\("
3785 "\\([" vmarkers "]\\)"
3786 "\\("
3787 "[^" border "]\\|"
3788 "[^" border "]"
3789 body1
3790 "[^" border "]"
3791 "\\)"
3792 "\\3\\)"
3793 "\\([" post "]\\|$\\)")))))
3795 (defcustom org-emphasis-regexp-components
3796 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3797 "Components used to build the regular expression for emphasis.
3798 This is a list with 6 entries. Terminology: In an emphasis string
3799 like \" *strong word* \", we call the initial space PREMATCH, the final
3800 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3801 and \"trong wor\" is the body. The different components in this variable
3802 specify what is allowed/forbidden in each part:
3804 pre Chars allowed as prematch. Beginning of line will be allowed too.
3805 post Chars allowed as postmatch. End of line will be allowed too.
3806 border The chars *forbidden* as border characters.
3807 body-regexp A regexp like \".\" to match a body character. Don't use
3808 non-shy groups here, and don't allow newline here.
3809 newline The maximum number of newlines allowed in an emphasis exp.
3811 Use customize to modify this, or restart Emacs after changing it."
3812 :group 'org-font-lock
3813 :set 'org-set-emph-re
3814 :type '(list
3815 (sexp :tag "Allowed chars in pre ")
3816 (sexp :tag "Allowed chars in post ")
3817 (sexp :tag "Forbidden chars in border ")
3818 (sexp :tag "Regexp for body ")
3819 (integer :tag "number of newlines allowed")
3820 (option (boolean :tag "Stacking (DISABLED) "))))
3822 (defcustom org-emphasis-alist
3823 '(("*" bold "<b>" "</b>")
3824 ("/" italic "<i>" "</i>")
3825 ("_" underline "<u>" "</u>")
3826 ("=" org-code "<code>" "</code>" verbatim)
3827 ("~" org-verbatim "" "" verbatim)
3828 ("+" (:strike-through t) "<del>" "</del>")
3830 "Special syntax for emphasized text.
3831 Text starting and ending with a special character will be emphasized, for
3832 example *bold*, _underlined_ and /italic/. This variable sets the marker
3833 characters, the face to be used by font-lock for highlighting in Org-mode
3834 Emacs buffers, and the HTML tags to be used for this.
3835 Use customize to modify this, or restart Emacs after changing it."
3836 :group 'org-font-lock
3837 :set 'org-set-emph-re
3838 :type '(repeat
3839 (list
3840 (string :tag "Marker character")
3841 (choice
3842 (face :tag "Font-lock-face")
3843 (plist :tag "Face property list"))
3844 (string :tag "HTML start tag")
3845 (string :tag "HTML end tag")
3846 (option (const verbatim)))))
3848 ;;; The faces
3850 (defgroup org-faces nil
3851 "Faces in Org-mode."
3852 :tag "Org Faces"
3853 :group 'org-font-lock)
3855 (defun org-compatible-face (inherits specs)
3856 "Make a compatible face specification.
3857 If INHERITS is an existing face and if the Emacs version supports it,
3858 just inherit the face. If not, use SPECS to define the face.
3859 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3860 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3861 to the top of the list. The `min-colors' attribute will be removed from
3862 any other entries, and any resulting duplicates will be removed entirely."
3863 (cond
3864 ((and inherits (facep inherits)
3865 (not (featurep 'xemacs)) (> emacs-major-version 22))
3866 ;; In Emacs 23, we use inheritance where possible.
3867 ;; We only do this in Emacs 23, because only there the outline
3868 ;; faces have been changed to the original org-mode-level-faces.
3869 (list (list t :inherit inherits)))
3870 ((or (featurep 'xemacs) (< emacs-major-version 22))
3871 ;; These do not understand the `min-colors' attribute.
3872 (let (r e a)
3873 (while (setq e (pop specs))
3874 (cond
3875 ((memq (car e) '(t default)) (push e r))
3876 ((setq a (member '(min-colors 8) (car e)))
3877 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3878 (cdr e)))))
3879 ((setq a (assq 'min-colors (car e)))
3880 (setq e (cons (delq a (car e)) (cdr e)))
3881 (or (assoc (car e) r) (push e r)))
3882 (t (or (assoc (car e) r) (push e r)))))
3883 (nreverse r)))
3884 (t specs)))
3885 (put 'org-compatible-face 'lisp-indent-function 1)
3887 (defface org-hide
3888 '((((background light)) (:foreground "white"))
3889 (((background dark)) (:foreground "black")))
3890 "Face used to hide leading stars in headlines.
3891 The forground color of this face should be equal to the background
3892 color of the frame."
3893 :group 'org-faces)
3895 (defface org-level-1 ;; font-lock-function-name-face
3896 (org-compatible-face 'outline-1
3897 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3898 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3899 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3900 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3901 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3902 (t (:bold t))))
3903 "Face used for level 1 headlines."
3904 :group 'org-faces)
3906 (defface org-level-2 ;; font-lock-variable-name-face
3907 (org-compatible-face 'outline-2
3908 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3909 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3910 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3911 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3912 (t (:bold t))))
3913 "Face used for level 2 headlines."
3914 :group 'org-faces)
3916 (defface org-level-3 ;; font-lock-keyword-face
3917 (org-compatible-face 'outline-3
3918 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3919 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3920 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3921 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3922 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3923 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3924 (t (:bold t))))
3925 "Face used for level 3 headlines."
3926 :group 'org-faces)
3928 (defface org-level-4 ;; font-lock-comment-face
3929 (org-compatible-face 'outline-4
3930 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
3931 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
3932 (((class color) (min-colors 16) (background light)) (:foreground "red"))
3933 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
3934 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
3935 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
3936 (t (:bold t))))
3937 "Face used for level 4 headlines."
3938 :group 'org-faces)
3940 (defface org-level-5 ;; font-lock-type-face
3941 (org-compatible-face 'outline-5
3942 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
3943 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
3944 (((class color) (min-colors 8)) (:foreground "green"))))
3945 "Face used for level 5 headlines."
3946 :group 'org-faces)
3948 (defface org-level-6 ;; font-lock-constant-face
3949 (org-compatible-face 'outline-6
3950 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
3951 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
3952 (((class color) (min-colors 8)) (:foreground "magenta"))))
3953 "Face used for level 6 headlines."
3954 :group 'org-faces)
3956 (defface org-level-7 ;; font-lock-builtin-face
3957 (org-compatible-face 'outline-7
3958 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
3959 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
3960 (((class color) (min-colors 8)) (:foreground "blue"))))
3961 "Face used for level 7 headlines."
3962 :group 'org-faces)
3964 (defface org-level-8 ;; font-lock-string-face
3965 (org-compatible-face 'outline-8
3966 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3967 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3968 (((class color) (min-colors 8)) (:foreground "green"))))
3969 "Face used for level 8 headlines."
3970 :group 'org-faces)
3972 (defface org-special-keyword ;; font-lock-string-face
3973 (org-compatible-face nil
3974 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
3975 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
3976 (t (:italic t))))
3977 "Face used for special keywords."
3978 :group 'org-faces)
3980 (defface org-drawer ;; font-lock-function-name-face
3981 (org-compatible-face nil
3982 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3983 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3984 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3985 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3986 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3987 (t (:bold t))))
3988 "Face used for drawers."
3989 :group 'org-faces)
3991 (defface org-property-value nil
3992 "Face used for the value of a property."
3993 :group 'org-faces)
3995 (defface org-column
3996 (org-compatible-face nil
3997 '((((class color) (min-colors 16) (background light))
3998 (:background "grey90"))
3999 (((class color) (min-colors 16) (background dark))
4000 (:background "grey30"))
4001 (((class color) (min-colors 8))
4002 (:background "cyan" :foreground "black"))
4003 (t (:inverse-video t))))
4004 "Face for column display of entry properties."
4005 :group 'org-faces)
4007 (when (fboundp 'set-face-attribute)
4008 ;; Make sure that a fixed-width face is used when we have a column table.
4009 (set-face-attribute 'org-column nil
4010 :height (face-attribute 'default :height)
4011 :family (face-attribute 'default :family)))
4013 (defface org-warning
4014 (org-compatible-face 'font-lock-warning-face
4015 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4016 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4017 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4018 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4019 (t (:bold t))))
4020 "Face for deadlines and TODO keywords."
4021 :group 'org-faces)
4023 (defface org-archived ; similar to shadow
4024 (org-compatible-face 'shadow
4025 '((((class color grayscale) (min-colors 88) (background light))
4026 (:foreground "grey50"))
4027 (((class color grayscale) (min-colors 88) (background dark))
4028 (:foreground "grey70"))
4029 (((class color) (min-colors 8) (background light))
4030 (:foreground "green"))
4031 (((class color) (min-colors 8) (background dark))
4032 (:foreground "yellow"))))
4033 "Face for headline with the ARCHIVE tag."
4034 :group 'org-faces)
4036 (defface org-link
4037 '((((class color) (background light)) (:foreground "Purple" :underline t))
4038 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4039 (t (:underline t)))
4040 "Face for links."
4041 :group 'org-faces)
4043 (defface org-ellipsis
4044 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4045 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4046 (t (:strike-through t)))
4047 "Face for the ellipsis in folded text."
4048 :group 'org-faces)
4050 (defface org-target
4051 '((((class color) (background light)) (:underline t))
4052 (((class color) (background dark)) (:underline t))
4053 (t (:underline t)))
4054 "Face for links."
4055 :group 'org-faces)
4057 (defface org-date
4058 '((((class color) (background light)) (:foreground "Purple" :underline t))
4059 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4060 (t (:underline t)))
4061 "Face for links."
4062 :group 'org-faces)
4064 (defface org-sexp-date
4065 '((((class color) (background light)) (:foreground "Purple"))
4066 (((class color) (background dark)) (:foreground "Cyan"))
4067 (t (:underline t)))
4068 "Face for links."
4069 :group 'org-faces)
4071 (defface org-tag
4072 '((t (:bold t)))
4073 "Face for tags."
4074 :group 'org-faces)
4076 (defface org-todo ; font-lock-warning-face
4077 (org-compatible-face nil
4078 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4079 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4080 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4081 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4082 (t (:inverse-video t :bold t))))
4083 "Face for TODO keywords."
4084 :group 'org-faces)
4086 (defface org-done ;; font-lock-type-face
4087 (org-compatible-face nil
4088 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4089 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4090 (((class color) (min-colors 8)) (:foreground "green"))
4091 (t (:bold t))))
4092 "Face used for todo keywords that indicate DONE items."
4093 :group 'org-faces)
4095 (defface org-headline-done ;; font-lock-string-face
4096 (org-compatible-face nil
4097 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4098 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4099 (((class color) (min-colors 8) (background light)) (:bold nil))))
4100 "Face used to indicate that a headline is DONE.
4101 This face is only used if `org-fontify-done-headline' is set. If applies
4102 to the part of the headline after the DONE keyword."
4103 :group 'org-faces)
4105 (defcustom org-todo-keyword-faces nil
4106 "Faces for specific TODO keywords.
4107 This is a list of cons cells, with TODO keywords in the car
4108 and faces in the cdr. The face can be a symbol, or a property
4109 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4110 :group 'org-faces
4111 :group 'org-todo
4112 :type '(repeat
4113 (cons
4114 (string :tag "keyword")
4115 (sexp :tag "face"))))
4117 (defface org-table ;; font-lock-function-name-face
4118 (org-compatible-face nil
4119 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4120 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4121 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4122 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4123 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4124 (((class color) (min-colors 8) (background dark)))))
4125 "Face used for tables."
4126 :group 'org-faces)
4128 (defface org-formula
4129 (org-compatible-face nil
4130 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4131 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4132 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4133 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4134 (t (:bold t :italic t))))
4135 "Face for formulas."
4136 :group 'org-faces)
4138 (defface org-code
4139 (org-compatible-face nil
4140 '((((class color grayscale) (min-colors 88) (background light))
4141 (:foreground "grey50"))
4142 (((class color grayscale) (min-colors 88) (background dark))
4143 (:foreground "grey70"))
4144 (((class color) (min-colors 8) (background light))
4145 (:foreground "green"))
4146 (((class color) (min-colors 8) (background dark))
4147 (:foreground "yellow"))))
4148 "Face for fixed-with text like code snippets."
4149 :group 'org-faces
4150 :version "22.1")
4152 (defface org-verbatim
4153 (org-compatible-face nil
4154 '((((class color grayscale) (min-colors 88) (background light))
4155 (:foreground "grey50" :underline t))
4156 (((class color grayscale) (min-colors 88) (background dark))
4157 (:foreground "grey70" :underline t))
4158 (((class color) (min-colors 8) (background light))
4159 (:foreground "green" :underline t))
4160 (((class color) (min-colors 8) (background dark))
4161 (:foreground "yellow" :underline t))))
4162 "Face for fixed-with text like code snippets."
4163 :group 'org-faces
4164 :version "22.1")
4166 (defface org-agenda-structure ;; font-lock-function-name-face
4167 (org-compatible-face nil
4168 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4169 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4170 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4171 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4172 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4173 (t (:bold t))))
4174 "Face used in agenda for captions and dates."
4175 :group 'org-faces)
4177 (defface org-scheduled-today
4178 (org-compatible-face nil
4179 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4180 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4181 (((class color) (min-colors 8)) (:foreground "green"))
4182 (t (:bold t :italic t))))
4183 "Face for items scheduled for a certain day."
4184 :group 'org-faces)
4186 (defface org-scheduled-previously
4187 (org-compatible-face nil
4188 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4189 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4190 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4191 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4192 (t (:bold t))))
4193 "Face for items scheduled previously, and not yet done."
4194 :group 'org-faces)
4196 (defface org-upcoming-deadline
4197 (org-compatible-face nil
4198 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4199 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4200 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4201 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4202 (t (:bold t))))
4203 "Face for items scheduled previously, and not yet done."
4204 :group 'org-faces)
4206 (defcustom org-agenda-deadline-faces
4207 '((1.0 . org-warning)
4208 (0.5 . org-upcoming-deadline)
4209 (0.0 . default))
4210 "Faces for showing deadlines in the agenda.
4211 This is a list of cons cells. The cdr of each cell is a face to be used,
4212 and it can also just be like '(:foreground \"yellow\").
4213 Each car is a fraction of the head-warning time that must have passed for
4214 this the face in the cdr to be used for display. The numbers must be
4215 given in descending order. The head-warning time is normally taken
4216 from `org-deadline-warning-days', but can also be specified in the deadline
4217 timestamp itself, like this:
4219 DEADLINE: <2007-08-13 Mon -8d>
4221 You may use d for days, w for weeks, m for months and y for years. Months
4222 and years will only be treated in an approximate fashion (30.4 days for a
4223 month and 365.24 days for a year)."
4224 :group 'org-faces
4225 :group 'org-agenda-daily/weekly
4226 :type '(repeat
4227 (cons
4228 (number :tag "Fraction of head-warning time passed")
4229 (sexp :tag "Face"))))
4231 ;; FIXME: this is not a good face yet.
4232 (defface org-agenda-restriction-lock
4233 (org-compatible-face nil
4234 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4235 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4236 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4237 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4238 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4239 (t (:inverse-video t))))
4240 "Face for showing the agenda restriction lock."
4241 :group 'org-faces)
4243 (defface org-time-grid ;; font-lock-variable-name-face
4244 (org-compatible-face nil
4245 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4246 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4247 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4248 "Face used for time grids."
4249 :group 'org-faces)
4251 (defconst org-level-faces
4252 '(org-level-1 org-level-2 org-level-3 org-level-4
4253 org-level-5 org-level-6 org-level-7 org-level-8
4256 (defcustom org-n-level-faces (length org-level-faces)
4257 "The number of different faces to be used for headlines.
4258 Org-mode defines 8 different headline faces, so this can be at most 8.
4259 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4260 :type 'number
4261 :group 'org-faces)
4263 ;;; Functions and variables from ther packages
4264 ;; Declared here to avoid compiler warnings
4266 (eval-and-compile
4267 (unless (fboundp 'declare-function)
4268 (defmacro declare-function (fn file &optional arglist fileonly))))
4270 ;; XEmacs only
4271 (defvar outline-mode-menu-heading)
4272 (defvar outline-mode-menu-show)
4273 (defvar outline-mode-menu-hide)
4274 (defvar zmacs-regions) ; XEmacs regions
4276 ;; Emacs only
4277 (defvar mark-active)
4279 ;; Various packages
4280 ;; FIXME: get the argument lists for the UNKNOWN stuff
4281 (declare-function add-to-diary-list "diary-lib"
4282 (date string specifier &optional marker globcolor literal))
4283 (declare-function table--at-cell-p "table" (position &optional object at-column))
4284 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4285 (declare-function bbdb "ext:bbdb-com" (string elidep))
4286 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4287 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4288 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4289 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4290 (declare-function bbdb-record-name "ext:bbdb" (record))
4291 (declare-function bibtex-beginning-of-entry "bibtex" ())
4292 (declare-function bibtex-generate-autokey "bibtex" ())
4293 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4294 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4295 (defvar calc-embedded-close-formula)
4296 (defvar calc-embedded-open-formula)
4297 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4298 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4299 (declare-function calendar-check-holidays "holidays" (date))
4300 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4301 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4302 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4303 (declare-function calendar-forward-day "cal-move" (arg))
4304 (declare-function calendar-french-date-string "cal-french" (&optional date))
4305 (declare-function calendar-goto-date "cal-move" (date))
4306 (declare-function calendar-goto-today "cal-move" ())
4307 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4308 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4309 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4310 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4311 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4312 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4313 (defvar calendar-mode-map)
4314 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4315 (declare-function cdlatex-tab "ext:cdlatex" ())
4316 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4317 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4318 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4319 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4320 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4321 (defvar font-lock-unfontify-region-function)
4322 (declare-function gnus-article-show-summary "gnus-art" ())
4323 (declare-function gnus-summary-last-subject "gnus-sum" ())
4324 (defvar gnus-other-frame-object)
4325 (defvar gnus-group-name)
4326 (defvar gnus-article-current)
4327 (defvar Info-current-file)
4328 (defvar Info-current-node)
4329 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4330 (declare-function mh-find-path "mh-utils" ())
4331 (declare-function mh-get-header-field "mh-utils" (field))
4332 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4333 (declare-function mh-header-display "mh-show" ())
4334 (declare-function mh-index-previous-folder "mh-search" ())
4335 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4336 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4337 (declare-function mh-search-choose "mh-search" (&optional searcher))
4338 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4339 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4340 (declare-function mh-show-header-display "mh-show" t t)
4341 (declare-function mh-show-msg "mh-show" (msg))
4342 (declare-function mh-show-show "mh-show" t t)
4343 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4344 (defvar mh-progs)
4345 (defvar mh-current-folder)
4346 (defvar mh-show-folder-buffer)
4347 (defvar mh-index-folder)
4348 (defvar mh-searcher)
4349 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4350 (declare-function parse-time-string "parse-time" (string))
4351 (declare-function remember "remember" (&optional initial))
4352 (declare-function remember-buffer-desc "remember" ())
4353 (declare-function remember-finalize "remember" ())
4354 (defvar remember-save-after-remembering)
4355 (defvar remember-data-file)
4356 (defvar remember-register)
4357 (defvar remember-buffer)
4358 (defvar remember-handler-functions)
4359 (defvar remember-annotation-functions)
4360 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4361 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4362 (declare-function rmail-what-message "rmail" ())
4363 (defvar rmail-current-message)
4364 (defvar texmathp-why)
4365 (declare-function vm-beginning-of-message "ext:vm-page" ())
4366 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4367 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4368 (declare-function vm-isearch-narrow "ext:vm-search" ())
4369 (declare-function vm-isearch-update "ext:vm-search" ())
4370 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4371 (declare-function vm-su-message-id "ext:vm-summary" (m))
4372 (declare-function vm-su-subject "ext:vm-summary" (m))
4373 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4374 (defvar vm-message-pointer)
4375 (defvar vm-folder-directory)
4376 (defvar w3m-current-url)
4377 (defvar w3m-current-title)
4378 ;; backward compatibility to old version of wl
4379 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4380 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4381 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4382 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4383 (declare-function wl-summary-line-from "ext:wl-summary" ())
4384 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4385 (declare-function wl-summary-message-number "ext:wl-summary" ())
4386 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4387 (defvar wl-summary-buffer-elmo-folder)
4388 (defvar wl-summary-buffer-folder-name)
4389 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4391 (defvar org-latex-regexps)
4392 (defvar constants-unit-system)
4394 ;;; Variables for pre-computed regular expressions, all buffer local
4396 (defvar org-drawer-regexp nil
4397 "Matches first line of a hidden block.")
4398 (make-variable-buffer-local 'org-drawer-regexp)
4399 (defvar org-todo-regexp nil
4400 "Matches any of the TODO state keywords.")
4401 (make-variable-buffer-local 'org-todo-regexp)
4402 (defvar org-not-done-regexp nil
4403 "Matches any of the TODO state keywords except the last one.")
4404 (make-variable-buffer-local 'org-not-done-regexp)
4405 (defvar org-todo-line-regexp nil
4406 "Matches a headline and puts TODO state into group 2 if present.")
4407 (make-variable-buffer-local 'org-todo-line-regexp)
4408 (defvar org-complex-heading-regexp nil
4409 "Matches a headline and puts everything into groups:
4410 group 1: the stars
4411 group 2: The todo keyword, maybe
4412 group 3: Priority cookie
4413 group 4: True headline
4414 group 5: Tags")
4415 (make-variable-buffer-local 'org-complex-heading-regexp)
4416 (defvar org-todo-line-tags-regexp nil
4417 "Matches a headline and puts TODO state into group 2 if present.
4418 Also put tags into group 4 if tags are present.")
4419 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4420 (defvar org-nl-done-regexp nil
4421 "Matches newline followed by a headline with the DONE keyword.")
4422 (make-variable-buffer-local 'org-nl-done-regexp)
4423 (defvar org-looking-at-done-regexp nil
4424 "Matches the DONE keyword a point.")
4425 (make-variable-buffer-local 'org-looking-at-done-regexp)
4426 (defvar org-ds-keyword-length 12
4427 "Maximum length of the Deadline and SCHEDULED keywords.")
4428 (make-variable-buffer-local 'org-ds-keyword-length)
4429 (defvar org-deadline-regexp nil
4430 "Matches the DEADLINE keyword.")
4431 (make-variable-buffer-local 'org-deadline-regexp)
4432 (defvar org-deadline-time-regexp nil
4433 "Matches the DEADLINE keyword together with a time stamp.")
4434 (make-variable-buffer-local 'org-deadline-time-regexp)
4435 (defvar org-deadline-line-regexp nil
4436 "Matches the DEADLINE keyword and the rest of the line.")
4437 (make-variable-buffer-local 'org-deadline-line-regexp)
4438 (defvar org-scheduled-regexp nil
4439 "Matches the SCHEDULED keyword.")
4440 (make-variable-buffer-local 'org-scheduled-regexp)
4441 (defvar org-scheduled-time-regexp nil
4442 "Matches the SCHEDULED keyword together with a time stamp.")
4443 (make-variable-buffer-local 'org-scheduled-time-regexp)
4444 (defvar org-closed-time-regexp nil
4445 "Matches the CLOSED keyword together with a time stamp.")
4446 (make-variable-buffer-local 'org-closed-time-regexp)
4448 (defvar org-keyword-time-regexp nil
4449 "Matches any of the 4 keywords, together with the time stamp.")
4450 (make-variable-buffer-local 'org-keyword-time-regexp)
4451 (defvar org-keyword-time-not-clock-regexp nil
4452 "Matches any of the 3 keywords, together with the time stamp.")
4453 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4454 (defvar org-maybe-keyword-time-regexp nil
4455 "Matches a timestamp, possibly preceeded by a keyword.")
4456 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4457 (defvar org-planning-or-clock-line-re nil
4458 "Matches a line with planning or clock info.")
4459 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4461 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4462 rear-nonsticky t mouse-map t fontified t)
4463 "Properties to remove when a string without properties is wanted.")
4465 (defsubst org-match-string-no-properties (num &optional string)
4466 (if (featurep 'xemacs)
4467 (let ((s (match-string num string)))
4468 (remove-text-properties 0 (length s) org-rm-props s)
4470 (match-string-no-properties num string)))
4472 (defsubst org-no-properties (s)
4473 (if (fboundp 'set-text-properties)
4474 (set-text-properties 0 (length s) nil s)
4475 (remove-text-properties 0 (length s) org-rm-props s))
4478 (defsubst org-get-alist-option (option key)
4479 (cond ((eq key t) t)
4480 ((eq option t) t)
4481 ((assoc key option) (cdr (assoc key option)))
4482 (t (cdr (assq 'default option)))))
4484 (defsubst org-inhibit-invisibility ()
4485 "Modified `buffer-invisibility-spec' for Emacs 21.
4486 Some ops with invisible text do not work correctly on Emacs 21. For these
4487 we turn off invisibility temporarily. Use this in a `let' form."
4488 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4490 (defsubst org-set-local (var value)
4491 "Make VAR local in current buffer and set it to VALUE."
4492 (set (make-variable-buffer-local var) value))
4494 (defsubst org-mode-p ()
4495 "Check if the current buffer is in Org-mode."
4496 (eq major-mode 'org-mode))
4498 (defsubst org-last (list)
4499 "Return the last element of LIST."
4500 (car (last list)))
4502 (defun org-let (list &rest body)
4503 (eval (cons 'let (cons list body))))
4504 (put 'org-let 'lisp-indent-function 1)
4506 (defun org-let2 (list1 list2 &rest body)
4507 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4508 (put 'org-let2 'lisp-indent-function 2)
4509 (defconst org-startup-options
4510 '(("fold" org-startup-folded t)
4511 ("overview" org-startup-folded t)
4512 ("nofold" org-startup-folded nil)
4513 ("showall" org-startup-folded nil)
4514 ("content" org-startup-folded content)
4515 ("hidestars" org-hide-leading-stars t)
4516 ("showstars" org-hide-leading-stars nil)
4517 ("odd" org-odd-levels-only t)
4518 ("oddeven" org-odd-levels-only nil)
4519 ("align" org-startup-align-all-tables t)
4520 ("noalign" org-startup-align-all-tables nil)
4521 ("customtime" org-display-custom-times t)
4522 ("logdone" org-log-done time)
4523 ("lognotedone" org-log-done note)
4524 ("nologdone" org-log-done nil)
4525 ("lognoteclock-out" org-log-note-clock-out t)
4526 ("nolognoteclock-out" org-log-note-clock-out nil)
4527 ("logrepeat" org-log-repeat state)
4528 ("lognoterepeat" org-log-repeat note)
4529 ("nologrepeat" org-log-repeat nil)
4530 ("constcgs" constants-unit-system cgs)
4531 ("constSI" constants-unit-system SI))
4532 "Variable associated with STARTUP options for org-mode.
4533 Each element is a list of three items: The startup options as written
4534 in the #+STARTUP line, the corresponding variable, and the value to
4535 set this variable to if the option is found. An optional forth element PUSH
4536 means to push this value onto the list in the variable.")
4538 (defun org-set-regexps-and-options ()
4539 "Precompute regular expressions for current buffer."
4540 (when (org-mode-p)
4541 (org-set-local 'org-todo-kwd-alist nil)
4542 (org-set-local 'org-todo-key-alist nil)
4543 (org-set-local 'org-todo-key-trigger nil)
4544 (org-set-local 'org-todo-keywords-1 nil)
4545 (org-set-local 'org-done-keywords nil)
4546 (org-set-local 'org-todo-heads nil)
4547 (org-set-local 'org-todo-sets nil)
4548 (org-set-local 'org-todo-log-states nil)
4549 (let ((re (org-make-options-regexp
4550 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4551 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4552 "CONSTANTS" "PROPERTY" "DRAWERS")))
4553 (splitre "[ \t]+")
4554 kwds kws0 kwsa key log value cat arch tags const links hw dws
4555 tail sep kws1 prio props drawers)
4556 (save-excursion
4557 (save-restriction
4558 (widen)
4559 (goto-char (point-min))
4560 (while (re-search-forward re nil t)
4561 (setq key (match-string 1) value (org-match-string-no-properties 2))
4562 (cond
4563 ((equal key "CATEGORY")
4564 (if (string-match "[ \t]+$" value)
4565 (setq value (replace-match "" t t value)))
4566 (setq cat value))
4567 ((member key '("SEQ_TODO" "TODO"))
4568 (push (cons 'sequence (org-split-string value splitre)) kwds))
4569 ((equal key "TYP_TODO")
4570 (push (cons 'type (org-split-string value splitre)) kwds))
4571 ((equal key "TAGS")
4572 (setq tags (append tags (org-split-string value splitre))))
4573 ((equal key "COLUMNS")
4574 (org-set-local 'org-columns-default-format value))
4575 ((equal key "LINK")
4576 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4577 (push (cons (match-string 1 value)
4578 (org-trim (match-string 2 value)))
4579 links)))
4580 ((equal key "PRIORITIES")
4581 (setq prio (org-split-string value " +")))
4582 ((equal key "PROPERTY")
4583 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4584 (push (cons (match-string 1 value) (match-string 2 value))
4585 props)))
4586 ((equal key "DRAWERS")
4587 (setq drawers (org-split-string value splitre)))
4588 ((equal key "CONSTANTS")
4589 (setq const (append const (org-split-string value splitre))))
4590 ((equal key "STARTUP")
4591 (let ((opts (org-split-string value splitre))
4592 l var val)
4593 (while (setq l (pop opts))
4594 (when (setq l (assoc l org-startup-options))
4595 (setq var (nth 1 l) val (nth 2 l))
4596 (if (not (nth 3 l))
4597 (set (make-local-variable var) val)
4598 (if (not (listp (symbol-value var)))
4599 (set (make-local-variable var) nil))
4600 (set (make-local-variable var) (symbol-value var))
4601 (add-to-list var val))))))
4602 ((equal key "ARCHIVE")
4603 (string-match " *$" value)
4604 (setq arch (replace-match "" t t value))
4605 (remove-text-properties 0 (length arch)
4606 '(face t fontified t) arch)))
4608 (when cat
4609 (org-set-local 'org-category (intern cat))
4610 (push (cons "CATEGORY" cat) props))
4611 (when prio
4612 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4613 (setq prio (mapcar 'string-to-char prio))
4614 (org-set-local 'org-highest-priority (nth 0 prio))
4615 (org-set-local 'org-lowest-priority (nth 1 prio))
4616 (org-set-local 'org-default-priority (nth 2 prio)))
4617 (and props (org-set-local 'org-local-properties (nreverse props)))
4618 (and drawers (org-set-local 'org-drawers drawers))
4619 (and arch (org-set-local 'org-archive-location arch))
4620 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4621 ;; Process the TODO keywords
4622 (unless kwds
4623 ;; Use the global values as if they had been given locally.
4624 (setq kwds (default-value 'org-todo-keywords))
4625 (if (stringp (car kwds))
4626 (setq kwds (list (cons org-todo-interpretation
4627 (default-value 'org-todo-keywords)))))
4628 (setq kwds (reverse kwds)))
4629 (setq kwds (nreverse kwds))
4630 (let (inter kws kw)
4631 (while (setq kws (pop kwds))
4632 (setq inter (pop kws) sep (member "|" kws)
4633 kws0 (delete "|" (copy-sequence kws))
4634 kwsa nil
4635 kws1 (mapcar
4636 (lambda (x)
4637 ;; 1 2
4638 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4639 (progn
4640 (setq kw (match-string 1 x)
4641 key (and (match-end 2) (match-string 2 x))
4642 log (org-extract-log-state-settings x))
4643 (push (cons kw (and key (string-to-char key))) kwsa)
4644 (and log (push log org-todo-log-states))
4646 (error "Invalid TODO keyword %s" x)))
4647 kws0)
4648 kwsa (if kwsa (append '((:startgroup))
4649 (nreverse kwsa)
4650 '((:endgroup))))
4651 hw (car kws1)
4652 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4653 tail (list inter hw (car dws) (org-last dws)))
4654 (add-to-list 'org-todo-heads hw 'append)
4655 (push kws1 org-todo-sets)
4656 (setq org-done-keywords (append org-done-keywords dws nil))
4657 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4658 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4659 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4660 (setq org-todo-sets (nreverse org-todo-sets)
4661 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4662 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4663 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4664 ;; Process the constants
4665 (when const
4666 (let (e cst)
4667 (while (setq e (pop const))
4668 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4669 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4670 (setq org-table-formula-constants-local cst)))
4672 ;; Process the tags.
4673 (when tags
4674 (let (e tgs)
4675 (while (setq e (pop tags))
4676 (cond
4677 ((equal e "{") (push '(:startgroup) tgs))
4678 ((equal e "}") (push '(:endgroup) tgs))
4679 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4680 (push (cons (match-string 1 e)
4681 (string-to-char (match-string 2 e)))
4682 tgs))
4683 (t (push (list e) tgs))))
4684 (org-set-local 'org-tag-alist nil)
4685 (while (setq e (pop tgs))
4686 (or (and (stringp (car e))
4687 (assoc (car e) org-tag-alist))
4688 (push e org-tag-alist))))))
4690 ;; Compute the regular expressions and other local variables
4691 (if (not org-done-keywords)
4692 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4693 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4694 (length org-scheduled-string)))
4695 org-drawer-regexp
4696 (concat "^[ \t]*:\\("
4697 (mapconcat 'regexp-quote org-drawers "\\|")
4698 "\\):[ \t]*$")
4699 org-not-done-keywords
4700 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4701 org-todo-regexp
4702 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4703 "\\|") "\\)\\>")
4704 org-not-done-regexp
4705 (concat "\\<\\("
4706 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4707 "\\)\\>")
4708 org-todo-line-regexp
4709 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4710 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4711 "\\)\\>\\)?[ \t]*\\(.*\\)")
4712 org-complex-heading-regexp
4713 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4714 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4715 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4716 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4717 org-nl-done-regexp
4718 (concat "\n\\*+[ \t]+"
4719 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4720 "\\)" "\\>")
4721 org-todo-line-tags-regexp
4722 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4723 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4724 (org-re
4725 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4726 org-looking-at-done-regexp
4727 (concat "^" "\\(?:"
4728 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4729 "\\>")
4730 org-deadline-regexp (concat "\\<" org-deadline-string)
4731 org-deadline-time-regexp
4732 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4733 org-deadline-line-regexp
4734 (concat "\\<\\(" org-deadline-string "\\).*")
4735 org-scheduled-regexp
4736 (concat "\\<" org-scheduled-string)
4737 org-scheduled-time-regexp
4738 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4739 org-closed-time-regexp
4740 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4741 org-keyword-time-regexp
4742 (concat "\\<\\(" org-scheduled-string
4743 "\\|" org-deadline-string
4744 "\\|" org-closed-string
4745 "\\|" org-clock-string "\\)"
4746 " *[[<]\\([^]>]+\\)[]>]")
4747 org-keyword-time-not-clock-regexp
4748 (concat "\\<\\(" org-scheduled-string
4749 "\\|" org-deadline-string
4750 "\\|" org-closed-string
4751 "\\)"
4752 " *[[<]\\([^]>]+\\)[]>]")
4753 org-maybe-keyword-time-regexp
4754 (concat "\\(\\<\\(" org-scheduled-string
4755 "\\|" org-deadline-string
4756 "\\|" org-closed-string
4757 "\\|" org-clock-string "\\)\\)?"
4758 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4759 org-planning-or-clock-line-re
4760 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4761 "\\|" org-deadline-string
4762 "\\|" org-closed-string "\\|" org-clock-string
4763 "\\)\\>\\)")
4765 (org-compute-latex-and-specials-regexp)
4766 (org-set-font-lock-defaults)))
4768 (defun org-extract-log-state-settings (x)
4769 "Extract the log state setting from a TODO keyword string.
4770 This will extract info from a string like \"WAIT(w@/!)\"."
4771 (let (kw key log1 log2)
4772 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4773 (setq kw (match-string 1 x)
4774 key (and (match-end 2) (match-string 2 x))
4775 log1 (and (match-end 3) (match-string 3 x))
4776 log2 (and (match-end 4) (match-string 4 x)))
4777 (and (or log1 log2)
4778 (list kw
4779 (and log1 (if (equal log1 "!") 'time 'note))
4780 (and log2 (if (equal log2 "!") 'time 'note)))))))
4782 (defun org-remove-keyword-keys (list)
4783 "Remove a pair of parenthesis at the end of each string in LIST."
4784 (mapcar (lambda (x)
4785 (if (string-match "(.*)$" x)
4786 (substring x 0 (match-beginning 0))
4788 list))
4790 ;; FIXME: this could be done much better, using second characters etc.
4791 (defun org-assign-fast-keys (alist)
4792 "Assign fast keys to a keyword-key alist.
4793 Respect keys that are already there."
4794 (let (new e k c c1 c2 (char ?a))
4795 (while (setq e (pop alist))
4796 (cond
4797 ((equal e '(:startgroup)) (push e new))
4798 ((equal e '(:endgroup)) (push e new))
4800 (setq k (car e) c2 nil)
4801 (if (cdr e)
4802 (setq c (cdr e))
4803 ;; automatically assign a character.
4804 (setq c1 (string-to-char
4805 (downcase (substring
4806 k (if (= (string-to-char k) ?@) 1 0)))))
4807 (if (or (rassoc c1 new) (rassoc c1 alist))
4808 (while (or (rassoc char new) (rassoc char alist))
4809 (setq char (1+ char)))
4810 (setq c2 c1))
4811 (setq c (or c2 char)))
4812 (push (cons k c) new))))
4813 (nreverse new)))
4815 ;;; Some variables ujsed in various places
4817 (defvar org-window-configuration nil
4818 "Used in various places to store a window configuration.")
4819 (defvar org-finish-function nil
4820 "Function to be called when `C-c C-c' is used.
4821 This is for getting out of special buffers like remember.")
4824 ;; FIXME: Occasionally check by commenting these, to make sure
4825 ;; no other functions uses these, forgetting to let-bind them.
4826 (defvar entry)
4827 (defvar state)
4828 (defvar last-state)
4829 (defvar date)
4830 (defvar description)
4832 ;; Defined somewhere in this file, but used before definition.
4833 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4834 (defvar org-agenda-buffer-name)
4835 (defvar org-agenda-undo-list)
4836 (defvar org-agenda-pending-undo-list)
4837 (defvar org-agenda-overriding-header)
4838 (defvar orgtbl-mode)
4839 (defvar org-html-entities)
4840 (defvar org-struct-menu)
4841 (defvar org-org-menu)
4842 (defvar org-tbl-menu)
4843 (defvar org-agenda-keymap)
4845 ;;;; Emacs/XEmacs compatibility
4847 ;; Overlay compatibility functions
4848 (defun org-make-overlay (beg end &optional buffer)
4849 (if (featurep 'xemacs)
4850 (make-extent beg end buffer)
4851 (make-overlay beg end buffer)))
4852 (defun org-delete-overlay (ovl)
4853 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4854 (defun org-detach-overlay (ovl)
4855 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4856 (defun org-move-overlay (ovl beg end &optional buffer)
4857 (if (featurep 'xemacs)
4858 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4859 (move-overlay ovl beg end buffer)))
4860 (defun org-overlay-put (ovl prop value)
4861 (if (featurep 'xemacs)
4862 (set-extent-property ovl prop value)
4863 (overlay-put ovl prop value)))
4864 (defun org-overlay-display (ovl text &optional face evap)
4865 "Make overlay OVL display TEXT with face FACE."
4866 (if (featurep 'xemacs)
4867 (let ((gl (make-glyph text)))
4868 (and face (set-glyph-face gl face))
4869 (set-extent-property ovl 'invisible t)
4870 (set-extent-property ovl 'end-glyph gl))
4871 (overlay-put ovl 'display text)
4872 (if face (overlay-put ovl 'face face))
4873 (if evap (overlay-put ovl 'evaporate t))))
4874 (defun org-overlay-before-string (ovl text &optional face evap)
4875 "Make overlay OVL display TEXT with face FACE."
4876 (if (featurep 'xemacs)
4877 (let ((gl (make-glyph text)))
4878 (and face (set-glyph-face gl face))
4879 (set-extent-property ovl 'begin-glyph gl))
4880 (if face (org-add-props text nil 'face face))
4881 (overlay-put ovl 'before-string text)
4882 (if evap (overlay-put ovl 'evaporate t))))
4883 (defun org-overlay-get (ovl prop)
4884 (if (featurep 'xemacs)
4885 (extent-property ovl prop)
4886 (overlay-get ovl prop)))
4887 (defun org-overlays-at (pos)
4888 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4889 (defun org-overlays-in (&optional start end)
4890 (if (featurep 'xemacs)
4891 (extent-list nil start end)
4892 (overlays-in start end)))
4893 (defun org-overlay-start (o)
4894 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4895 (defun org-overlay-end (o)
4896 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4897 (defun org-find-overlays (prop &optional pos delete)
4898 "Find all overlays specifying PROP at POS or point.
4899 If DELETE is non-nil, delete all those overlays."
4900 (let ((overlays (org-overlays-at (or pos (point))))
4901 ov found)
4902 (while (setq ov (pop overlays))
4903 (if (org-overlay-get ov prop)
4904 (if delete (org-delete-overlay ov) (push ov found))))
4905 found))
4907 ;; Region compatibility
4909 (defun org-add-hook (hook function &optional append local)
4910 "Add-hook, compatible with both Emacsen."
4911 (if (and local (featurep 'xemacs))
4912 (add-local-hook hook function append)
4913 (add-hook hook function append local)))
4915 (defvar org-ignore-region nil
4916 "To temporarily disable the active region.")
4918 (defun org-region-active-p ()
4919 "Is `transient-mark-mode' on and the region active?
4920 Works on both Emacs and XEmacs."
4921 (if org-ignore-region
4923 (if (featurep 'xemacs)
4924 (and zmacs-regions (region-active-p))
4925 (if (fboundp 'use-region-p)
4926 (use-region-p)
4927 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
4929 ;; Invisibility compatibility
4931 (defun org-add-to-invisibility-spec (arg)
4932 "Add elements to `buffer-invisibility-spec'.
4933 See documentation for `buffer-invisibility-spec' for the kind of elements
4934 that can be added."
4935 (cond
4936 ((fboundp 'add-to-invisibility-spec)
4937 (add-to-invisibility-spec arg))
4938 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
4939 (setq buffer-invisibility-spec (list arg)))
4941 (setq buffer-invisibility-spec
4942 (cons arg buffer-invisibility-spec)))))
4944 (defun org-remove-from-invisibility-spec (arg)
4945 "Remove elements from `buffer-invisibility-spec'."
4946 (if (fboundp 'remove-from-invisibility-spec)
4947 (remove-from-invisibility-spec arg)
4948 (if (consp buffer-invisibility-spec)
4949 (setq buffer-invisibility-spec
4950 (delete arg buffer-invisibility-spec)))))
4952 (defun org-in-invisibility-spec-p (arg)
4953 "Is ARG a member of `buffer-invisibility-spec'?"
4954 (if (consp buffer-invisibility-spec)
4955 (member arg buffer-invisibility-spec)
4956 nil))
4958 ;;;; Define the Org-mode
4960 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4961 (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."))
4964 ;; We use a before-change function to check if a table might need
4965 ;; an update.
4966 (defvar org-table-may-need-update t
4967 "Indicates that a table might need an update.
4968 This variable is set by `org-before-change-function'.
4969 `org-table-align' sets it back to nil.")
4970 (defvar org-mode-map)
4971 (defvar org-mode-hook nil)
4972 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4973 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4974 (defvar org-table-buffer-is-an nil)
4975 (defconst org-outline-regexp "\\*+ ")
4977 ;;;###autoload
4978 (define-derived-mode org-mode outline-mode "Org"
4979 "Outline-based notes management and organizer, alias
4980 \"Carsten's outline-mode for keeping track of everything.\"
4982 Org-mode develops organizational tasks around a NOTES file which
4983 contains information about projects as plain text. Org-mode is
4984 implemented on top of outline-mode, which is ideal to keep the content
4985 of large files well structured. It supports ToDo items, deadlines and
4986 time stamps, which magically appear in the diary listing of the Emacs
4987 calendar. Tables are easily created with a built-in table editor.
4988 Plain text URL-like links connect to websites, emails (VM), Usenet
4989 messages (Gnus), BBDB entries, and any files related to the project.
4990 For printing and sharing of notes, an Org-mode file (or a part of it)
4991 can be exported as a structured ASCII or HTML file.
4993 The following commands are available:
4995 \\{org-mode-map}"
4997 ;; Get rid of Outline menus, they are not needed
4998 ;; Need to do this here because define-derived-mode sets up
4999 ;; the keymap so late. Still, it is a waste to call this each time
5000 ;; we switch another buffer into org-mode.
5001 (if (featurep 'xemacs)
5002 (when (boundp 'outline-mode-menu-heading)
5003 ;; Assume this is Greg's port, it used easymenu
5004 (easy-menu-remove outline-mode-menu-heading)
5005 (easy-menu-remove outline-mode-menu-show)
5006 (easy-menu-remove outline-mode-menu-hide))
5007 (define-key org-mode-map [menu-bar headings] 'undefined)
5008 (define-key org-mode-map [menu-bar hide] 'undefined)
5009 (define-key org-mode-map [menu-bar show] 'undefined))
5011 (easy-menu-add org-org-menu)
5012 (easy-menu-add org-tbl-menu)
5013 (org-install-agenda-files-menu)
5014 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5015 (org-add-to-invisibility-spec '(org-cwidth))
5016 (when (featurep 'xemacs)
5017 (org-set-local 'line-move-ignore-invisible t))
5018 (org-set-local 'outline-regexp org-outline-regexp)
5019 (org-set-local 'outline-level 'org-outline-level)
5020 (when (and org-ellipsis
5021 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5022 (fboundp 'make-glyph-code))
5023 (unless org-display-table
5024 (setq org-display-table (make-display-table)))
5025 (set-display-table-slot
5026 org-display-table 4
5027 (vconcat (mapcar
5028 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5029 org-ellipsis)))
5030 (if (stringp org-ellipsis) org-ellipsis "..."))))
5031 (setq buffer-display-table org-display-table))
5032 (org-set-regexps-and-options)
5033 ;; Calc embedded
5034 (org-set-local 'calc-embedded-open-mode "# ")
5035 (modify-syntax-entry ?# "<")
5036 (modify-syntax-entry ?@ "w")
5037 (if org-startup-truncated (setq truncate-lines t))
5038 (org-set-local 'font-lock-unfontify-region-function
5039 'org-unfontify-region)
5040 ;; Activate before-change-function
5041 (org-set-local 'org-table-may-need-update t)
5042 (org-add-hook 'before-change-functions 'org-before-change-function nil
5043 'local)
5044 ;; Check for running clock before killing a buffer
5045 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5046 ;; Paragraphs and auto-filling
5047 (org-set-autofill-regexps)
5048 (setq indent-line-function 'org-indent-line-function)
5049 (org-update-radio-target-regexp)
5051 ;; Comment characters
5052 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5053 (org-set-local 'comment-padding " ")
5055 ;; Align options lines
5056 (org-set-local
5057 'align-mode-rules-list
5058 '((org-in-buffer-settings
5059 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5060 (modes . '(org-mode)))))
5062 ;; Imenu
5063 (org-set-local 'imenu-create-index-function
5064 'org-imenu-get-tree)
5066 ;; Make isearch reveal context
5067 (if (or (featurep 'xemacs)
5068 (not (boundp 'outline-isearch-open-invisible-function)))
5069 ;; Emacs 21 and XEmacs make use of the hook
5070 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5071 ;; Emacs 22 deals with this through a special variable
5072 (org-set-local 'outline-isearch-open-invisible-function
5073 (lambda (&rest ignore) (org-show-context 'isearch))))
5075 ;; If empty file that did not turn on org-mode automatically, make it to.
5076 (if (and org-insert-mode-line-in-empty-file
5077 (interactive-p)
5078 (= (point-min) (point-max)))
5079 (insert "# -*- mode: org -*-\n\n"))
5081 (unless org-inhibit-startup
5082 (when org-startup-align-all-tables
5083 (let ((bmp (buffer-modified-p)))
5084 (org-table-map-tables 'org-table-align)
5085 (set-buffer-modified-p bmp)))
5086 (org-cycle-hide-drawers 'all)
5087 (cond
5088 ((eq org-startup-folded t)
5089 (org-cycle '(4)))
5090 ((eq org-startup-folded 'content)
5091 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5092 (org-cycle '(4)) (org-cycle '(4)))))))
5094 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5096 (defsubst org-call-with-arg (command arg)
5097 "Call COMMAND interactively, but pretend prefix are was ARG."
5098 (let ((current-prefix-arg arg)) (call-interactively command)))
5100 (defsubst org-current-line (&optional pos)
5101 (save-excursion
5102 (and pos (goto-char pos))
5103 ;; works also in narrowed buffer, because we start at 1, not point-min
5104 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5106 (defun org-current-time ()
5107 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5108 (if (> (car org-time-stamp-rounding-minutes) 1)
5109 (let ((r (car org-time-stamp-rounding-minutes))
5110 (time (decode-time)))
5111 (apply 'encode-time
5112 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5113 (nthcdr 2 time))))
5114 (current-time)))
5116 (defun org-add-props (string plist &rest props)
5117 "Add text properties to entire string, from beginning to end.
5118 PLIST may be a list of properties, PROPS are individual properties and values
5119 that will be added to PLIST. Returns the string that was modified."
5120 (add-text-properties
5121 0 (length string) (if props (append plist props) plist) string)
5122 string)
5123 (put 'org-add-props 'lisp-indent-function 2)
5126 ;;;; Font-Lock stuff, including the activators
5128 (defvar org-mouse-map (make-sparse-keymap))
5129 (org-defkey org-mouse-map
5130 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5131 (org-defkey org-mouse-map
5132 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5133 (when org-mouse-1-follows-link
5134 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5135 (when org-tab-follows-link
5136 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5137 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5138 (when org-return-follows-link
5139 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5140 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5142 (require 'font-lock)
5144 (defconst org-non-link-chars "]\t\n\r<>")
5145 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5146 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5147 (defvar org-link-re-with-space nil
5148 "Matches a link with spaces, optional angular brackets around it.")
5149 (defvar org-link-re-with-space2 nil
5150 "Matches a link with spaces, optional angular brackets around it.")
5151 (defvar org-angle-link-re nil
5152 "Matches link with angular brackets, spaces are allowed.")
5153 (defvar org-plain-link-re nil
5154 "Matches plain link, without spaces.")
5155 (defvar org-bracket-link-regexp nil
5156 "Matches a link in double brackets.")
5157 (defvar org-bracket-link-analytic-regexp nil
5158 "Regular expression used to analyze links.
5159 Here is what the match groups contain after a match:
5160 1: http:
5161 2: http
5162 3: path
5163 4: [desc]
5164 5: desc")
5165 (defvar org-any-link-re nil
5166 "Regular expression matching any link.")
5168 (defun org-make-link-regexps ()
5169 "Update the link regular expressions.
5170 This should be called after the variable `org-link-types' has changed."
5171 (setq org-link-re-with-space
5172 (concat
5173 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5174 "\\([^" org-non-link-chars " ]"
5175 "[^" org-non-link-chars "]*"
5176 "[^" org-non-link-chars " ]\\)>?")
5177 org-link-re-with-space2
5178 (concat
5179 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5180 "\\([^" org-non-link-chars " ]"
5181 "[^]\t\n\r]*"
5182 "[^" org-non-link-chars " ]\\)>?")
5183 org-angle-link-re
5184 (concat
5185 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5186 "\\([^" org-non-link-chars " ]"
5187 "[^" org-non-link-chars "]*"
5188 "\\)>")
5189 org-plain-link-re
5190 (concat
5191 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5192 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5193 org-bracket-link-regexp
5194 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5195 org-bracket-link-analytic-regexp
5196 (concat
5197 "\\[\\["
5198 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5199 "\\([^]]+\\)"
5200 "\\]"
5201 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5202 "\\]")
5203 org-any-link-re
5204 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5205 org-angle-link-re "\\)\\|\\("
5206 org-plain-link-re "\\)")))
5208 (org-make-link-regexps)
5210 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5211 "Regular expression for fast time stamp matching.")
5212 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5213 "Regular expression for fast time stamp matching.")
5214 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5215 "Regular expression matching time strings for analysis.
5216 This one does not require the space after the date.")
5217 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) \\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5218 "Regular expression matching time strings for analysis.")
5219 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5220 "Regular expression matching time stamps, with groups.")
5221 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5222 "Regular expression matching time stamps (also [..]), with groups.")
5223 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5224 "Regular expression matching a time stamp range.")
5225 (defconst org-tr-regexp-both
5226 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5227 "Regular expression matching a time stamp range.")
5228 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5229 org-ts-regexp "\\)?")
5230 "Regular expression matching a time stamp or time stamp range.")
5231 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5232 org-ts-regexp-both "\\)?")
5233 "Regular expression matching a time stamp or time stamp range.
5234 The time stamps may be either active or inactive.")
5236 (defvar org-emph-face nil)
5238 (defun org-do-emphasis-faces (limit)
5239 "Run through the buffer and add overlays to links."
5240 (let (rtn)
5241 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5242 (if (not (= (char-after (match-beginning 3))
5243 (char-after (match-beginning 4))))
5244 (progn
5245 (setq rtn t)
5246 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5247 'face
5248 (nth 1 (assoc (match-string 3)
5249 org-emphasis-alist)))
5250 (add-text-properties (match-beginning 2) (match-end 2)
5251 '(font-lock-multiline t))
5252 (when org-hide-emphasis-markers
5253 (add-text-properties (match-end 4) (match-beginning 5)
5254 '(invisible org-link))
5255 (add-text-properties (match-beginning 3) (match-end 3)
5256 '(invisible org-link)))))
5257 (backward-char 1))
5258 rtn))
5260 (defun org-emphasize (&optional char)
5261 "Insert or change an emphasis, i.e. a font like bold or italic.
5262 If there is an active region, change that region to a new emphasis.
5263 If there is no region, just insert the marker characters and position
5264 the cursor between them.
5265 CHAR should be either the marker character, or the first character of the
5266 HTML tag associated with that emphasis. If CHAR is a space, the means
5267 to remove the emphasis of the selected region.
5268 If char is not given (for example in an interactive call) it
5269 will be prompted for."
5270 (interactive)
5271 (let ((eal org-emphasis-alist) e det
5272 (erc org-emphasis-regexp-components)
5273 (prompt "")
5274 (string "") beg end move tag c s)
5275 (if (org-region-active-p)
5276 (setq beg (region-beginning) end (region-end)
5277 string (buffer-substring beg end))
5278 (setq move t))
5280 (while (setq e (pop eal))
5281 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5282 c (aref tag 0))
5283 (push (cons c (string-to-char (car e))) det)
5284 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5285 (substring tag 1)))))
5286 (unless char
5287 (message "%s" (concat "Emphasis marker or tag:" prompt))
5288 (setq char (read-char-exclusive)))
5289 (setq char (or (cdr (assoc char det)) char))
5290 (if (equal char ?\ )
5291 (setq s "" move nil)
5292 (unless (assoc (char-to-string char) org-emphasis-alist)
5293 (error "No such emphasis marker: \"%c\"" char))
5294 (setq s (char-to-string char)))
5295 (while (and (> (length string) 1)
5296 (equal (substring string 0 1) (substring string -1))
5297 (assoc (substring string 0 1) org-emphasis-alist))
5298 (setq string (substring string 1 -1)))
5299 (setq string (concat s string s))
5300 (if beg (delete-region beg end))
5301 (unless (or (bolp)
5302 (string-match (concat "[" (nth 0 erc) "\n]")
5303 (char-to-string (char-before (point)))))
5304 (insert " "))
5305 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5306 (char-to-string (char-after (point))))
5307 (insert " ") (backward-char 1))
5308 (insert string)
5309 (and move (backward-char 1))))
5311 (defconst org-nonsticky-props
5312 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5315 (defun org-activate-plain-links (limit)
5316 "Run through the buffer and add overlays to links."
5317 (catch 'exit
5318 (let (f)
5319 (while (re-search-forward org-plain-link-re limit t)
5320 (setq f (get-text-property (match-beginning 0) 'face))
5321 (if (or (eq f 'org-tag)
5322 (and (listp f) (memq 'org-tag f)))
5324 (add-text-properties (match-beginning 0) (match-end 0)
5325 (list 'mouse-face 'highlight
5326 'rear-nonsticky org-nonsticky-props
5327 'keymap org-mouse-map
5329 (throw 'exit t))))))
5331 (defun org-activate-code (limit)
5332 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5333 (unless (get-text-property (match-beginning 1) 'face)
5334 (remove-text-properties (match-beginning 0) (match-end 0)
5335 '(display t invisible t intangible t))
5336 t)))
5338 (defun org-activate-angle-links (limit)
5339 "Run through the buffer and add overlays to links."
5340 (if (re-search-forward org-angle-link-re limit t)
5341 (progn
5342 (add-text-properties (match-beginning 0) (match-end 0)
5343 (list 'mouse-face 'highlight
5344 'rear-nonsticky org-nonsticky-props
5345 'keymap org-mouse-map
5347 t)))
5349 (defmacro org-maybe-intangible (props)
5350 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5351 In emacs 21, invisible text is not avoided by the command loop, so the
5352 intangible property is needed to make sure point skips this text.
5353 In Emacs 22, this is not necessary. The intangible text property has
5354 led to problems with flyspell. These problems are fixed in flyspell.el,
5355 but we still avoid setting the property in Emacs 22 and later.
5356 We use a macro so that the test can happen at compilation time."
5357 (if (< emacs-major-version 22)
5358 `(append '(intangible t) ,props)
5359 props))
5361 (defun org-activate-bracket-links (limit)
5362 "Run through the buffer and add overlays to bracketed links."
5363 (if (re-search-forward org-bracket-link-regexp limit t)
5364 (let* ((help (concat "LINK: "
5365 (org-match-string-no-properties 1)))
5366 ;; FIXME: above we should remove the escapes.
5367 ;; but that requires another match, protecting match data,
5368 ;; a lot of overhead for font-lock.
5369 (ip (org-maybe-intangible
5370 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5371 'keymap org-mouse-map 'mouse-face 'highlight
5372 'font-lock-multiline t 'help-echo help)))
5373 (vp (list 'rear-nonsticky org-nonsticky-props
5374 'keymap org-mouse-map 'mouse-face 'highlight
5375 ' font-lock-multiline t 'help-echo help)))
5376 ;; We need to remove the invisible property here. Table narrowing
5377 ;; may have made some of this invisible.
5378 (remove-text-properties (match-beginning 0) (match-end 0)
5379 '(invisible nil))
5380 (if (match-end 3)
5381 (progn
5382 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5383 (add-text-properties (match-beginning 3) (match-end 3) vp)
5384 (add-text-properties (match-end 3) (match-end 0) ip))
5385 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5386 (add-text-properties (match-beginning 1) (match-end 1) vp)
5387 (add-text-properties (match-end 1) (match-end 0) ip))
5388 t)))
5390 (defun org-activate-dates (limit)
5391 "Run through the buffer and add overlays to dates."
5392 (if (re-search-forward org-tsr-regexp-both limit t)
5393 (progn
5394 (add-text-properties (match-beginning 0) (match-end 0)
5395 (list 'mouse-face 'highlight
5396 'rear-nonsticky org-nonsticky-props
5397 'keymap org-mouse-map))
5398 (when org-display-custom-times
5399 (if (match-end 3)
5400 (org-display-custom-time (match-beginning 3) (match-end 3)))
5401 (org-display-custom-time (match-beginning 1) (match-end 1)))
5402 t)))
5404 (defvar org-target-link-regexp nil
5405 "Regular expression matching radio targets in plain text.")
5406 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5407 "Regular expression matching a link target.")
5408 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5409 "Regular expression matching a radio target.")
5410 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5411 "Regular expression matching any target.")
5413 (defun org-activate-target-links (limit)
5414 "Run through the buffer and add overlays to target matches."
5415 (when org-target-link-regexp
5416 (let ((case-fold-search t))
5417 (if (re-search-forward org-target-link-regexp limit t)
5418 (progn
5419 (add-text-properties (match-beginning 0) (match-end 0)
5420 (list 'mouse-face 'highlight
5421 'rear-nonsticky org-nonsticky-props
5422 'keymap org-mouse-map
5423 'help-echo "Radio target link"
5424 'org-linked-text t))
5425 t)))))
5427 (defun org-update-radio-target-regexp ()
5428 "Find all radio targets in this file and update the regular expression."
5429 (interactive)
5430 (when (memq 'radio org-activate-links)
5431 (setq org-target-link-regexp
5432 (org-make-target-link-regexp (org-all-targets 'radio)))
5433 (org-restart-font-lock)))
5435 (defun org-hide-wide-columns (limit)
5436 (let (s e)
5437 (setq s (text-property-any (point) (or limit (point-max))
5438 'org-cwidth t))
5439 (when s
5440 (setq e (next-single-property-change s 'org-cwidth))
5441 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5442 (goto-char e)
5443 t)))
5445 (defvar org-latex-and-specials-regexp nil
5446 "Regular expression for highlighting export special stuff.")
5447 (defvar org-match-substring-regexp)
5448 (defvar org-match-substring-with-braces-regexp)
5449 (defvar org-export-html-special-string-regexps)
5451 (defun org-compute-latex-and-specials-regexp ()
5452 "Compute regular expression for stuff treated specially by exporters."
5453 (if (not org-highlight-latex-fragments-and-specials)
5454 (org-set-local 'org-latex-and-specials-regexp nil)
5455 (let*
5456 ((matchers (plist-get org-format-latex-options :matchers))
5457 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5458 org-latex-regexps)))
5459 (options (org-combine-plists (org-default-export-plist)
5460 (org-infile-export-plist)))
5461 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5462 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5463 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5464 (org-export-html-expand (plist-get options :expand-quoted-html))
5465 (org-export-with-special-strings (plist-get options :special-strings))
5466 (re-sub
5467 (cond
5468 ((equal org-export-with-sub-superscripts '{})
5469 (list org-match-substring-with-braces-regexp))
5470 (org-export-with-sub-superscripts
5471 (list org-match-substring-regexp))
5472 (t nil)))
5473 (re-latex
5474 (if org-export-with-LaTeX-fragments
5475 (mapcar (lambda (x) (nth 1 x)) latexs)))
5476 (re-macros
5477 (if org-export-with-TeX-macros
5478 (list (concat "\\\\"
5479 (regexp-opt
5480 (append (mapcar 'car org-html-entities)
5481 (if (boundp 'org-latex-entities)
5482 org-latex-entities nil))
5483 'words))) ; FIXME
5485 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5486 (re-special (if org-export-with-special-strings
5487 (mapcar (lambda (x) (car x))
5488 org-export-html-special-string-regexps)))
5489 (re-rest
5490 (delq nil
5491 (list
5492 (if org-export-html-expand "@<[^>\n]+>")
5493 ))))
5494 (org-set-local
5495 'org-latex-and-specials-regexp
5496 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5497 re-rest) "\\|")))))
5499 (defface org-latex-and-export-specials
5500 (let ((font (cond ((assq :inherit custom-face-attributes)
5501 '(:inherit underline))
5502 (t '(:underline t)))))
5503 `((((class grayscale) (background light))
5504 (:foreground "DimGray" ,@font))
5505 (((class grayscale) (background dark))
5506 (:foreground "LightGray" ,@font))
5507 (((class color) (background light))
5508 (:foreground "SaddleBrown"))
5509 (((class color) (background dark))
5510 (:foreground "burlywood"))
5511 (t (,@font))))
5512 "Face used to highlight math latex and other special exporter stuff."
5513 :group 'org-faces)
5515 (defun org-do-latex-and-special-faces (limit)
5516 "Run through the buffer and add overlays to links."
5517 (when org-latex-and-specials-regexp
5518 (let (rtn d)
5519 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5520 limit t))
5521 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5522 'face))
5523 '(org-code org-verbatim underline)))
5524 (progn
5525 (setq rtn t
5526 d (cond ((member (char-after (1+ (match-beginning 0)))
5527 '(?_ ?^)) 1)
5528 (t 0)))
5529 (font-lock-prepend-text-property
5530 (+ d (match-beginning 0)) (match-end 0)
5531 'face 'org-latex-and-export-specials)
5532 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5533 '(font-lock-multiline t)))))
5534 rtn)))
5536 (defun org-restart-font-lock ()
5537 "Restart font-lock-mode, to force refontification."
5538 (when (and (boundp 'font-lock-mode) font-lock-mode)
5539 (font-lock-mode -1)
5540 (font-lock-mode 1)))
5542 (defun org-all-targets (&optional radio)
5543 "Return a list of all targets in this file.
5544 With optional argument RADIO, only find radio targets."
5545 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5546 rtn)
5547 (save-excursion
5548 (goto-char (point-min))
5549 (while (re-search-forward re nil t)
5550 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5551 rtn)))
5553 (defun org-make-target-link-regexp (targets)
5554 "Make regular expression matching all strings in TARGETS.
5555 The regular expression finds the targets also if there is a line break
5556 between words."
5557 (and targets
5558 (concat
5559 "\\<\\("
5560 (mapconcat
5561 (lambda (x)
5562 (while (string-match " +" x)
5563 (setq x (replace-match "\\s-+" t t x)))
5565 targets
5566 "\\|")
5567 "\\)\\>")))
5569 (defun org-activate-tags (limit)
5570 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5571 (progn
5572 (add-text-properties (match-beginning 1) (match-end 1)
5573 (list 'mouse-face 'highlight
5574 'rear-nonsticky org-nonsticky-props
5575 'keymap org-mouse-map))
5576 t)))
5578 (defun org-outline-level ()
5579 (save-excursion
5580 (looking-at outline-regexp)
5581 (if (match-beginning 1)
5582 (+ (org-get-string-indentation (match-string 1)) 1000)
5583 (1- (- (match-end 0) (match-beginning 0))))))
5585 (defvar org-font-lock-keywords nil)
5587 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5588 "Regular expression matching a property line.")
5590 (defun org-set-font-lock-defaults ()
5591 (let* ((em org-fontify-emphasized-text)
5592 (lk org-activate-links)
5593 (org-font-lock-extra-keywords
5594 (list
5595 ;; Headlines
5596 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5597 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5598 ;; Table lines
5599 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5600 (1 'org-table t))
5601 ;; Table internals
5602 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5603 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5604 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5605 ;; Drawers
5606 (list org-drawer-regexp '(0 'org-special-keyword t))
5607 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5608 ;; Properties
5609 (list org-property-re
5610 '(1 'org-special-keyword t)
5611 '(3 'org-property-value t))
5612 (if org-format-transports-properties-p
5613 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5614 ;; Links
5615 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5616 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5617 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5618 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5619 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5620 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5621 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5622 '(org-hide-wide-columns (0 nil append))
5623 ;; TODO lines
5624 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5625 '(1 (org-get-todo-face 1) t))
5626 ;; DONE
5627 (if org-fontify-done-headline
5628 (list (concat "^[*]+ +\\<\\("
5629 (mapconcat 'regexp-quote org-done-keywords "\\|")
5630 "\\)\\(.*\\)")
5631 '(2 'org-headline-done t))
5632 nil)
5633 ;; Priorities
5634 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5635 ;; Special keywords
5636 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5637 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5638 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5639 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5640 ;; Emphasis
5641 (if em
5642 (if (featurep 'xemacs)
5643 '(org-do-emphasis-faces (0 nil append))
5644 '(org-do-emphasis-faces)))
5645 ;; Checkboxes
5646 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5647 2 'bold prepend)
5648 (if org-provide-checkbox-statistics
5649 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5650 (0 (org-get-checkbox-statistics-face) t)))
5651 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5652 '(1 'org-archived prepend))
5653 ;; Specials
5654 '(org-do-latex-and-special-faces)
5655 ;; Code
5656 '(org-activate-code (1 'org-code t))
5657 ;; COMMENT
5658 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5659 "\\|" org-quote-string "\\)\\>")
5660 '(1 'org-special-keyword t))
5661 '("^#.*" (0 'font-lock-comment-face t))
5663 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5664 ;; Now set the full font-lock-keywords
5665 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5666 (org-set-local 'font-lock-defaults
5667 '(org-font-lock-keywords t nil nil backward-paragraph))
5668 (kill-local-variable 'font-lock-keywords) nil))
5670 (defvar org-m nil)
5671 (defvar org-l nil)
5672 (defvar org-f nil)
5673 (defun org-get-level-face (n)
5674 "Get the right face for match N in font-lock matching of healdines."
5675 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5676 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5677 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5678 (cond
5679 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5680 ((eq n 2) org-f)
5681 (t (if org-level-color-stars-only nil org-f))))
5683 (defun org-get-todo-face (kwd)
5684 "Get the right face for a TODO keyword KWD.
5685 If KWD is a number, get the corresponding match group."
5686 (if (numberp kwd) (setq kwd (match-string kwd)))
5687 (or (cdr (assoc kwd org-todo-keyword-faces))
5688 (and (member kwd org-done-keywords) 'org-done)
5689 'org-todo))
5691 (defun org-unfontify-region (beg end &optional maybe_loudly)
5692 "Remove fontification and activation overlays from links."
5693 (font-lock-default-unfontify-region beg end)
5694 (let* ((buffer-undo-list t)
5695 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5696 (inhibit-modification-hooks t)
5697 deactivate-mark buffer-file-name buffer-file-truename)
5698 (remove-text-properties beg end
5699 '(mouse-face t keymap t org-linked-text t
5700 invisible t intangible t))))
5702 ;;;; Visibility cycling, including org-goto and indirect buffer
5704 ;;; Cycling
5706 (defvar org-cycle-global-status nil)
5707 (make-variable-buffer-local 'org-cycle-global-status)
5708 (defvar org-cycle-subtree-status nil)
5709 (make-variable-buffer-local 'org-cycle-subtree-status)
5711 ;;;###autoload
5712 (defun org-cycle (&optional arg)
5713 "Visibility cycling for Org-mode.
5715 - When this function is called with a prefix argument, rotate the entire
5716 buffer through 3 states (global cycling)
5717 1. OVERVIEW: Show only top-level headlines.
5718 2. CONTENTS: Show all headlines of all levels, but no body text.
5719 3. SHOW ALL: Show everything.
5721 - When point is at the beginning of a headline, rotate the subtree started
5722 by this line through 3 different states (local cycling)
5723 1. FOLDED: Only the main headline is shown.
5724 2. CHILDREN: The main headline and the direct children are shown.
5725 From this state, you can move to one of the children
5726 and zoom in further.
5727 3. SUBTREE: Show the entire subtree, including body text.
5729 - When there is a numeric prefix, go up to a heading with level ARG, do
5730 a `show-subtree' and return to the previous cursor position. If ARG
5731 is negative, go up that many levels.
5733 - When point is not at the beginning of a headline, execute
5734 `indent-relative', like TAB normally does. See the option
5735 `org-cycle-emulate-tab' for details.
5737 - Special case: if point is at the beginning of the buffer and there is
5738 no headline in line 1, this function will act as if called with prefix arg.
5739 But only if also the variable `org-cycle-global-at-bob' is t."
5740 (interactive "P")
5741 (let* ((outline-regexp
5742 (if (and (org-mode-p) org-cycle-include-plain-lists)
5743 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5744 outline-regexp))
5745 (bob-special (and org-cycle-global-at-bob (bobp)
5746 (not (looking-at outline-regexp))))
5747 (org-cycle-hook
5748 (if bob-special
5749 (delq 'org-optimize-window-after-visibility-change
5750 (copy-sequence org-cycle-hook))
5751 org-cycle-hook))
5752 (pos (point)))
5754 (if (or bob-special (equal arg '(4)))
5755 ;; special case: use global cycling
5756 (setq arg t))
5758 (cond
5760 ((org-at-table-p 'any)
5761 ;; Enter the table or move to the next field in the table
5762 (or (org-table-recognize-table.el)
5763 (progn
5764 (if arg (org-table-edit-field t)
5765 (org-table-justify-field-maybe)
5766 (call-interactively 'org-table-next-field)))))
5768 ((eq arg t) ;; Global cycling
5770 (cond
5771 ((and (eq last-command this-command)
5772 (eq org-cycle-global-status 'overview))
5773 ;; We just created the overview - now do table of contents
5774 ;; This can be slow in very large buffers, so indicate action
5775 (message "CONTENTS...")
5776 (org-content)
5777 (message "CONTENTS...done")
5778 (setq org-cycle-global-status 'contents)
5779 (run-hook-with-args 'org-cycle-hook 'contents))
5781 ((and (eq last-command this-command)
5782 (eq org-cycle-global-status 'contents))
5783 ;; We just showed the table of contents - now show everything
5784 (show-all)
5785 (message "SHOW ALL")
5786 (setq org-cycle-global-status 'all)
5787 (run-hook-with-args 'org-cycle-hook 'all))
5790 ;; Default action: go to overview
5791 (org-overview)
5792 (message "OVERVIEW")
5793 (setq org-cycle-global-status 'overview)
5794 (run-hook-with-args 'org-cycle-hook 'overview))))
5796 ((and org-drawers org-drawer-regexp
5797 (save-excursion
5798 (beginning-of-line 1)
5799 (looking-at org-drawer-regexp)))
5800 ;; Toggle block visibility
5801 (org-flag-drawer
5802 (not (get-char-property (match-end 0) 'invisible))))
5804 ((integerp arg)
5805 ;; Show-subtree, ARG levels up from here.
5806 (save-excursion
5807 (org-back-to-heading)
5808 (outline-up-heading (if (< arg 0) (- arg)
5809 (- (funcall outline-level) arg)))
5810 (org-show-subtree)))
5812 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5813 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5814 ;; At a heading: rotate between three different views
5815 (org-back-to-heading)
5816 (let ((goal-column 0) eoh eol eos)
5817 ;; First, some boundaries
5818 (save-excursion
5819 (org-back-to-heading)
5820 (save-excursion
5821 (beginning-of-line 2)
5822 (while (and (not (eobp)) ;; this is like `next-line'
5823 (get-char-property (1- (point)) 'invisible))
5824 (beginning-of-line 2)) (setq eol (point)))
5825 (outline-end-of-heading) (setq eoh (point))
5826 (org-end-of-subtree t)
5827 (unless (eobp)
5828 (skip-chars-forward " \t\n")
5829 (beginning-of-line 1) ; in case this is an item
5831 (setq eos (1- (point))))
5832 ;; Find out what to do next and set `this-command'
5833 (cond
5834 ((= eos eoh)
5835 ;; Nothing is hidden behind this heading
5836 (message "EMPTY ENTRY")
5837 (setq org-cycle-subtree-status nil)
5838 (save-excursion
5839 (goto-char eos)
5840 (outline-next-heading)
5841 (if (org-invisible-p) (org-flag-heading nil))))
5842 ((or (>= eol eos)
5843 (not (string-match "\\S-" (buffer-substring eol eos))))
5844 ;; Entire subtree is hidden in one line: open it
5845 (org-show-entry)
5846 (show-children)
5847 (message "CHILDREN")
5848 (save-excursion
5849 (goto-char eos)
5850 (outline-next-heading)
5851 (if (org-invisible-p) (org-flag-heading nil)))
5852 (setq org-cycle-subtree-status 'children)
5853 (run-hook-with-args 'org-cycle-hook 'children))
5854 ((and (eq last-command this-command)
5855 (eq org-cycle-subtree-status 'children))
5856 ;; We just showed the children, now show everything.
5857 (org-show-subtree)
5858 (message "SUBTREE")
5859 (setq org-cycle-subtree-status 'subtree)
5860 (run-hook-with-args 'org-cycle-hook 'subtree))
5862 ;; Default action: hide the subtree.
5863 (hide-subtree)
5864 (message "FOLDED")
5865 (setq org-cycle-subtree-status 'folded)
5866 (run-hook-with-args 'org-cycle-hook 'folded)))))
5868 ;; TAB emulation
5869 (buffer-read-only (org-back-to-heading))
5871 ((org-try-cdlatex-tab))
5873 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5874 (or (not (bolp))
5875 (not (looking-at outline-regexp))))
5876 (call-interactively (global-key-binding "\t")))
5878 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5879 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5880 (or (and (eq org-cycle-emulate-tab 'white)
5881 (= (match-end 0) (point-at-eol)))
5882 (and (eq org-cycle-emulate-tab 'whitestart)
5883 (>= (match-end 0) pos))))
5885 (eq org-cycle-emulate-tab t))
5886 ; (if (and (looking-at "[ \n\r\t]")
5887 ; (string-match "^[ \t]*$" (buffer-substring
5888 ; (point-at-bol) (point))))
5889 ; (progn
5890 ; (beginning-of-line 1)
5891 ; (and (looking-at "[ \t]+") (replace-match ""))))
5892 (call-interactively (global-key-binding "\t")))
5894 (t (save-excursion
5895 (org-back-to-heading)
5896 (org-cycle))))))
5898 ;;;###autoload
5899 (defun org-global-cycle (&optional arg)
5900 "Cycle the global visibility. For details see `org-cycle'."
5901 (interactive "P")
5902 (let ((org-cycle-include-plain-lists
5903 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5904 (if (integerp arg)
5905 (progn
5906 (show-all)
5907 (hide-sublevels arg)
5908 (setq org-cycle-global-status 'contents))
5909 (org-cycle '(4)))))
5911 (defun org-overview ()
5912 "Switch to overview mode, shoing only top-level headlines.
5913 Really, this shows all headlines with level equal or greater than the level
5914 of the first headline in the buffer. This is important, because if the
5915 first headline is not level one, then (hide-sublevels 1) gives confusing
5916 results."
5917 (interactive)
5918 (let ((level (save-excursion
5919 (goto-char (point-min))
5920 (if (re-search-forward (concat "^" outline-regexp) nil t)
5921 (progn
5922 (goto-char (match-beginning 0))
5923 (funcall outline-level))))))
5924 (and level (hide-sublevels level))))
5926 (defun org-content (&optional arg)
5927 "Show all headlines in the buffer, like a table of contents.
5928 With numerical argument N, show content up to level N."
5929 (interactive "P")
5930 (save-excursion
5931 ;; Visit all headings and show their offspring
5932 (and (integerp arg) (org-overview))
5933 (goto-char (point-max))
5934 (catch 'exit
5935 (while (and (progn (condition-case nil
5936 (outline-previous-visible-heading 1)
5937 (error (goto-char (point-min))))
5939 (looking-at outline-regexp))
5940 (if (integerp arg)
5941 (show-children (1- arg))
5942 (show-branches))
5943 (if (bobp) (throw 'exit nil))))))
5946 (defun org-optimize-window-after-visibility-change (state)
5947 "Adjust the window after a change in outline visibility.
5948 This function is the default value of the hook `org-cycle-hook'."
5949 (when (get-buffer-window (current-buffer))
5950 (cond
5951 ; ((eq state 'overview) (org-first-headline-recenter 1))
5952 ; ((eq state 'overview) (org-beginning-of-line))
5953 ((eq state 'content) nil)
5954 ((eq state 'all) nil)
5955 ((eq state 'folded) nil)
5956 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5957 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5959 (defun org-compact-display-after-subtree-move ()
5960 (let (beg end)
5961 (save-excursion
5962 (if (org-up-heading-safe)
5963 (progn
5964 (hide-subtree)
5965 (show-entry)
5966 (show-children)
5967 (org-cycle-show-empty-lines 'children)
5968 (org-cycle-hide-drawers 'children))
5969 (org-overview)))))
5971 (defun org-cycle-show-empty-lines (state)
5972 "Show empty lines above all visible headlines.
5973 The region to be covered depends on STATE when called through
5974 `org-cycle-hook'. Lisp program can use t for STATE to get the
5975 entire buffer covered. Note that an empty line is only shown if there
5976 are at least `org-cycle-separator-lines' empty lines before the headeline."
5977 (when (> org-cycle-separator-lines 0)
5978 (save-excursion
5979 (let* ((n org-cycle-separator-lines)
5980 (re (cond
5981 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5982 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5983 (t (let ((ns (number-to-string (- n 2))))
5984 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5985 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5986 beg end)
5987 (cond
5988 ((memq state '(overview contents t))
5989 (setq beg (point-min) end (point-max)))
5990 ((memq state '(children folded))
5991 (setq beg (point) end (progn (org-end-of-subtree t t)
5992 (beginning-of-line 2)
5993 (point)))))
5994 (when beg
5995 (goto-char beg)
5996 (while (re-search-forward re end t)
5997 (if (not (get-char-property (match-end 1) 'invisible))
5998 (outline-flag-region
5999 (match-beginning 1) (match-end 1) nil)))))))
6000 ;; Never hide empty lines at the end of the file.
6001 (save-excursion
6002 (goto-char (point-max))
6003 (outline-previous-heading)
6004 (outline-end-of-heading)
6005 (if (and (looking-at "[ \t\n]+")
6006 (= (match-end 0) (point-max)))
6007 (outline-flag-region (point) (match-end 0) nil))))
6009 (defun org-subtree-end-visible-p ()
6010 "Is the end of the current subtree visible?"
6011 (pos-visible-in-window-p
6012 (save-excursion (org-end-of-subtree t) (point))))
6014 (defun org-first-headline-recenter (&optional N)
6015 "Move cursor to the first headline and recenter the headline.
6016 Optional argument N means, put the headline into the Nth line of the window."
6017 (goto-char (point-min))
6018 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6019 (beginning-of-line)
6020 (recenter (prefix-numeric-value N))))
6022 ;;; Org-goto
6024 (defvar org-goto-window-configuration nil)
6025 (defvar org-goto-marker nil)
6026 (defvar org-goto-map
6027 (let ((map (make-sparse-keymap)))
6028 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6029 (while (setq cmd (pop cmds))
6030 (substitute-key-definition cmd cmd map global-map)))
6031 (suppress-keymap map)
6032 (org-defkey map "\C-m" 'org-goto-ret)
6033 (org-defkey map [(return)] 'org-goto-ret)
6034 (org-defkey map [(left)] 'org-goto-left)
6035 (org-defkey map [(right)] 'org-goto-right)
6036 (org-defkey map [(control ?g)] 'org-goto-quit)
6037 (org-defkey map "\C-i" 'org-cycle)
6038 (org-defkey map [(tab)] 'org-cycle)
6039 (org-defkey map [(down)] 'outline-next-visible-heading)
6040 (org-defkey map [(up)] 'outline-previous-visible-heading)
6041 (if org-goto-auto-isearch
6042 (if (fboundp 'define-key-after)
6043 (define-key-after map [t] 'org-goto-local-auto-isearch)
6044 nil)
6045 (org-defkey map "q" 'org-goto-quit)
6046 (org-defkey map "n" 'outline-next-visible-heading)
6047 (org-defkey map "p" 'outline-previous-visible-heading)
6048 (org-defkey map "f" 'outline-forward-same-level)
6049 (org-defkey map "b" 'outline-backward-same-level)
6050 (org-defkey map "u" 'outline-up-heading))
6051 (org-defkey map "/" 'org-occur)
6052 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6053 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6054 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6055 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6056 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6057 map))
6059 (defconst org-goto-help
6060 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6061 RET=jump to location [Q]uit and return to previous location
6062 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6064 (defvar org-goto-start-pos) ; dynamically scoped parameter
6066 (defun org-goto (&optional alternative-interface)
6067 "Look up a different location in the current file, keeping current visibility.
6069 When you want look-up or go to a different location in a document, the
6070 fastest way is often to fold the entire buffer and then dive into the tree.
6071 This method has the disadvantage, that the previous location will be folded,
6072 which may not be what you want.
6074 This command works around this by showing a copy of the current buffer
6075 in an indirect buffer, in overview mode. You can dive into the tree in
6076 that copy, use org-occur and incremental search to find a location.
6077 When pressing RET or `Q', the command returns to the original buffer in
6078 which the visibility is still unchanged. After RET is will also jump to
6079 the location selected in the indirect buffer and expose the
6080 the headline hierarchy above."
6081 (interactive "P")
6082 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6083 (org-refile-use-outline-path t)
6084 (interface
6085 (if (not alternative-interface)
6086 org-goto-interface
6087 (if (eq org-goto-interface 'outline)
6088 'outline-path-completion
6089 'outline)))
6090 (org-goto-start-pos (point))
6091 (selected-point
6092 (if (eq interface 'outline)
6093 (car (org-get-location (current-buffer) org-goto-help))
6094 (nth 3 (org-refile-get-location "Goto: ")))))
6095 (if selected-point
6096 (progn
6097 (org-mark-ring-push org-goto-start-pos)
6098 (goto-char selected-point)
6099 (if (or (org-invisible-p) (org-invisible-p2))
6100 (org-show-context 'org-goto)))
6101 (message "Quit"))))
6103 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6104 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6105 (defvar org-goto-local-auto-isearch-map) ; defined below
6107 (defun org-get-location (buf help)
6108 "Let the user select a location in the Org-mode buffer BUF.
6109 This function uses a recursive edit. It returns the selected position
6110 or nil."
6111 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6112 (isearch-hide-immediately nil)
6113 (isearch-search-fun-function
6114 (lambda () 'org-goto-local-search-forward-headings))
6115 (org-goto-selected-point org-goto-exit-command))
6116 (save-excursion
6117 (save-window-excursion
6118 (delete-other-windows)
6119 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6120 (switch-to-buffer
6121 (condition-case nil
6122 (make-indirect-buffer (current-buffer) "*org-goto*")
6123 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6124 (with-output-to-temp-buffer "*Help*"
6125 (princ help))
6126 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6127 (setq buffer-read-only nil)
6128 (let ((org-startup-truncated t)
6129 (org-startup-folded nil)
6130 (org-startup-align-all-tables nil))
6131 (org-mode)
6132 (org-overview))
6133 (setq buffer-read-only t)
6134 (if (and (boundp 'org-goto-start-pos)
6135 (integer-or-marker-p org-goto-start-pos))
6136 (let ((org-show-hierarchy-above t)
6137 (org-show-siblings t)
6138 (org-show-following-heading t))
6139 (goto-char org-goto-start-pos)
6140 (and (org-invisible-p) (org-show-context)))
6141 (goto-char (point-min)))
6142 (org-beginning-of-line)
6143 (message "Select location and press RET")
6144 (use-local-map org-goto-map)
6145 (recursive-edit)
6147 (kill-buffer "*org-goto*")
6148 (cons org-goto-selected-point org-goto-exit-command)))
6150 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6151 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6152 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6153 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6155 (defun org-goto-local-search-forward-headings (string bound noerror)
6156 "Search and make sure that anu matches are in headlines."
6157 (catch 'return
6158 (while (search-forward string bound noerror)
6159 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6160 (and (member :headline context)
6161 (not (member :tags context))))
6162 (throw 'return (point))))))
6164 (defun org-goto-local-auto-isearch ()
6165 "Start isearch."
6166 (interactive)
6167 (goto-char (point-min))
6168 (let ((keys (this-command-keys)))
6169 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6170 (isearch-mode t)
6171 (isearch-process-search-char (string-to-char keys)))))
6173 (defun org-goto-ret (&optional arg)
6174 "Finish `org-goto' by going to the new location."
6175 (interactive "P")
6176 (setq org-goto-selected-point (point)
6177 org-goto-exit-command 'return)
6178 (throw 'exit nil))
6180 (defun org-goto-left ()
6181 "Finish `org-goto' by going to the new location."
6182 (interactive)
6183 (if (org-on-heading-p)
6184 (progn
6185 (beginning-of-line 1)
6186 (setq org-goto-selected-point (point)
6187 org-goto-exit-command 'left)
6188 (throw 'exit nil))
6189 (error "Not on a heading")))
6191 (defun org-goto-right ()
6192 "Finish `org-goto' by going to the new location."
6193 (interactive)
6194 (if (org-on-heading-p)
6195 (progn
6196 (setq org-goto-selected-point (point)
6197 org-goto-exit-command 'right)
6198 (throw 'exit nil))
6199 (error "Not on a heading")))
6201 (defun org-goto-quit ()
6202 "Finish `org-goto' without cursor motion."
6203 (interactive)
6204 (setq org-goto-selected-point nil)
6205 (setq org-goto-exit-command 'quit)
6206 (throw 'exit nil))
6208 ;;; Indirect buffer display of subtrees
6210 (defvar org-indirect-dedicated-frame nil
6211 "This is the frame being used for indirect tree display.")
6212 (defvar org-last-indirect-buffer nil)
6214 (defun org-tree-to-indirect-buffer (&optional arg)
6215 "Create indirect buffer and narrow it to current subtree.
6216 With numerical prefix ARG, go up to this level and then take that tree.
6217 If ARG is negative, go up that many levels.
6218 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6219 indirect buffer previously made with this command, to avoid proliferation of
6220 indirect buffers. However, when you call the command with a `C-u' prefix, or
6221 when `org-indirect-buffer-display' is `new-frame', the last buffer
6222 is kept so that you can work with several indirect buffers at the same time.
6223 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6224 requests that a new frame be made for the new buffer, so that the dedicated
6225 frame is not changed."
6226 (interactive "P")
6227 (let ((cbuf (current-buffer))
6228 (cwin (selected-window))
6229 (pos (point))
6230 beg end level heading ibuf)
6231 (save-excursion
6232 (org-back-to-heading t)
6233 (when (numberp arg)
6234 (setq level (org-outline-level))
6235 (if (< arg 0) (setq arg (+ level arg)))
6236 (while (> (setq level (org-outline-level)) arg)
6237 (outline-up-heading 1 t)))
6238 (setq beg (point)
6239 heading (org-get-heading))
6240 (org-end-of-subtree t) (setq end (point)))
6241 (if (and (buffer-live-p org-last-indirect-buffer)
6242 (not (eq org-indirect-buffer-display 'new-frame))
6243 (not arg))
6244 (kill-buffer org-last-indirect-buffer))
6245 (setq ibuf (org-get-indirect-buffer cbuf)
6246 org-last-indirect-buffer ibuf)
6247 (cond
6248 ((or (eq org-indirect-buffer-display 'new-frame)
6249 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6250 (select-frame (make-frame))
6251 (delete-other-windows)
6252 (switch-to-buffer ibuf)
6253 (org-set-frame-title heading))
6254 ((eq org-indirect-buffer-display 'dedicated-frame)
6255 (raise-frame
6256 (select-frame (or (and org-indirect-dedicated-frame
6257 (frame-live-p org-indirect-dedicated-frame)
6258 org-indirect-dedicated-frame)
6259 (setq org-indirect-dedicated-frame (make-frame)))))
6260 (delete-other-windows)
6261 (switch-to-buffer ibuf)
6262 (org-set-frame-title (concat "Indirect: " heading)))
6263 ((eq org-indirect-buffer-display 'current-window)
6264 (switch-to-buffer ibuf))
6265 ((eq org-indirect-buffer-display 'other-window)
6266 (pop-to-buffer ibuf))
6267 (t (error "Invalid value.")))
6268 (if (featurep 'xemacs)
6269 (save-excursion (org-mode) (turn-on-font-lock)))
6270 (narrow-to-region beg end)
6271 (show-all)
6272 (goto-char pos)
6273 (and (window-live-p cwin) (select-window cwin))))
6275 (defun org-get-indirect-buffer (&optional buffer)
6276 (setq buffer (or buffer (current-buffer)))
6277 (let ((n 1) (base (buffer-name buffer)) bname)
6278 (while (buffer-live-p
6279 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6280 (setq n (1+ n)))
6281 (condition-case nil
6282 (make-indirect-buffer buffer bname 'clone)
6283 (error (make-indirect-buffer buffer bname)))))
6285 (defun org-set-frame-title (title)
6286 "Set the title of the current frame to the string TITLE."
6287 ;; FIXME: how to name a single frame in XEmacs???
6288 (unless (featurep 'xemacs)
6289 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6291 ;;;; Structure editing
6293 ;;; Inserting headlines
6295 (defun org-insert-heading (&optional force-heading)
6296 "Insert a new heading or item with same depth at point.
6297 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6298 If point is at the beginning of a headline, insert a sibling before the
6299 current headline. If point is not at the beginning, do not split the line,
6300 but create the new hedline after the current line."
6301 (interactive "P")
6302 (if (= (buffer-size) 0)
6303 (insert "\n* ")
6304 (when (or force-heading (not (org-insert-item)))
6305 (let* ((head (save-excursion
6306 (condition-case nil
6307 (progn
6308 (org-back-to-heading)
6309 (match-string 0))
6310 (error "*"))))
6311 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6312 pos)
6313 (cond
6314 ((and (org-on-heading-p) (bolp)
6315 (or (bobp)
6316 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6317 ;; insert before the current line
6318 (open-line (if blank 2 1)))
6319 ((and (bolp)
6320 (or (bobp)
6321 (save-excursion
6322 (backward-char 1) (not (org-invisible-p)))))
6323 ;; insert right here
6324 nil)
6326 ; ;; in the middle of the line
6327 ; (org-show-entry)
6328 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6329 ; (if (and
6330 ; (org-on-heading-p)
6331 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6332 ; ;; protect the tags
6333 ;; (let ((tags (match-string 2)) pos)
6334 ; (delete-region (match-beginning 1) (match-end 1))
6335 ; (setq pos (point-at-bol))
6336 ; (newline (if blank 2 1))
6337 ; (save-excursion
6338 ; (goto-char pos)
6339 ; (end-of-line 1)
6340 ; (insert " " tags)
6341 ; (org-set-tags nil 'align)))
6342 ; (newline (if blank 2 1)))
6343 ; (newline (if blank 2 1))))
6346 ;; in the middle of the line
6347 (org-show-entry)
6348 (let ((split
6349 (org-get-alist-option org-M-RET-may-split-line 'headline))
6350 tags pos)
6351 (if (org-on-heading-p)
6352 (progn
6353 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6354 (setq tags (and (match-end 2) (match-string 2)))
6355 (and (match-end 1)
6356 (delete-region (match-beginning 1) (match-end 1)))
6357 (setq pos (point-at-bol))
6358 (or split (end-of-line 1))
6359 (delete-horizontal-space)
6360 (newline (if blank 2 1))
6361 (when tags
6362 (save-excursion
6363 (goto-char pos)
6364 (end-of-line 1)
6365 (insert " " tags)
6366 (org-set-tags nil 'align))))
6367 (or split (end-of-line 1))
6368 (newline (if blank 2 1))))))
6369 (insert head) (just-one-space)
6370 (setq pos (point))
6371 (end-of-line 1)
6372 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6373 (run-hooks 'org-insert-heading-hook)))))
6375 (defun org-insert-heading-after-current ()
6376 "Insert a new heading with same level as current, after current subtree."
6377 (interactive)
6378 (org-back-to-heading)
6379 (org-insert-heading)
6380 (org-move-subtree-down)
6381 (end-of-line 1))
6383 (defun org-insert-todo-heading (arg)
6384 "Insert a new heading with the same level and TODO state as current heading.
6385 If the heading has no TODO state, or if the state is DONE, use the first
6386 state (TODO by default). Also with prefix arg, force first state."
6387 (interactive "P")
6388 (when (not (org-insert-item 'checkbox))
6389 (org-insert-heading)
6390 (save-excursion
6391 (org-back-to-heading)
6392 (outline-previous-heading)
6393 (looking-at org-todo-line-regexp))
6394 (if (or arg
6395 (not (match-beginning 2))
6396 (member (match-string 2) org-done-keywords))
6397 (insert (car org-todo-keywords-1) " ")
6398 (insert (match-string 2) " "))))
6400 (defun org-insert-subheading (arg)
6401 "Insert a new subheading and demote it.
6402 Works for outline headings and for plain lists alike."
6403 (interactive "P")
6404 (org-insert-heading arg)
6405 (cond
6406 ((org-on-heading-p) (org-do-demote))
6407 ((org-at-item-p) (org-indent-item 1))))
6409 (defun org-insert-todo-subheading (arg)
6410 "Insert a new subheading with TODO keyword or checkbox and demote it.
6411 Works for outline headings and for plain lists alike."
6412 (interactive "P")
6413 (org-insert-todo-heading arg)
6414 (cond
6415 ((org-on-heading-p) (org-do-demote))
6416 ((org-at-item-p) (org-indent-item 1))))
6418 ;;; Promotion and Demotion
6420 (defun org-promote-subtree ()
6421 "Promote the entire subtree.
6422 See also `org-promote'."
6423 (interactive)
6424 (save-excursion
6425 (org-map-tree 'org-promote))
6426 (org-fix-position-after-promote))
6428 (defun org-demote-subtree ()
6429 "Demote the entire subtree. See `org-demote'.
6430 See also `org-promote'."
6431 (interactive)
6432 (save-excursion
6433 (org-map-tree 'org-demote))
6434 (org-fix-position-after-promote))
6437 (defun org-do-promote ()
6438 "Promote the current heading higher up the tree.
6439 If the region is active in `transient-mark-mode', promote all headings
6440 in the region."
6441 (interactive)
6442 (save-excursion
6443 (if (org-region-active-p)
6444 (org-map-region 'org-promote (region-beginning) (region-end))
6445 (org-promote)))
6446 (org-fix-position-after-promote))
6448 (defun org-do-demote ()
6449 "Demote the current heading lower down the tree.
6450 If the region is active in `transient-mark-mode', demote all headings
6451 in the region."
6452 (interactive)
6453 (save-excursion
6454 (if (org-region-active-p)
6455 (org-map-region 'org-demote (region-beginning) (region-end))
6456 (org-demote)))
6457 (org-fix-position-after-promote))
6459 (defun org-fix-position-after-promote ()
6460 "Make sure that after pro/demotion cursor position is right."
6461 (let ((pos (point)))
6462 (when (save-excursion
6463 (beginning-of-line 1)
6464 (looking-at org-todo-line-regexp)
6465 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6466 (cond ((eobp) (insert " "))
6467 ((eolp) (insert " "))
6468 ((equal (char-after) ?\ ) (forward-char 1))))))
6470 (defun org-reduced-level (l)
6471 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6473 (defun org-get-legal-level (level &optional change)
6474 "Rectify a level change under the influence of `org-odd-levels-only'
6475 LEVEL is a current level, CHANGE is by how much the level should be
6476 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6477 even level numbers will become the next higher odd number."
6478 (if org-odd-levels-only
6479 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6480 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6481 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6482 (max 1 (+ level change))))
6484 (defun org-promote ()
6485 "Promote the current heading higher up the tree.
6486 If the region is active in `transient-mark-mode', promote all headings
6487 in the region."
6488 (org-back-to-heading t)
6489 (let* ((level (save-match-data (funcall outline-level)))
6490 (up-head (concat (make-string (org-get-legal-level level -1) ?*) " "))
6491 (diff (abs (- level (length up-head) -1))))
6492 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6493 (replace-match up-head nil t)
6494 ;; Fixup tag positioning
6495 (and org-auto-align-tags (org-set-tags nil t))
6496 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6498 (defun org-demote ()
6499 "Demote the current heading lower down the tree.
6500 If the region is active in `transient-mark-mode', demote all headings
6501 in the region."
6502 (org-back-to-heading t)
6503 (let* ((level (save-match-data (funcall outline-level)))
6504 (down-head (concat (make-string (org-get-legal-level level 1) ?*) " "))
6505 (diff (abs (- level (length down-head) -1))))
6506 (replace-match down-head nil t)
6507 ;; Fixup tag positioning
6508 (and org-auto-align-tags (org-set-tags nil t))
6509 (if org-adapt-indentation (org-fixup-indentation diff))))
6511 (defun org-map-tree (fun)
6512 "Call FUN for every heading underneath the current one."
6513 (org-back-to-heading)
6514 (let ((level (funcall outline-level)))
6515 (save-excursion
6516 (funcall fun)
6517 (while (and (progn
6518 (outline-next-heading)
6519 (> (funcall outline-level) level))
6520 (not (eobp)))
6521 (funcall fun)))))
6523 (defun org-map-region (fun beg end)
6524 "Call FUN for every heading between BEG and END."
6525 (let ((org-ignore-region t))
6526 (save-excursion
6527 (setq end (copy-marker end))
6528 (goto-char beg)
6529 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6530 (< (point) end))
6531 (funcall fun))
6532 (while (and (progn
6533 (outline-next-heading)
6534 (< (point) end))
6535 (not (eobp)))
6536 (funcall fun)))))
6538 (defun org-fixup-indentation (diff)
6539 "Change the indentation in the current entry by DIFF
6540 However, if any line in the current entry has no indentation, or if it
6541 would end up with no indentation after the change, nothing at all is done."
6542 (save-excursion
6543 (let ((end (save-excursion (outline-next-heading)
6544 (point-marker)))
6545 (prohibit (if (> diff 0)
6546 "^\\S-"
6547 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6548 col)
6549 (unless (save-excursion (end-of-line 1)
6550 (re-search-forward prohibit end t))
6551 (while (and (< (point) end)
6552 (re-search-forward "^[ \t]+" end t))
6553 (goto-char (match-end 0))
6554 (setq col (current-column))
6555 (if (< diff 0) (replace-match ""))
6556 (indent-to (+ diff col))))
6557 (move-marker end nil))))
6559 (defun org-convert-to-odd-levels ()
6560 "Convert an org-mode file with all levels allowed to one with odd levels.
6561 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6562 level 5 etc."
6563 (interactive)
6564 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6565 (let ((org-odd-levels-only nil) n)
6566 (save-excursion
6567 (goto-char (point-min))
6568 (while (re-search-forward "^\\*\\*+ " nil t)
6569 (setq n (- (length (match-string 0)) 2))
6570 (while (>= (setq n (1- n)) 0)
6571 (org-demote))
6572 (end-of-line 1))))))
6575 (defun org-convert-to-oddeven-levels ()
6576 "Convert an org-mode file with only odd levels to one with odd and even levels.
6577 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6578 section with an even level, conversion would destroy the structure of the file. An error
6579 is signaled in this case."
6580 (interactive)
6581 (goto-char (point-min))
6582 ;; First check if there are no even levels
6583 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6584 (org-show-context t)
6585 (error "Not all levels are odd in this file. Conversion not possible."))
6586 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6587 (let ((org-odd-levels-only nil) n)
6588 (save-excursion
6589 (goto-char (point-min))
6590 (while (re-search-forward "^\\*\\*+ " nil t)
6591 (setq n (/ (1- (length (match-string 0))) 2))
6592 (while (>= (setq n (1- n)) 0)
6593 (org-promote))
6594 (end-of-line 1))))))
6596 (defun org-tr-level (n)
6597 "Make N odd if required."
6598 (if org-odd-levels-only (1+ (/ n 2)) n))
6600 ;;; Vertical tree motion, cutting and pasting of subtrees
6602 (defun org-move-subtree-up (&optional arg)
6603 "Move the current subtree up past ARG headlines of the same level."
6604 (interactive "p")
6605 (org-move-subtree-down (- (prefix-numeric-value arg))))
6607 (defun org-move-subtree-down (&optional arg)
6608 "Move the current subtree down past ARG headlines of the same level."
6609 (interactive "p")
6610 (setq arg (prefix-numeric-value arg))
6611 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6612 'outline-get-last-sibling))
6613 (ins-point (make-marker))
6614 (cnt (abs arg))
6615 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6616 ;; Select the tree
6617 (org-back-to-heading)
6618 (setq beg0 (point))
6619 (save-excursion
6620 (setq ne-beg (org-back-over-empty-lines))
6621 (setq beg (point)))
6622 (save-match-data
6623 (save-excursion (outline-end-of-heading)
6624 (setq folded (org-invisible-p)))
6625 (outline-end-of-subtree))
6626 (outline-next-heading)
6627 (setq ne-end (org-back-over-empty-lines))
6628 (setq end (point))
6629 (goto-char beg0)
6630 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6631 ;; include less whitespace
6632 (save-excursion
6633 (goto-char beg)
6634 (forward-line (- ne-beg ne-end))
6635 (setq beg (point))))
6636 ;; Find insertion point, with error handling
6637 (while (> cnt 0)
6638 (or (and (funcall movfunc) (looking-at outline-regexp))
6639 (progn (goto-char beg0)
6640 (error "Cannot move past superior level or buffer limit")))
6641 (setq cnt (1- cnt)))
6642 (if (> arg 0)
6643 ;; Moving forward - still need to move over subtree
6644 (progn (org-end-of-subtree t t)
6645 (save-excursion
6646 (org-back-over-empty-lines)
6647 (or (bolp) (newline)))))
6648 (setq ne-ins (org-back-over-empty-lines))
6649 (move-marker ins-point (point))
6650 (setq txt (buffer-substring beg end))
6651 (delete-region beg end)
6652 (outline-flag-region (1- beg) beg nil)
6653 (outline-flag-region (1- (point)) (point) nil)
6654 (insert txt)
6655 (or (bolp) (insert "\n"))
6656 (setq ins-end (point))
6657 (goto-char ins-point)
6658 (org-skip-whitespace)
6659 (when (and (< arg 0)
6660 (org-first-sibling-p)
6661 (> ne-ins ne-beg))
6662 ;; Move whitespace back to beginning
6663 (save-excursion
6664 (goto-char ins-end)
6665 (let ((kill-whole-line t))
6666 (kill-line (- ne-ins ne-beg)) (point)))
6667 (insert (make-string (- ne-ins ne-beg) ?\n)))
6668 (move-marker ins-point nil)
6669 (org-compact-display-after-subtree-move)
6670 (unless folded
6671 (org-show-entry)
6672 (show-children)
6673 (org-cycle-hide-drawers 'children))))
6675 (defvar org-subtree-clip ""
6676 "Clipboard for cut and paste of subtrees.
6677 This is actually only a copy of the kill, because we use the normal kill
6678 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6680 (defvar org-subtree-clip-folded nil
6681 "Was the last copied subtree folded?
6682 This is used to fold the tree back after pasting.")
6684 (defun org-cut-subtree (&optional n)
6685 "Cut the current subtree into the clipboard.
6686 With prefix arg N, cut this many sequential subtrees.
6687 This is a short-hand for marking the subtree and then cutting it."
6688 (interactive "p")
6689 (org-copy-subtree n 'cut))
6691 (defun org-copy-subtree (&optional n cut)
6692 "Cut the current subtree into the clipboard.
6693 With prefix arg N, cut this many sequential subtrees.
6694 This is a short-hand for marking the subtree and then copying it.
6695 If CUT is non-nil, actually cut the subtree."
6696 (interactive "p")
6697 (let (beg end folded (beg0 (point)))
6698 (if (interactive-p)
6699 (org-back-to-heading nil) ; take what looks like a subtree
6700 (org-back-to-heading t)) ; take what is really there
6701 (org-back-over-empty-lines)
6702 (setq beg (point))
6703 (skip-chars-forward " \t\r\n")
6704 (save-match-data
6705 (save-excursion (outline-end-of-heading)
6706 (setq folded (org-invisible-p)))
6707 (condition-case nil
6708 (outline-forward-same-level (1- n))
6709 (error nil))
6710 (org-end-of-subtree t t))
6711 (org-back-over-empty-lines)
6712 (setq end (point))
6713 (goto-char beg0)
6714 (when (> end beg)
6715 (setq org-subtree-clip-folded folded)
6716 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6717 (setq org-subtree-clip (current-kill 0))
6718 (message "%s: Subtree(s) with %d characters"
6719 (if cut "Cut" "Copied")
6720 (length org-subtree-clip)))))
6722 (defun org-paste-subtree (&optional level tree)
6723 "Paste the clipboard as a subtree, with modification of headline level.
6724 The entire subtree is promoted or demoted in order to match a new headline
6725 level. By default, the new level is derived from the visible headings
6726 before and after the insertion point, and taken to be the inferior headline
6727 level of the two. So if the previous visible heading is level 3 and the
6728 next is level 4 (or vice versa), level 4 will be used for insertion.
6729 This makes sure that the subtree remains an independent subtree and does
6730 not swallow low level entries.
6732 You can also force a different level, either by using a numeric prefix
6733 argument, or by inserting the heading marker by hand. For example, if the
6734 cursor is after \"*****\", then the tree will be shifted to level 5.
6736 If you want to insert the tree as is, just use \\[yank].
6738 If optional TREE is given, use this text instead of the kill ring."
6739 (interactive "P")
6740 (unless (org-kill-is-subtree-p tree)
6741 (error "%s"
6742 (substitute-command-keys
6743 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6744 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6745 (^re (concat "^\\(" outline-regexp "\\)"))
6746 (re (concat "\\(" outline-regexp "\\)"))
6747 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6749 (old-level (if (string-match ^re txt)
6750 (- (match-end 0) (match-beginning 0) 1)
6751 -1))
6752 (force-level (cond (level (prefix-numeric-value level))
6753 ((string-match
6754 ^re_ (buffer-substring (point-at-bol) (point)))
6755 (- (match-end 1) (match-beginning 1)))
6756 (t nil)))
6757 (previous-level (save-excursion
6758 (condition-case nil
6759 (progn
6760 (outline-previous-visible-heading 1)
6761 (if (looking-at re)
6762 (- (match-end 0) (match-beginning 0) 1)
6764 (error 1))))
6765 (next-level (save-excursion
6766 (condition-case nil
6767 (progn
6768 (or (looking-at outline-regexp)
6769 (outline-next-visible-heading 1))
6770 (if (looking-at re)
6771 (- (match-end 0) (match-beginning 0) 1)
6773 (error 1))))
6774 (new-level (or force-level (max previous-level next-level)))
6775 (shift (if (or (= old-level -1)
6776 (= new-level -1)
6777 (= old-level new-level))
6779 (- new-level old-level)))
6780 (delta (if (> shift 0) -1 1))
6781 (func (if (> shift 0) 'org-demote 'org-promote))
6782 (org-odd-levels-only nil)
6783 beg end)
6784 ;; Remove the forced level indicator
6785 (if force-level
6786 (delete-region (point-at-bol) (point)))
6787 ;; Paste
6788 (beginning-of-line 1)
6789 (org-back-over-empty-lines) ;; FIXME: correct fix????
6790 (setq beg (point))
6791 (insert-before-markers txt) ;; FIXME: correct fix????
6792 (unless (string-match "\n\\'" txt) (insert "\n"))
6793 (setq end (point))
6794 (goto-char beg)
6795 (skip-chars-forward " \t\n\r")
6796 (setq beg (point))
6797 ;; Shift if necessary
6798 (unless (= shift 0)
6799 (save-restriction
6800 (narrow-to-region beg end)
6801 (while (not (= shift 0))
6802 (org-map-region func (point-min) (point-max))
6803 (setq shift (+ delta shift)))
6804 (goto-char (point-min))))
6805 (when (interactive-p)
6806 (message "Clipboard pasted as level %d subtree" new-level))
6807 (if (and kill-ring
6808 (eq org-subtree-clip (current-kill 0))
6809 org-subtree-clip-folded)
6810 ;; The tree was folded before it was killed/copied
6811 (hide-subtree))))
6813 (defun org-kill-is-subtree-p (&optional txt)
6814 "Check if the current kill is an outline subtree, or a set of trees.
6815 Returns nil if kill does not start with a headline, or if the first
6816 headline level is not the largest headline level in the tree.
6817 So this will actually accept several entries of equal levels as well,
6818 which is OK for `org-paste-subtree'.
6819 If optional TXT is given, check this string instead of the current kill."
6820 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6821 (start-level (and kill
6822 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6823 org-outline-regexp "\\)")
6824 kill)
6825 (- (match-end 2) (match-beginning 2) 1)))
6826 (re (concat "^" org-outline-regexp))
6827 (start (1+ (match-beginning 2))))
6828 (if (not start-level)
6829 (progn
6830 nil) ;; does not even start with a heading
6831 (catch 'exit
6832 (while (setq start (string-match re kill (1+ start)))
6833 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6834 (throw 'exit nil)))
6835 t))))
6837 (defun org-narrow-to-subtree ()
6838 "Narrow buffer to the current subtree."
6839 (interactive)
6840 (save-excursion
6841 (save-match-data
6842 (narrow-to-region
6843 (progn (org-back-to-heading) (point))
6844 (progn (org-end-of-subtree t t) (point))))))
6847 ;;; Outline Sorting
6849 (defun org-sort (with-case)
6850 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6851 Optional argument WITH-CASE means sort case-sensitively."
6852 (interactive "P")
6853 (if (org-at-table-p)
6854 (org-call-with-arg 'org-table-sort-lines with-case)
6855 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6857 (defvar org-priority-regexp) ; defined later in the file
6859 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6860 "Sort entries on a certain level of an outline tree.
6861 If there is an active region, the entries in the region are sorted.
6862 Else, if the cursor is before the first entry, sort the top-level items.
6863 Else, the children of the entry at point are sorted.
6865 Sorting can be alphabetically, numerically, and by date/time as given by
6866 the first time stamp in the entry. The command prompts for the sorting
6867 type unless it has been given to the function through the SORTING-TYPE
6868 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6869 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6870 called with point at the beginning of the record. It must return either
6871 a string or a number that should serve as the sorting key for that record.
6873 Comparing entries ignores case by default. However, with an optional argument
6874 WITH-CASE, the sorting considers case as well."
6875 (interactive "P")
6876 (let ((case-func (if with-case 'identity 'downcase))
6877 start beg end stars re re2
6878 txt what tmp plain-list-p)
6879 ;; Find beginning and end of region to sort
6880 (cond
6881 ((org-region-active-p)
6882 ;; we will sort the region
6883 (setq end (region-end)
6884 what "region")
6885 (goto-char (region-beginning))
6886 (if (not (org-on-heading-p)) (outline-next-heading))
6887 (setq start (point)))
6888 ((org-at-item-p)
6889 ;; we will sort this plain list
6890 (org-beginning-of-item-list) (setq start (point))
6891 (org-end-of-item-list) (setq end (point))
6892 (goto-char start)
6893 (setq plain-list-p t
6894 what "plain list"))
6895 ((or (org-on-heading-p)
6896 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6897 ;; we will sort the children of the current headline
6898 (org-back-to-heading)
6899 (setq start (point)
6900 end (progn (org-end-of-subtree t t)
6901 (org-back-over-empty-lines)
6902 (point))
6903 what "children")
6904 (goto-char start)
6905 (show-subtree)
6906 (outline-next-heading))
6908 ;; we will sort the top-level entries in this file
6909 (goto-char (point-min))
6910 (or (org-on-heading-p) (outline-next-heading))
6911 (setq start (point) end (point-max) what "top-level")
6912 (goto-char start)
6913 (show-all)))
6915 (setq beg (point))
6916 (if (>= beg end) (error "Nothing to sort"))
6918 (unless plain-list-p
6919 (looking-at "\\(\\*+\\)")
6920 (setq stars (match-string 1)
6921 re (concat "^" (regexp-quote stars) " +")
6922 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6923 txt (buffer-substring beg end))
6924 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6925 (if (and (not (equal stars "*")) (string-match re2 txt))
6926 (error "Region to sort contains a level above the first entry")))
6928 (unless sorting-type
6929 (message
6930 (if plain-list-p
6931 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6932 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
6933 what)
6934 (setq sorting-type (read-char-exclusive))
6936 (and (= (downcase sorting-type) ?f)
6937 (setq getkey-func
6938 (completing-read "Sort using function: "
6939 obarray 'fboundp t nil nil))
6940 (setq getkey-func (intern getkey-func)))
6942 (and (= (downcase sorting-type) ?r)
6943 (setq property
6944 (completing-read "Property: "
6945 (mapcar 'list (org-buffer-property-keys t))
6946 nil t))))
6948 (message "Sorting entries...")
6950 (save-restriction
6951 (narrow-to-region start end)
6953 (let ((dcst (downcase sorting-type))
6954 (now (current-time)))
6955 (sort-subr
6956 (/= dcst sorting-type)
6957 ;; This function moves to the beginning character of the "record" to
6958 ;; be sorted.
6959 (if plain-list-p
6960 (lambda nil
6961 (if (org-at-item-p) t (goto-char (point-max))))
6962 (lambda nil
6963 (if (re-search-forward re nil t)
6964 (goto-char (match-beginning 0))
6965 (goto-char (point-max)))))
6966 ;; This function moves to the last character of the "record" being
6967 ;; sorted.
6968 (if plain-list-p
6969 'org-end-of-item
6970 (lambda nil
6971 (save-match-data
6972 (condition-case nil
6973 (outline-forward-same-level 1)
6974 (error
6975 (goto-char (point-max)))))))
6977 ;; This function returns the value that gets sorted against.
6978 (if plain-list-p
6979 (lambda nil
6980 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6981 (cond
6982 ((= dcst ?n)
6983 (string-to-number (buffer-substring (match-end 0)
6984 (point-at-eol))))
6985 ((= dcst ?a)
6986 (buffer-substring (match-end 0) (point-at-eol)))
6987 ((= dcst ?t)
6988 (if (re-search-forward org-ts-regexp
6989 (point-at-eol) t)
6990 (org-time-string-to-time (match-string 0))
6991 now))
6992 ((= dcst ?f)
6993 (if getkey-func
6994 (progn
6995 (setq tmp (funcall getkey-func))
6996 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6997 tmp)
6998 (error "Invalid key function `%s'" getkey-func)))
6999 (t (error "Invalid sorting type `%c'" sorting-type)))))
7000 (lambda nil
7001 (cond
7002 ((= dcst ?n)
7003 (if (looking-at outline-regexp)
7004 (string-to-number (buffer-substring (match-end 0)
7005 (point-at-eol)))
7006 nil))
7007 ((= dcst ?a)
7008 (funcall case-func (buffer-substring (point-at-bol)
7009 (point-at-eol))))
7010 ((= dcst ?t)
7011 (if (re-search-forward org-ts-regexp
7012 (save-excursion
7013 (forward-line 2)
7014 (point)) t)
7015 (org-time-string-to-time (match-string 0))
7016 now))
7017 ((= dcst ?p)
7018 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7019 (string-to-char (match-string 2))
7020 org-default-priority))
7021 ((= dcst ?r)
7022 (or (org-entry-get nil property) ""))
7023 ((= dcst ?f)
7024 (if getkey-func
7025 (progn
7026 (setq tmp (funcall getkey-func))
7027 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7028 tmp)
7029 (error "Invalid key function `%s'" getkey-func)))
7030 (t (error "Invalid sorting type `%c'" sorting-type)))))
7032 (cond
7033 ((= dcst ?a) 'string<)
7034 ((= dcst ?t) 'time-less-p)
7035 (t nil)))))
7036 (message "Sorting entries...done")))
7038 (defun org-do-sort (table what &optional with-case sorting-type)
7039 "Sort TABLE of WHAT according to SORTING-TYPE.
7040 The user will be prompted for the SORTING-TYPE if the call to this
7041 function does not specify it. WHAT is only for the prompt, to indicate
7042 what is being sorted. The sorting key will be extracted from
7043 the car of the elements of the table.
7044 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7045 (unless sorting-type
7046 (message
7047 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7048 what)
7049 (setq sorting-type (read-char-exclusive)))
7050 (let ((dcst (downcase sorting-type))
7051 extractfun comparefun)
7052 ;; Define the appropriate functions
7053 (cond
7054 ((= dcst ?n)
7055 (setq extractfun 'string-to-number
7056 comparefun (if (= dcst sorting-type) '< '>)))
7057 ((= dcst ?a)
7058 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7059 (lambda(x) (downcase (org-sort-remove-invisible x))))
7060 comparefun (if (= dcst sorting-type)
7061 'string<
7062 (lambda (a b) (and (not (string< a b))
7063 (not (string= a b)))))))
7064 ((= dcst ?t)
7065 (setq extractfun
7066 (lambda (x)
7067 (if (string-match org-ts-regexp x)
7068 (time-to-seconds
7069 (org-time-string-to-time (match-string 0 x)))
7071 comparefun (if (= dcst sorting-type) '< '>)))
7072 (t (error "Invalid sorting type `%c'" sorting-type)))
7074 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7075 table)
7076 (lambda (a b) (funcall comparefun (car a) (car b))))))
7078 ;;;; Plain list items, including checkboxes
7080 ;;; Plain list items
7082 (defun org-at-item-p ()
7083 "Is point in a line starting a hand-formatted item?"
7084 (let ((llt org-plain-list-ordered-item-terminator))
7085 (save-excursion
7086 (goto-char (point-at-bol))
7087 (looking-at
7088 (cond
7089 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7090 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7091 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7092 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7094 (defun org-in-item-p ()
7095 "It the cursor inside a plain list item.
7096 Does not have to be the first line."
7097 (save-excursion
7098 (condition-case nil
7099 (progn
7100 (org-beginning-of-item)
7101 (org-at-item-p)
7103 (error nil))))
7105 (defun org-insert-item (&optional checkbox)
7106 "Insert a new item at the current level.
7107 Return t when things worked, nil when we are not in an item."
7108 (when (save-excursion
7109 (condition-case nil
7110 (progn
7111 (org-beginning-of-item)
7112 (org-at-item-p)
7113 (if (org-invisible-p) (error "Invisible item"))
7115 (error nil)))
7116 (let* ((bul (match-string 0))
7117 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7118 (match-end 0)))
7119 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7120 pos)
7121 (cond
7122 ((and (org-at-item-p) (<= (point) eow))
7123 ;; before the bullet
7124 (beginning-of-line 1)
7125 (open-line (if blank 2 1)))
7126 ((<= (point) eow)
7127 (beginning-of-line 1))
7129 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7130 (end-of-line 1)
7131 (delete-horizontal-space))
7132 (newline (if blank 2 1))))
7133 (insert bul (if checkbox "[ ]" ""))
7134 (just-one-space)
7135 (setq pos (point))
7136 (end-of-line 1)
7137 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7138 (org-maybe-renumber-ordered-list)
7139 (and checkbox (org-update-checkbox-count-maybe))
7142 ;;; Checkboxes
7144 (defun org-at-item-checkbox-p ()
7145 "Is point at a line starting a plain-list item with a checklet?"
7146 (and (org-at-item-p)
7147 (save-excursion
7148 (goto-char (match-end 0))
7149 (skip-chars-forward " \t")
7150 (looking-at "\\[[- X]\\]"))))
7152 (defun org-toggle-checkbox (&optional arg)
7153 "Toggle the checkbox in the current line."
7154 (interactive "P")
7155 (catch 'exit
7156 (let (beg end status (firstnew 'unknown))
7157 (cond
7158 ((org-region-active-p)
7159 (setq beg (region-beginning) end (region-end)))
7160 ((org-on-heading-p)
7161 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7162 ((org-at-item-checkbox-p)
7163 (let ((pos (point)))
7164 (replace-match
7165 (cond (arg "[-]")
7166 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7167 (t "[ ]"))
7168 t t)
7169 (goto-char pos))
7170 (throw 'exit t))
7171 (t (error "Not at a checkbox or heading, and no active region")))
7172 (save-excursion
7173 (goto-char beg)
7174 (while (< (point) end)
7175 (when (org-at-item-checkbox-p)
7176 (setq status (equal (match-string 0) "[X]"))
7177 (when (eq firstnew 'unknown)
7178 (setq firstnew (not status)))
7179 (replace-match
7180 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7181 (beginning-of-line 2)))))
7182 (org-update-checkbox-count-maybe))
7184 (defun org-update-checkbox-count-maybe ()
7185 "Update checkbox statistics unless turned off by user."
7186 (when org-provide-checkbox-statistics
7187 (org-update-checkbox-count)))
7189 (defun org-update-checkbox-count (&optional all)
7190 "Update the checkbox statistics in the current section.
7191 This will find all statistic cookies like [57%] and [6/12] and update them
7192 with the current numbers. With optional prefix argument ALL, do this for
7193 the whole buffer."
7194 (interactive "P")
7195 (save-excursion
7196 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7197 (beg (condition-case nil
7198 (progn (outline-back-to-heading) (point))
7199 (error (point-min))))
7200 (end (move-marker (make-marker)
7201 (progn (outline-next-heading) (point))))
7202 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7203 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7204 (re-find (concat re "\\|" re-box))
7205 beg-cookie end-cookie is-percent c-on c-off lim
7206 eline curr-ind next-ind continue-from startsearch
7207 (cstat 0)
7209 (when all
7210 (goto-char (point-min))
7211 (outline-next-heading)
7212 (setq beg (point) end (point-max)))
7213 (goto-char end)
7214 ;; find each statistic cookie
7215 (while (re-search-backward re-find beg t)
7216 (setq beg-cookie (match-beginning 1)
7217 end-cookie (match-end 1)
7218 cstat (+ cstat (if end-cookie 1 0))
7219 startsearch (point-at-eol)
7220 continue-from (point-at-bol)
7221 is-percent (match-beginning 2)
7222 lim (cond
7223 ((org-on-heading-p) (outline-next-heading) (point))
7224 ((org-at-item-p) (org-end-of-item) (point))
7225 (t nil))
7226 c-on 0
7227 c-off 0)
7228 (when lim
7229 ;; find first checkbox for this cookie and gather
7230 ;; statistics from all that are at this indentation level
7231 (goto-char startsearch)
7232 (if (re-search-forward re-box lim t)
7233 (progn
7234 (org-beginning-of-item)
7235 (setq curr-ind (org-get-indentation))
7236 (setq next-ind curr-ind)
7237 (while (= curr-ind next-ind)
7238 (save-excursion (end-of-line) (setq eline (point)))
7239 (if (re-search-forward re-box eline t)
7240 (if (member (match-string 2) '("[ ]" "[-]"))
7241 (setq c-off (1+ c-off))
7242 (setq c-on (1+ c-on))
7245 (org-end-of-item)
7246 (setq next-ind (org-get-indentation))
7248 (goto-char continue-from)
7249 ;; update cookie
7250 (when end-cookie
7251 (delete-region beg-cookie end-cookie)
7252 (goto-char beg-cookie)
7253 (insert
7254 (if is-percent
7255 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7256 (format "[%d/%d]" c-on (+ c-on c-off)))))
7257 ;; update items checkbox if it has one
7258 (when (org-at-item-p)
7259 (org-beginning-of-item)
7260 (when (and (> (+ c-on c-off) 0)
7261 (re-search-forward re-box (point-at-eol) t))
7262 (setq beg-cookie (match-beginning 2)
7263 end-cookie (match-end 2))
7264 (delete-region beg-cookie end-cookie)
7265 (goto-char beg-cookie)
7266 (cond ((= c-off 0) (insert "[X]"))
7267 ((= c-on 0) (insert "[ ]"))
7268 (t (insert "[-]")))
7270 (goto-char continue-from))
7271 (when (interactive-p)
7272 (message "Checkbox satistics updated %s (%d places)"
7273 (if all "in entire file" "in current outline entry") cstat)))))
7275 (defun org-get-checkbox-statistics-face ()
7276 "Select the face for checkbox statistics.
7277 The face will be `org-done' when all relevant boxes are checked. Otherwise
7278 it will be `org-todo'."
7279 (if (match-end 1)
7280 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7281 (if (and (> (match-end 2) (match-beginning 2))
7282 (equal (match-string 2) (match-string 3)))
7283 'org-done
7284 'org-todo)))
7286 (defun org-get-indentation (&optional line)
7287 "Get the indentation of the current line, interpreting tabs.
7288 When LINE is given, assume it represents a line and compute its indentation."
7289 (if line
7290 (if (string-match "^ *" (org-remove-tabs line))
7291 (match-end 0))
7292 (save-excursion
7293 (beginning-of-line 1)
7294 (skip-chars-forward " \t")
7295 (current-column))))
7297 (defun org-remove-tabs (s &optional width)
7298 "Replace tabulators in S with spaces.
7299 Assumes that s is a single line, starting in column 0."
7300 (setq width (or width tab-width))
7301 (while (string-match "\t" s)
7302 (setq s (replace-match
7303 (make-string
7304 (- (* width (/ (+ (match-beginning 0) width) width))
7305 (match-beginning 0)) ?\ )
7306 t t s)))
7309 (defun org-fix-indentation (line ind)
7310 "Fix indentation in LINE.
7311 IND is a cons cell with target and minimum indentation.
7312 If the current indenation in LINE is smaller than the minimum,
7313 leave it alone. If it is larger than ind, set it to the target."
7314 (let* ((l (org-remove-tabs line))
7315 (i (org-get-indentation l))
7316 (i1 (car ind)) (i2 (cdr ind)))
7317 (if (>= i i2) (setq l (substring line i2)))
7318 (if (> i1 0)
7319 (concat (make-string i1 ?\ ) l)
7320 l)))
7322 (defcustom org-empty-line-terminates-plain-lists nil
7323 "Non-nil means, an empty line ends all plain list levels.
7324 When nil, empty lines are part of the preceeding item."
7325 :group 'org-plain-lists
7326 :type 'boolean)
7328 (defun org-beginning-of-item ()
7329 "Go to the beginning of the current hand-formatted item.
7330 If the cursor is not in an item, throw an error."
7331 (interactive)
7332 (let ((pos (point))
7333 (limit (save-excursion
7334 (condition-case nil
7335 (progn
7336 (org-back-to-heading)
7337 (beginning-of-line 2) (point))
7338 (error (point-min)))))
7339 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7340 ind ind1)
7341 (if (org-at-item-p)
7342 (beginning-of-line 1)
7343 (beginning-of-line 1)
7344 (skip-chars-forward " \t")
7345 (setq ind (current-column))
7346 (if (catch 'exit
7347 (while t
7348 (beginning-of-line 0)
7349 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7351 (if (looking-at "[ \t]*$")
7352 (setq ind1 ind-empty)
7353 (skip-chars-forward " \t")
7354 (setq ind1 (current-column)))
7355 (if (< ind1 ind)
7356 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7358 (goto-char pos)
7359 (error "Not in an item")))))
7361 (defun org-end-of-item ()
7362 "Go to the end of the current hand-formatted item.
7363 If the cursor is not in an item, throw an error."
7364 (interactive)
7365 (let* ((pos (point))
7366 ind1
7367 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7368 (limit (save-excursion (outline-next-heading) (point)))
7369 (ind (save-excursion
7370 (org-beginning-of-item)
7371 (skip-chars-forward " \t")
7372 (current-column)))
7373 (end (catch 'exit
7374 (while t
7375 (beginning-of-line 2)
7376 (if (eobp) (throw 'exit (point)))
7377 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7378 (if (looking-at "[ \t]*$")
7379 (setq ind1 ind-empty)
7380 (skip-chars-forward " \t")
7381 (setq ind1 (current-column)))
7382 (if (<= ind1 ind)
7383 (throw 'exit (point-at-bol)))))))
7384 (if end
7385 (goto-char end)
7386 (goto-char pos)
7387 (error "Not in an item"))))
7389 (defun org-next-item ()
7390 "Move to the beginning of the next item in the current plain list.
7391 Error if not at a plain list, or if this is the last item in the list."
7392 (interactive)
7393 (let (ind ind1 (pos (point)))
7394 (org-beginning-of-item)
7395 (setq ind (org-get-indentation))
7396 (org-end-of-item)
7397 (setq ind1 (org-get-indentation))
7398 (unless (and (org-at-item-p) (= ind ind1))
7399 (goto-char pos)
7400 (error "On last item"))))
7402 (defun org-previous-item ()
7403 "Move to the beginning of the previous item in the current plain list.
7404 Error if not at a plain list, or if this is the first item in the list."
7405 (interactive)
7406 (let (beg ind ind1 (pos (point)))
7407 (org-beginning-of-item)
7408 (setq beg (point))
7409 (setq ind (org-get-indentation))
7410 (goto-char beg)
7411 (catch 'exit
7412 (while t
7413 (beginning-of-line 0)
7414 (if (looking-at "[ \t]*$")
7416 (if (<= (setq ind1 (org-get-indentation)) ind)
7417 (throw 'exit t)))))
7418 (condition-case nil
7419 (if (or (not (org-at-item-p))
7420 (< ind1 (1- ind)))
7421 (error "")
7422 (org-beginning-of-item))
7423 (error (goto-char pos)
7424 (error "On first item")))))
7426 (defun org-first-list-item-p ()
7427 "Is this heading the item in a plain list?"
7428 (unless (org-at-item-p)
7429 (error "Not at a plain list item"))
7430 (org-beginning-of-item)
7431 (= (point) (save-excursion (org-beginning-of-item-list))))
7433 (defun org-move-item-down ()
7434 "Move the plain list item at point down, i.e. swap with following item.
7435 Subitems (items with larger indentation) are considered part of the item,
7436 so this really moves item trees."
7437 (interactive)
7438 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7439 (org-beginning-of-item)
7440 (setq beg0 (point))
7441 (save-excursion
7442 (setq ne-beg (org-back-over-empty-lines))
7443 (setq beg (point)))
7444 (goto-char beg0)
7445 (setq ind (org-get-indentation))
7446 (org-end-of-item)
7447 (setq end0 (point))
7448 (setq ind1 (org-get-indentation))
7449 (setq ne-end (org-back-over-empty-lines))
7450 (setq end (point))
7451 (goto-char beg0)
7452 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7453 ;; include less whitespace
7454 (save-excursion
7455 (goto-char beg)
7456 (forward-line (- ne-beg ne-end))
7457 (setq beg (point))))
7458 (goto-char end0)
7459 (if (and (org-at-item-p) (= ind ind1))
7460 (progn
7461 (org-end-of-item)
7462 (org-back-over-empty-lines)
7463 (setq txt (buffer-substring beg end))
7464 (save-excursion
7465 (delete-region beg end))
7466 (setq pos (point))
7467 (insert txt)
7468 (goto-char pos) (org-skip-whitespace)
7469 (org-maybe-renumber-ordered-list))
7470 (goto-char pos)
7471 (error "Cannot move this item further down"))))
7473 (defun org-move-item-up (arg)
7474 "Move the plain list item at point up, i.e. swap with previous item.
7475 Subitems (items with larger indentation) are considered part of the item,
7476 so this really moves item trees."
7477 (interactive "p")
7478 (let (beg beg0 end ind ind1 (pos (point)) txt
7479 ne-beg ne-ins ins-end)
7480 (org-beginning-of-item)
7481 (setq beg0 (point))
7482 (setq ind (org-get-indentation))
7483 (save-excursion
7484 (setq ne-beg (org-back-over-empty-lines))
7485 (setq beg (point)))
7486 (goto-char beg0)
7487 (org-end-of-item)
7488 (setq end (point))
7489 (goto-char beg0)
7490 (catch 'exit
7491 (while t
7492 (beginning-of-line 0)
7493 (if (looking-at "[ \t]*$")
7494 (if org-empty-line-terminates-plain-lists
7495 (progn
7496 (goto-char pos)
7497 (error "Cannot move this item further up"))
7498 nil)
7499 (if (<= (setq ind1 (org-get-indentation)) ind)
7500 (throw 'exit t)))))
7501 (condition-case nil
7502 (org-beginning-of-item)
7503 (error (goto-char beg)
7504 (error "Cannot move this item further up")))
7505 (setq ind1 (org-get-indentation))
7506 (if (and (org-at-item-p) (= ind ind1))
7507 (progn
7508 (setq ne-ins (org-back-over-empty-lines))
7509 (setq txt (buffer-substring beg end))
7510 (save-excursion
7511 (delete-region beg end))
7512 (setq pos (point))
7513 (insert txt)
7514 (setq ins-end (point))
7515 (goto-char pos) (org-skip-whitespace)
7517 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7518 ;; Move whitespace back to beginning
7519 (save-excursion
7520 (goto-char ins-end)
7521 (let ((kill-whole-line t))
7522 (kill-line (- ne-ins ne-beg)) (point)))
7523 (insert (make-string (- ne-ins ne-beg) ?\n)))
7525 (org-maybe-renumber-ordered-list))
7526 (goto-char pos)
7527 (error "Cannot move this item further up"))))
7529 (defun org-maybe-renumber-ordered-list ()
7530 "Renumber the ordered list at point if setup allows it.
7531 This tests the user option `org-auto-renumber-ordered-lists' before
7532 doing the renumbering."
7533 (interactive)
7534 (when (and org-auto-renumber-ordered-lists
7535 (org-at-item-p))
7536 (if (match-beginning 3)
7537 (org-renumber-ordered-list 1)
7538 (org-fix-bullet-type))))
7540 (defun org-maybe-renumber-ordered-list-safe ()
7541 (condition-case nil
7542 (save-excursion
7543 (org-maybe-renumber-ordered-list))
7544 (error nil)))
7546 (defun org-cycle-list-bullet (&optional which)
7547 "Cycle through the different itemize/enumerate bullets.
7548 This cycle the entire list level through the sequence:
7550 `-' -> `+' -> `*' -> `1.' -> `1)'
7552 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7553 0 meand `-', 1 means `+' etc."
7554 (interactive "P")
7555 (org-preserve-lc
7556 (org-beginning-of-item-list)
7557 (org-at-item-p)
7558 (beginning-of-line 1)
7559 (let ((current (match-string 0))
7560 (prevp (eq which 'previous))
7561 new)
7562 (setq new (cond
7563 ((and (numberp which)
7564 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7565 ((string-match "-" current) (if prevp "1)" "+"))
7566 ((string-match "\\+" current)
7567 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7568 ((string-match "\\*" current) (if prevp "+" "1."))
7569 ((string-match "\\." current) (if prevp "*" "1)"))
7570 ((string-match ")" current) (if prevp "1." "-"))
7571 (t (error "This should not happen"))))
7572 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7573 (org-fix-bullet-type)
7574 (org-maybe-renumber-ordered-list))))
7576 (defun org-get-string-indentation (s)
7577 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7578 (let ((n -1) (i 0) (w tab-width) c)
7579 (catch 'exit
7580 (while (< (setq n (1+ n)) (length s))
7581 (setq c (aref s n))
7582 (cond ((= c ?\ ) (setq i (1+ i)))
7583 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7584 (t (throw 'exit t)))))
7587 (defun org-renumber-ordered-list (arg)
7588 "Renumber an ordered plain list.
7589 Cursor needs to be in the first line of an item, the line that starts
7590 with something like \"1.\" or \"2)\"."
7591 (interactive "p")
7592 (unless (and (org-at-item-p)
7593 (match-beginning 3))
7594 (error "This is not an ordered list"))
7595 (let ((line (org-current-line))
7596 (col (current-column))
7597 (ind (org-get-string-indentation
7598 (buffer-substring (point-at-bol) (match-beginning 3))))
7599 ;; (term (substring (match-string 3) -1))
7600 ind1 (n (1- arg))
7601 fmt)
7602 ;; find where this list begins
7603 (org-beginning-of-item-list)
7604 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7605 (setq fmt (concat "%d" (match-string 1)))
7606 (beginning-of-line 0)
7607 ;; walk forward and replace these numbers
7608 (catch 'exit
7609 (while t
7610 (catch 'next
7611 (beginning-of-line 2)
7612 (if (eobp) (throw 'exit nil))
7613 (if (looking-at "[ \t]*$") (throw 'next nil))
7614 (skip-chars-forward " \t") (setq ind1 (current-column))
7615 (if (> ind1 ind) (throw 'next t))
7616 (if (< ind1 ind) (throw 'exit t))
7617 (if (not (org-at-item-p)) (throw 'exit nil))
7618 (delete-region (match-beginning 2) (match-end 2))
7619 (goto-char (match-beginning 2))
7620 (insert (format fmt (setq n (1+ n)))))))
7621 (goto-line line)
7622 (move-to-column col)))
7624 (defun org-fix-bullet-type ()
7625 "Make sure all items in this list have the same bullet as the firsst item."
7626 (interactive)
7627 (unless (org-at-item-p) (error "This is not a list"))
7628 (let ((line (org-current-line))
7629 (col (current-column))
7630 (ind (current-indentation))
7631 ind1 bullet)
7632 ;; find where this list begins
7633 (org-beginning-of-item-list)
7634 (beginning-of-line 1)
7635 ;; find out what the bullet type is
7636 (looking-at "[ \t]*\\(\\S-+\\)")
7637 (setq bullet (match-string 1))
7638 ;; walk forward and replace these numbers
7639 (beginning-of-line 0)
7640 (catch 'exit
7641 (while t
7642 (catch 'next
7643 (beginning-of-line 2)
7644 (if (eobp) (throw 'exit nil))
7645 (if (looking-at "[ \t]*$") (throw 'next nil))
7646 (skip-chars-forward " \t") (setq ind1 (current-column))
7647 (if (> ind1 ind) (throw 'next t))
7648 (if (< ind1 ind) (throw 'exit t))
7649 (if (not (org-at-item-p)) (throw 'exit nil))
7650 (skip-chars-forward " \t")
7651 (looking-at "\\S-+")
7652 (replace-match bullet))))
7653 (goto-line line)
7654 (move-to-column col)
7655 (if (string-match "[0-9]" bullet)
7656 (org-renumber-ordered-list 1))))
7658 (defun org-beginning-of-item-list ()
7659 "Go to the beginning of the current item list.
7660 I.e. to the first item in this list."
7661 (interactive)
7662 (org-beginning-of-item)
7663 (let ((pos (point-at-bol))
7664 (ind (org-get-indentation))
7665 ind1)
7666 ;; find where this list begins
7667 (catch 'exit
7668 (while t
7669 (catch 'next
7670 (beginning-of-line 0)
7671 (if (looking-at "[ \t]*$")
7672 (throw (if (bobp) 'exit 'next) t))
7673 (skip-chars-forward " \t") (setq ind1 (current-column))
7674 (if (or (< ind1 ind)
7675 (and (= ind1 ind)
7676 (not (org-at-item-p)))
7677 (bobp))
7678 (throw 'exit t)
7679 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7680 (goto-char pos)))
7683 (defun org-end-of-item-list ()
7684 "Go to the end of the current item list.
7685 I.e. to the text after the last item."
7686 (interactive)
7687 (org-beginning-of-item)
7688 (let ((pos (point-at-bol))
7689 (ind (org-get-indentation))
7690 ind1)
7691 ;; find where this list begins
7692 (catch 'exit
7693 (while t
7694 (catch 'next
7695 (beginning-of-line 2)
7696 (if (looking-at "[ \t]*$")
7697 (throw (if (eobp) 'exit 'next) t))
7698 (skip-chars-forward " \t") (setq ind1 (current-column))
7699 (if (or (< ind1 ind)
7700 (and (= ind1 ind)
7701 (not (org-at-item-p)))
7702 (eobp))
7703 (progn
7704 (setq pos (point-at-bol))
7705 (throw 'exit t))))))
7706 (goto-char pos)))
7709 (defvar org-last-indent-begin-marker (make-marker))
7710 (defvar org-last-indent-end-marker (make-marker))
7712 (defun org-outdent-item (arg)
7713 "Outdent a local list item."
7714 (interactive "p")
7715 (org-indent-item (- arg)))
7717 (defun org-indent-item (arg)
7718 "Indent a local list item."
7719 (interactive "p")
7720 (unless (org-at-item-p)
7721 (error "Not on an item"))
7722 (save-excursion
7723 (let (beg end ind ind1 tmp delta ind-down ind-up)
7724 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7725 (setq beg org-last-indent-begin-marker
7726 end org-last-indent-end-marker)
7727 (org-beginning-of-item)
7728 (setq beg (move-marker org-last-indent-begin-marker (point)))
7729 (org-end-of-item)
7730 (setq end (move-marker org-last-indent-end-marker (point))))
7731 (goto-char beg)
7732 (setq tmp (org-item-indent-positions)
7733 ind (car tmp)
7734 ind-down (nth 2 tmp)
7735 ind-up (nth 1 tmp)
7736 delta (if (> arg 0)
7737 (if ind-down (- ind-down ind) 2)
7738 (if ind-up (- ind-up ind) -2)))
7739 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7740 (while (< (point) end)
7741 (beginning-of-line 1)
7742 (skip-chars-forward " \t") (setq ind1 (current-column))
7743 (delete-region (point-at-bol) (point))
7744 (or (eolp) (indent-to-column (+ ind1 delta)))
7745 (beginning-of-line 2))))
7746 (org-fix-bullet-type)
7747 (org-maybe-renumber-ordered-list-safe)
7748 (save-excursion
7749 (beginning-of-line 0)
7750 (condition-case nil (org-beginning-of-item) (error nil))
7751 (org-maybe-renumber-ordered-list-safe)))
7753 (defun org-item-indent-positions ()
7754 "Return indentation for plain list items.
7755 This returns a list with three values: The current indentation, the
7756 parent indentation and the indentation a child should habe.
7757 Assumes cursor in item line."
7758 (let* ((bolpos (point-at-bol))
7759 (ind (org-get-indentation))
7760 ind-down ind-up pos)
7761 (save-excursion
7762 (org-beginning-of-item-list)
7763 (skip-chars-backward "\n\r \t")
7764 (when (org-in-item-p)
7765 (org-beginning-of-item)
7766 (setq ind-up (org-get-indentation))))
7767 (setq pos (point))
7768 (save-excursion
7769 (cond
7770 ((and (condition-case nil (progn (org-previous-item) t)
7771 (error nil))
7772 (or (forward-char 1) t)
7773 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7774 (setq ind-down (org-get-indentation)))
7775 ((and (goto-char pos)
7776 (org-at-item-p))
7777 (goto-char (match-end 0))
7778 (skip-chars-forward " \t")
7779 (setq ind-down (current-column)))))
7780 (list ind ind-up ind-down)))
7782 ;;; The orgstruct minor mode
7784 ;; Define a minor mode which can be used in other modes in order to
7785 ;; integrate the org-mode structure editing commands.
7787 ;; This is really a hack, because the org-mode structure commands use
7788 ;; keys which normally belong to the major mode. Here is how it
7789 ;; works: The minor mode defines all the keys necessary to operate the
7790 ;; structure commands, but wraps the commands into a function which
7791 ;; tests if the cursor is currently at a headline or a plain list
7792 ;; item. If that is the case, the structure command is used,
7793 ;; temporarily setting many Org-mode variables like regular
7794 ;; expressions for filling etc. However, when any of those keys is
7795 ;; used at a different location, function uses `key-binding' to look
7796 ;; up if the key has an associated command in another currently active
7797 ;; keymap (minor modes, major mode, global), and executes that
7798 ;; command. There might be problems if any of the keys is otherwise
7799 ;; used as a prefix key.
7801 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7802 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7803 ;; addresses this by checking explicitly for both bindings.
7805 (defvar orgstruct-mode-map (make-sparse-keymap)
7806 "Keymap for the minor `orgstruct-mode'.")
7808 (defvar org-local-vars nil
7809 "List of local variables, for use by `orgstruct-mode'")
7811 ;;;###autoload
7812 (define-minor-mode orgstruct-mode
7813 "Toggle the minor more `orgstruct-mode'.
7814 This mode is for using Org-mode structure commands in other modes.
7815 The following key behave as if Org-mode was active, if the cursor
7816 is on a headline, or on a plain list item (both in the definition
7817 of Org-mode).
7819 M-up Move entry/item up
7820 M-down Move entry/item down
7821 M-left Promote
7822 M-right Demote
7823 M-S-up Move entry/item up
7824 M-S-down Move entry/item down
7825 M-S-left Promote subtree
7826 M-S-right Demote subtree
7827 M-q Fill paragraph and items like in Org-mode
7828 C-c ^ Sort entries
7829 C-c - Cycle list bullet
7830 TAB Cycle item visibility
7831 M-RET Insert new heading/item
7832 S-M-RET Insert new TODO heading / Chekbox item
7833 C-c C-c Set tags / toggle checkbox"
7834 nil " OrgStruct" nil
7835 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7837 ;;;###autoload
7838 (defun turn-on-orgstruct ()
7839 "Unconditionally turn on `orgstruct-mode'."
7840 (orgstruct-mode 1))
7842 ;;;###autoload
7843 (defun turn-on-orgstruct++ ()
7844 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7845 In addition to setting orgstruct-mode, this also exports all indentation and
7846 autofilling variables from org-mode into the buffer. Note that turning
7847 off orgstruct-mode will *not* remove these additional settings."
7848 (orgstruct-mode 1)
7849 (let (var val)
7850 (mapc
7851 (lambda (x)
7852 (when (string-match
7853 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7854 (symbol-name (car x)))
7855 (setq var (car x) val (nth 1 x))
7856 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7857 org-local-vars)))
7859 (defun orgstruct-error ()
7860 "Error when there is no default binding for a structure key."
7861 (interactive)
7862 (error "This key has no function outside structure elements"))
7864 (defun orgstruct-setup ()
7865 "Setup orgstruct keymaps."
7866 (let ((nfunc 0)
7867 (bindings
7868 (list
7869 '([(meta up)] org-metaup)
7870 '([(meta down)] org-metadown)
7871 '([(meta left)] org-metaleft)
7872 '([(meta right)] org-metaright)
7873 '([(meta shift up)] org-shiftmetaup)
7874 '([(meta shift down)] org-shiftmetadown)
7875 '([(meta shift left)] org-shiftmetaleft)
7876 '([(meta shift right)] org-shiftmetaright)
7877 '([(shift up)] org-shiftup)
7878 '([(shift down)] org-shiftdown)
7879 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7880 '("\M-q" fill-paragraph)
7881 '("\C-c^" org-sort)
7882 '("\C-c-" org-cycle-list-bullet)))
7883 elt key fun cmd)
7884 (while (setq elt (pop bindings))
7885 (setq nfunc (1+ nfunc))
7886 (setq key (org-key (car elt))
7887 fun (nth 1 elt)
7888 cmd (orgstruct-make-binding fun nfunc key))
7889 (org-defkey orgstruct-mode-map key cmd))
7891 ;; Special treatment needed for TAB and RET
7892 (org-defkey orgstruct-mode-map [(tab)]
7893 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7894 (org-defkey orgstruct-mode-map "\C-i"
7895 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7897 (org-defkey orgstruct-mode-map "\M-\C-m"
7898 (orgstruct-make-binding 'org-insert-heading 105
7899 "\M-\C-m" [(meta return)]))
7900 (org-defkey orgstruct-mode-map [(meta return)]
7901 (orgstruct-make-binding 'org-insert-heading 106
7902 [(meta return)] "\M-\C-m"))
7904 (org-defkey orgstruct-mode-map [(shift meta return)]
7905 (orgstruct-make-binding 'org-insert-todo-heading 107
7906 [(meta return)] "\M-\C-m"))
7908 (unless org-local-vars
7909 (setq org-local-vars (org-get-local-variables)))
7913 (defun orgstruct-make-binding (fun n &rest keys)
7914 "Create a function for binding in the structure minor mode.
7915 FUN is the command to call inside a table. N is used to create a unique
7916 command name. KEYS are keys that should be checked in for a command
7917 to execute outside of tables."
7918 (eval
7919 (list 'defun
7920 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7921 '(arg)
7922 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7923 "Outside of structure, run the binding of `"
7924 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7925 "'.")
7926 '(interactive "p")
7927 (list 'if
7928 '(org-context-p 'headline 'item)
7929 (list 'org-run-like-in-org-mode (list 'quote fun))
7930 (list 'let '(orgstruct-mode)
7931 (list 'call-interactively
7932 (append '(or)
7933 (mapcar (lambda (k)
7934 (list 'key-binding k))
7935 keys)
7936 '('orgstruct-error))))))))
7938 (defun org-context-p (&rest contexts)
7939 "Check if local context is and of CONTEXTS.
7940 Possible values in the list of contexts are `table', `headline', and `item'."
7941 (let ((pos (point)))
7942 (goto-char (point-at-bol))
7943 (prog1 (or (and (memq 'table contexts)
7944 (looking-at "[ \t]*|"))
7945 (and (memq 'headline contexts)
7946 (looking-at "\\*+"))
7947 (and (memq 'item contexts)
7948 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
7949 (goto-char pos))))
7951 (defun org-get-local-variables ()
7952 "Return a list of all local variables in an org-mode buffer."
7953 (let (varlist)
7954 (with-current-buffer (get-buffer-create "*Org tmp*")
7955 (erase-buffer)
7956 (org-mode)
7957 (setq varlist (buffer-local-variables)))
7958 (kill-buffer "*Org tmp*")
7959 (delq nil
7960 (mapcar
7961 (lambda (x)
7962 (setq x
7963 (if (symbolp x)
7964 (list x)
7965 (list (car x) (list 'quote (cdr x)))))
7966 (if (string-match
7967 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7968 (symbol-name (car x)))
7969 x nil))
7970 varlist))))
7972 ;;;###autoload
7973 (defun org-run-like-in-org-mode (cmd)
7974 (unless org-local-vars
7975 (setq org-local-vars (org-get-local-variables)))
7976 (eval (list 'let org-local-vars
7977 (list 'call-interactively (list 'quote cmd)))))
7979 ;;;; Archiving
7981 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
7983 (defun org-archive-subtree (&optional find-done)
7984 "Move the current subtree to the archive.
7985 The archive can be a certain top-level heading in the current file, or in
7986 a different file. The tree will be moved to that location, the subtree
7987 heading be marked DONE, and the current time will be added.
7989 When called with prefix argument FIND-DONE, find whole trees without any
7990 open TODO items and archive them (after getting confirmation from the user).
7991 If the cursor is not at a headline when this comand is called, try all level
7992 1 trees. If the cursor is on a headline, only try the direct children of
7993 this heading."
7994 (interactive "P")
7995 (if find-done
7996 (org-archive-all-done)
7997 ;; Save all relevant TODO keyword-relatex variables
7999 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8000 (tr-org-todo-keywords-1 org-todo-keywords-1)
8001 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8002 (tr-org-done-keywords org-done-keywords)
8003 (tr-org-todo-regexp org-todo-regexp)
8004 (tr-org-todo-line-regexp org-todo-line-regexp)
8005 (tr-org-odd-levels-only org-odd-levels-only)
8006 (this-buffer (current-buffer))
8007 (org-archive-location org-archive-location)
8008 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8009 ;; start of variables that will be used for saving context
8010 ;; The compiler complains about them - keep them anyway!
8011 (file (abbreviate-file-name (buffer-file-name)))
8012 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8013 (time (format-time-string
8014 (substring (cdr org-time-stamp-formats) 1 -1)
8015 (current-time)))
8016 afile heading buffer level newfile-p
8017 category todo priority
8018 ;; start of variables that will be used for savind context
8019 ltags itags prop)
8021 ;; Try to find a local archive location
8022 (save-excursion
8023 (save-restriction
8024 (widen)
8025 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8026 (if (and prop (string-match "\\S-" prop))
8027 (setq org-archive-location prop)
8028 (if (or (re-search-backward re nil t)
8029 (re-search-forward re nil t))
8030 (setq org-archive-location (match-string 1))))))
8032 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8033 (progn
8034 (setq afile (format (match-string 1 org-archive-location)
8035 (file-name-nondirectory buffer-file-name))
8036 heading (match-string 2 org-archive-location)))
8037 (error "Invalid `org-archive-location'"))
8038 (if (> (length afile) 0)
8039 (setq newfile-p (not (file-exists-p afile))
8040 buffer (find-file-noselect afile))
8041 (setq buffer (current-buffer)))
8042 (unless buffer
8043 (error "Cannot access file \"%s\"" afile))
8044 (if (and (> (length heading) 0)
8045 (string-match "^\\*+" heading))
8046 (setq level (match-end 0))
8047 (setq heading nil level 0))
8048 (save-excursion
8049 (org-back-to-heading t)
8050 ;; Get context information that will be lost by moving the tree
8051 (org-refresh-category-properties)
8052 (setq category (org-get-category)
8053 todo (and (looking-at org-todo-line-regexp)
8054 (match-string 2))
8055 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8056 ltags (org-get-tags)
8057 itags (org-delete-all ltags (org-get-tags-at)))
8058 (setq ltags (mapconcat 'identity ltags " ")
8059 itags (mapconcat 'identity itags " "))
8060 ;; We first only copy, in case something goes wrong
8061 ;; we need to protect this-command, to avoid kill-region sets it,
8062 ;; which would lead to duplication of subtrees
8063 (let (this-command) (org-copy-subtree))
8064 (set-buffer buffer)
8065 ;; Enforce org-mode for the archive buffer
8066 (if (not (org-mode-p))
8067 ;; Force the mode for future visits.
8068 (let ((org-insert-mode-line-in-empty-file t)
8069 (org-inhibit-startup t))
8070 (call-interactively 'org-mode)))
8071 (when newfile-p
8072 (goto-char (point-max))
8073 (insert (format "\nArchived entries from file %s\n\n"
8074 (buffer-file-name this-buffer))))
8075 ;; Force the TODO keywords of the original buffer
8076 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8077 (org-todo-keywords-1 tr-org-todo-keywords-1)
8078 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8079 (org-done-keywords tr-org-done-keywords)
8080 (org-todo-regexp tr-org-todo-regexp)
8081 (org-todo-line-regexp tr-org-todo-line-regexp)
8082 (org-odd-levels-only
8083 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8084 org-odd-levels-only
8085 tr-org-odd-levels-only)))
8086 (goto-char (point-min))
8087 (show-all)
8088 (if heading
8089 (progn
8090 (if (re-search-forward
8091 (concat "^" (regexp-quote heading)
8092 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8093 nil t)
8094 (goto-char (match-end 0))
8095 ;; Heading not found, just insert it at the end
8096 (goto-char (point-max))
8097 (or (bolp) (insert "\n"))
8098 (insert "\n" heading "\n")
8099 (end-of-line 0))
8100 ;; Make the subtree visible
8101 (show-subtree)
8102 (org-end-of-subtree t)
8103 (skip-chars-backward " \t\r\n")
8104 (and (looking-at "[ \t\r\n]*")
8105 (replace-match "\n\n")))
8106 ;; No specific heading, just go to end of file.
8107 (goto-char (point-max)) (insert "\n"))
8108 ;; Paste
8109 (org-paste-subtree (org-get-legal-level level 1))
8111 ;; Mark the entry as done
8112 (when (and org-archive-mark-done
8113 (looking-at org-todo-line-regexp)
8114 (or (not (match-end 2))
8115 (not (member (match-string 2) org-done-keywords))))
8116 (let (org-log-done org-todo-log-states)
8117 (org-todo
8118 (car (or (member org-archive-mark-done org-done-keywords)
8119 org-done-keywords)))))
8121 ;; Add the context info
8122 (when org-archive-save-context-info
8123 (let ((l org-archive-save-context-info) e n v)
8124 (while (setq e (pop l))
8125 (when (and (setq v (symbol-value e))
8126 (stringp v) (string-match "\\S-" v))
8127 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8128 (org-entry-put (point) n v)))))
8130 ;; Save and kill the buffer, if it is not the same buffer.
8131 (if (not (eq this-buffer buffer))
8132 (progn (save-buffer) (kill-buffer buffer)))))
8133 ;; Here we are back in the original buffer. Everything seems to have
8134 ;; worked. So now cut the tree and finish up.
8135 (let (this-command) (org-cut-subtree))
8136 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8137 (message "Subtree archived %s"
8138 (if (eq this-buffer buffer)
8139 (concat "under heading: " heading)
8140 (concat "in file: " (abbreviate-file-name afile)))))))
8142 (defun org-refresh-category-properties ()
8143 "Refresh category text properties in teh buffer."
8144 (let ((def-cat (cond
8145 ((null org-category)
8146 (if buffer-file-name
8147 (file-name-sans-extension
8148 (file-name-nondirectory buffer-file-name))
8149 "???"))
8150 ((symbolp org-category) (symbol-name org-category))
8151 (t org-category)))
8152 beg end cat pos optionp)
8153 (org-unmodified
8154 (save-excursion
8155 (save-restriction
8156 (widen)
8157 (goto-char (point-min))
8158 (put-text-property (point) (point-max) 'org-category def-cat)
8159 (while (re-search-forward
8160 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8161 (setq pos (match-end 0)
8162 optionp (equal (char-after (match-beginning 0)) ?#)
8163 cat (org-trim (match-string 2)))
8164 (if optionp
8165 (setq beg (point-at-bol) end (point-max))
8166 (org-back-to-heading t)
8167 (setq beg (point) end (org-end-of-subtree t t)))
8168 (put-text-property beg end 'org-category cat)
8169 (goto-char pos)))))))
8171 (defun org-archive-all-done (&optional tag)
8172 "Archive sublevels of the current tree without open TODO items.
8173 If the cursor is not on a headline, try all level 1 trees. If
8174 it is on a headline, try all direct children.
8175 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8176 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8177 (rea (concat ".*:" org-archive-tag ":"))
8178 (begm (make-marker))
8179 (endm (make-marker))
8180 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8181 "Move subtree to archive (no open TODO items)? "))
8182 beg end (cntarch 0))
8183 (if (org-on-heading-p)
8184 (progn
8185 (setq re1 (concat "^" (regexp-quote
8186 (make-string
8187 (1+ (- (match-end 0) (match-beginning 0) 1))
8188 ?*))
8189 " "))
8190 (move-marker begm (point))
8191 (move-marker endm (org-end-of-subtree t)))
8192 (setq re1 "^* ")
8193 (move-marker begm (point-min))
8194 (move-marker endm (point-max)))
8195 (save-excursion
8196 (goto-char begm)
8197 (while (re-search-forward re1 endm t)
8198 (setq beg (match-beginning 0)
8199 end (save-excursion (org-end-of-subtree t) (point)))
8200 (goto-char beg)
8201 (if (re-search-forward re end t)
8202 (goto-char end)
8203 (goto-char beg)
8204 (if (and (or (not tag) (not (looking-at rea)))
8205 (y-or-n-p question))
8206 (progn
8207 (if tag
8208 (org-toggle-tag org-archive-tag 'on)
8209 (org-archive-subtree))
8210 (setq cntarch (1+ cntarch)))
8211 (goto-char end)))))
8212 (message "%d trees archived" cntarch)))
8214 (defun org-cycle-hide-drawers (state)
8215 "Re-hide all drawers after a visibility state change."
8216 (when (and (org-mode-p)
8217 (not (memq state '(overview folded))))
8218 (save-excursion
8219 (let* ((globalp (memq state '(contents all)))
8220 (beg (if globalp (point-min) (point)))
8221 (end (if globalp (point-max) (org-end-of-subtree t))))
8222 (goto-char beg)
8223 (while (re-search-forward org-drawer-regexp end t)
8224 (org-flag-drawer t))))))
8226 (defun org-flag-drawer (flag)
8227 (save-excursion
8228 (beginning-of-line 1)
8229 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8230 (let ((b (match-end 0))
8231 (outline-regexp org-outline-regexp))
8232 (if (re-search-forward
8233 "^[ \t]*:END:"
8234 (save-excursion (outline-next-heading) (point)) t)
8235 (outline-flag-region b (point-at-eol) flag)
8236 (error ":END: line missing"))))))
8238 (defun org-cycle-hide-archived-subtrees (state)
8239 "Re-hide all archived subtrees after a visibility state change."
8240 (when (and (not org-cycle-open-archived-trees)
8241 (not (memq state '(overview folded))))
8242 (save-excursion
8243 (let* ((globalp (memq state '(contents all)))
8244 (beg (if globalp (point-min) (point)))
8245 (end (if globalp (point-max) (org-end-of-subtree t))))
8246 (org-hide-archived-subtrees beg end)
8247 (goto-char beg)
8248 (if (looking-at (concat ".*:" org-archive-tag ":"))
8249 (message "%s" (substitute-command-keys
8250 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8252 (defun org-force-cycle-archived ()
8253 "Cycle subtree even if it is archived."
8254 (interactive)
8255 (setq this-command 'org-cycle)
8256 (let ((org-cycle-open-archived-trees t))
8257 (call-interactively 'org-cycle)))
8259 (defun org-hide-archived-subtrees (beg end)
8260 "Re-hide all archived subtrees after a visibility state change."
8261 (save-excursion
8262 (let* ((re (concat ":" org-archive-tag ":")))
8263 (goto-char beg)
8264 (while (re-search-forward re end t)
8265 (and (org-on-heading-p) (hide-subtree))
8266 (org-end-of-subtree t)))))
8268 (defun org-toggle-tag (tag &optional onoff)
8269 "Toggle the tag TAG for the current line.
8270 If ONOFF is `on' or `off', don't toggle but set to this state."
8271 (unless (org-on-heading-p t) (error "Not on headling"))
8272 (let (res current)
8273 (save-excursion
8274 (beginning-of-line)
8275 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8276 (point-at-eol) t)
8277 (progn
8278 (setq current (match-string 1))
8279 (replace-match ""))
8280 (setq current ""))
8281 (setq current (nreverse (org-split-string current ":")))
8282 (cond
8283 ((eq onoff 'on)
8284 (setq res t)
8285 (or (member tag current) (push tag current)))
8286 ((eq onoff 'off)
8287 (or (not (member tag current)) (setq current (delete tag current))))
8288 (t (if (member tag current)
8289 (setq current (delete tag current))
8290 (setq res t)
8291 (push tag current))))
8292 (end-of-line 1)
8293 (if current
8294 (progn
8295 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8296 (org-set-tags nil t))
8297 (delete-horizontal-space))
8298 (run-hooks 'org-after-tags-change-hook))
8299 res))
8301 (defun org-toggle-archive-tag (&optional arg)
8302 "Toggle the archive tag for the current headline.
8303 With prefix ARG, check all children of current headline and offer tagging
8304 the children that do not contain any open TODO items."
8305 (interactive "P")
8306 (if arg
8307 (org-archive-all-done 'tag)
8308 (let (set)
8309 (save-excursion
8310 (org-back-to-heading t)
8311 (setq set (org-toggle-tag org-archive-tag))
8312 (when set (hide-subtree)))
8313 (and set (beginning-of-line 1))
8314 (message "Subtree %s" (if set "archived" "unarchived")))))
8317 ;;;; Tables
8319 ;;; The table editor
8321 ;; Watch out: Here we are talking about two different kind of tables.
8322 ;; Most of the code is for the tables created with the Org-mode table editor.
8323 ;; Sometimes, we talk about tables created and edited with the table.el
8324 ;; Emacs package. We call the former org-type tables, and the latter
8325 ;; table.el-type tables.
8327 (defun org-before-change-function (beg end)
8328 "Every change indicates that a table might need an update."
8329 (setq org-table-may-need-update t))
8331 (defconst org-table-line-regexp "^[ \t]*|"
8332 "Detects an org-type table line.")
8333 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8334 "Detects an org-type table line.")
8335 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8336 "Detects a table line marked for automatic recalculation.")
8337 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8338 "Detects a table line marked for automatic recalculation.")
8339 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8340 "Detects a table line marked for automatic recalculation.")
8341 (defconst org-table-hline-regexp "^[ \t]*|-"
8342 "Detects an org-type table hline.")
8343 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8344 "Detects a table-type table hline.")
8345 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8346 "Detects an org-type or table-type table.")
8347 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8348 "Searching from within a table (any type) this finds the first line
8349 outside the table.")
8350 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8351 "Searching from within a table (any type) this finds the first line
8352 outside the table.")
8354 (defvar org-table-last-highlighted-reference nil)
8355 (defvar org-table-formula-history nil)
8357 (defvar org-table-column-names nil
8358 "Alist with column names, derived from the `!' line.")
8359 (defvar org-table-column-name-regexp nil
8360 "Regular expression matching the current column names.")
8361 (defvar org-table-local-parameters nil
8362 "Alist with parameter names, derived from the `$' line.")
8363 (defvar org-table-named-field-locations nil
8364 "Alist with locations of named fields.")
8366 (defvar org-table-current-line-types nil
8367 "Table row types, non-nil only for the duration of a comand.")
8368 (defvar org-table-current-begin-line nil
8369 "Table begin line, non-nil only for the duration of a comand.")
8370 (defvar org-table-current-begin-pos nil
8371 "Table begin position, non-nil only for the duration of a comand.")
8372 (defvar org-table-dlines nil
8373 "Vector of data line line numbers in the current table.")
8374 (defvar org-table-hlines nil
8375 "Vector of hline line numbers in the current table.")
8377 (defconst org-table-range-regexp
8378 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8379 ;; 1 2 3 4 5
8380 "Regular expression for matching ranges in formulas.")
8382 (defconst org-table-range-regexp2
8383 (concat
8384 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8385 "\\.\\."
8386 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8387 "Match a range for reference display.")
8389 (defconst org-table-translate-regexp
8390 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8391 "Match a reference that needs translation, for reference display.")
8393 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8395 (defun org-table-create-with-table.el ()
8396 "Use the table.el package to insert a new table.
8397 If there is already a table at point, convert between Org-mode tables
8398 and table.el tables."
8399 (interactive)
8400 (require 'table)
8401 (cond
8402 ((org-at-table.el-p)
8403 (if (y-or-n-p "Convert table to Org-mode table? ")
8404 (org-table-convert)))
8405 ((org-at-table-p)
8406 (if (y-or-n-p "Convert table to table.el table? ")
8407 (org-table-convert)))
8408 (t (call-interactively 'table-insert))))
8410 (defun org-table-create-or-convert-from-region (arg)
8411 "Convert region to table, or create an empty table.
8412 If there is an active region, convert it to a table, using the function
8413 `org-table-convert-region'. See the documentation of that function
8414 to learn how the prefix argument is interpreted to determine the field
8415 separator.
8416 If there is no such region, create an empty table with `org-table-create'."
8417 (interactive "P")
8418 (if (org-region-active-p)
8419 (org-table-convert-region (region-beginning) (region-end) arg)
8420 (org-table-create arg)))
8422 (defun org-table-create (&optional size)
8423 "Query for a size and insert a table skeleton.
8424 SIZE is a string Columns x Rows like for example \"3x2\"."
8425 (interactive "P")
8426 (unless size
8427 (setq size (read-string
8428 (concat "Table size Columns x Rows [e.g. "
8429 org-table-default-size "]: ")
8430 "" nil org-table-default-size)))
8432 (let* ((pos (point))
8433 (indent (make-string (current-column) ?\ ))
8434 (split (org-split-string size " *x *"))
8435 (rows (string-to-number (nth 1 split)))
8436 (columns (string-to-number (car split)))
8437 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8438 "\n")))
8439 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8440 (point-at-bol) (point)))
8441 (beginning-of-line 1)
8442 (newline))
8443 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8444 (dotimes (i rows) (insert line))
8445 (goto-char pos)
8446 (if (> rows 1)
8447 ;; Insert a hline after the first row.
8448 (progn
8449 (end-of-line 1)
8450 (insert "\n|-")
8451 (goto-char pos)))
8452 (org-table-align)))
8454 (defun org-table-convert-region (beg0 end0 &optional separator)
8455 "Convert region to a table.
8456 The region goes from BEG0 to END0, but these borders will be moved
8457 slightly, to make sure a beginning of line in the first line is included.
8459 SEPARATOR specifies the field separator in the lines. It can have the
8460 following values:
8462 '(4) Use the comma as a field separator
8463 '(16) Use a TAB as field separator
8464 integer When a number, use that many spaces as field separator
8465 nil When nil, the command tries to be smart and figure out the
8466 separator in the following way:
8467 - when each line contains a TAB, assume TAB-separated material
8468 - when each line contains a comme, assume CSV material
8469 - else, assume one or more SPACE charcters as separator."
8470 (interactive "rP")
8471 (let* ((beg (min beg0 end0))
8472 (end (max beg0 end0))
8474 (goto-char beg)
8475 (beginning-of-line 1)
8476 (setq beg (move-marker (make-marker) (point)))
8477 (goto-char end)
8478 (if (bolp) (backward-char 1) (end-of-line 1))
8479 (setq end (move-marker (make-marker) (point)))
8480 ;; Get the right field separator
8481 (unless separator
8482 (goto-char beg)
8483 (setq separator
8484 (cond
8485 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8486 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8487 (t 1))))
8488 (setq re (cond
8489 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8490 ((equal separator '(16)) "^\\|\t")
8491 ((integerp separator)
8492 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8493 (t (error "This should not happen"))))
8494 (goto-char beg)
8495 (while (re-search-forward re end t)
8496 (replace-match "| " t t))
8497 (goto-char beg)
8498 (insert " ")
8499 (org-table-align)))
8501 (defun org-table-import (file arg)
8502 "Import FILE as a table.
8503 The file is assumed to be tab-separated. Such files can be produced by most
8504 spreadsheet and database applications. If no tabs (at least one per line)
8505 are found, lines will be split on whitespace into fields."
8506 (interactive "f\nP")
8507 (or (bolp) (newline))
8508 (let ((beg (point))
8509 (pm (point-max)))
8510 (insert-file-contents file)
8511 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8513 (defun org-table-export ()
8514 "Export table as a tab-separated file.
8515 Such a file can be imported into a spreadsheet program like Excel."
8516 (interactive)
8517 (let* ((beg (org-table-begin))
8518 (end (org-table-end))
8519 (table (buffer-substring beg end))
8520 (file (read-file-name "Export table to: "))
8521 buf)
8522 (unless (or (not (file-exists-p file))
8523 (y-or-n-p (format "Overwrite file %s? " file)))
8524 (error "Abort"))
8525 (with-current-buffer (find-file-noselect file)
8526 (setq buf (current-buffer))
8527 (erase-buffer)
8528 (fundamental-mode)
8529 (insert table)
8530 (goto-char (point-min))
8531 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8532 (replace-match "" t t)
8533 (end-of-line 1))
8534 (goto-char (point-min))
8535 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8536 (replace-match "" t t)
8537 (goto-char (min (1+ (point)) (point-max))))
8538 (goto-char (point-min))
8539 (while (re-search-forward "^-[-+]*$" nil t)
8540 (replace-match "")
8541 (if (looking-at "\n")
8542 (delete-char 1)))
8543 (goto-char (point-min))
8544 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8545 (replace-match "\t" t t))
8546 (save-buffer))
8547 (kill-buffer buf)))
8549 (defvar org-table-aligned-begin-marker (make-marker)
8550 "Marker at the beginning of the table last aligned.
8551 Used to check if cursor still is in that table, to minimize realignment.")
8552 (defvar org-table-aligned-end-marker (make-marker)
8553 "Marker at the end of the table last aligned.
8554 Used to check if cursor still is in that table, to minimize realignment.")
8555 (defvar org-table-last-alignment nil
8556 "List of flags for flushright alignment, from the last re-alignment.
8557 This is being used to correctly align a single field after TAB or RET.")
8558 (defvar org-table-last-column-widths nil
8559 "List of max width of fields in each column.
8560 This is being used to correctly align a single field after TAB or RET.")
8561 (defvar org-table-overlay-coordinates nil
8562 "Overlay coordinates after each align of a table.")
8563 (make-variable-buffer-local 'org-table-overlay-coordinates)
8565 (defvar org-last-recalc-line nil)
8566 (defconst org-narrow-column-arrow "=>"
8567 "Used as display property in narrowed table columns.")
8569 (defun org-table-align ()
8570 "Align the table at point by aligning all vertical bars."
8571 (interactive)
8572 (let* (
8573 ;; Limits of table
8574 (beg (org-table-begin))
8575 (end (org-table-end))
8576 ;; Current cursor position
8577 (linepos (org-current-line))
8578 (colpos (org-table-current-column))
8579 (winstart (window-start))
8580 (winstartline (org-current-line (min winstart (1- (point-max)))))
8581 lines (new "") lengths l typenums ty fields maxfields i
8582 column
8583 (indent "") cnt frac
8584 rfmt hfmt
8585 (spaces '(1 . 1))
8586 (sp1 (car spaces))
8587 (sp2 (cdr spaces))
8588 (rfmt1 (concat
8589 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8590 (hfmt1 (concat
8591 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8592 emptystrings links dates emph narrow fmax f1 len c e)
8593 (untabify beg end)
8594 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8595 ;; Check if we have links or dates
8596 (goto-char beg)
8597 (setq links (re-search-forward org-bracket-link-regexp end t))
8598 (goto-char beg)
8599 (setq emph (and org-hide-emphasis-markers
8600 (re-search-forward org-emph-re end t)))
8601 (goto-char beg)
8602 (setq dates (and org-display-custom-times
8603 (re-search-forward org-ts-regexp-both end t)))
8604 ;; Make sure the link properties are right
8605 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8606 ;; Make sure the date properties are right
8607 (when dates (goto-char beg) (while (org-activate-dates end)))
8608 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8610 ;; Check if we are narrowing any columns
8611 (goto-char beg)
8612 (setq narrow (and org-format-transports-properties-p
8613 (re-search-forward "<[0-9]+>" end t)))
8614 ;; Get the rows
8615 (setq lines (org-split-string
8616 (buffer-substring beg end) "\n"))
8617 ;; Store the indentation of the first line
8618 (if (string-match "^ *" (car lines))
8619 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8620 ;; Mark the hlines by setting the corresponding element to nil
8621 ;; At the same time, we remove trailing space.
8622 (setq lines (mapcar (lambda (l)
8623 (if (string-match "^ *|-" l)
8625 (if (string-match "[ \t]+$" l)
8626 (substring l 0 (match-beginning 0))
8627 l)))
8628 lines))
8629 ;; Get the data fields by splitting the lines.
8630 (setq fields (mapcar
8631 (lambda (l)
8632 (org-split-string l " *| *"))
8633 (delq nil (copy-sequence lines))))
8634 ;; How many fields in the longest line?
8635 (condition-case nil
8636 (setq maxfields (apply 'max (mapcar 'length fields)))
8637 (error
8638 (kill-region beg end)
8639 (org-table-create org-table-default-size)
8640 (error "Empty table - created default table")))
8641 ;; A list of empty strings to fill any short rows on output
8642 (setq emptystrings (make-list maxfields ""))
8643 ;; Check for special formatting.
8644 (setq i -1)
8645 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8646 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8647 ;; Check if there is an explicit width specified
8648 (when narrow
8649 (setq c column fmax nil)
8650 (while c
8651 (setq e (pop c))
8652 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8653 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8654 ;; Find fields that are wider than fmax, and shorten them
8655 (when fmax
8656 (loop for xx in column do
8657 (when (and (stringp xx)
8658 (> (org-string-width xx) fmax))
8659 (org-add-props xx nil
8660 'help-echo
8661 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8662 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8663 (unless (> f1 1)
8664 (error "Cannot narrow field starting with wide link \"%s\""
8665 (match-string 0 xx)))
8666 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8667 (add-text-properties (- f1 2) f1
8668 (list 'display org-narrow-column-arrow)
8669 xx)))))
8670 ;; Get the maximum width for each column
8671 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8672 ;; Get the fraction of numbers, to decide about alignment of the column
8673 (setq cnt 0 frac 0.0)
8674 (loop for x in column do
8675 (if (equal x "")
8677 (setq frac ( / (+ (* frac cnt)
8678 (if (string-match org-table-number-regexp x) 1 0))
8679 (setq cnt (1+ cnt))))))
8680 (push (>= frac org-table-number-fraction) typenums))
8681 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8683 ;; Store the alignment of this table, for later editing of single fields
8684 (setq org-table-last-alignment typenums
8685 org-table-last-column-widths lengths)
8687 ;; With invisible characters, `format' does not get the field width right
8688 ;; So we need to make these fields wide by hand.
8689 (when (or links emph)
8690 (loop for i from 0 upto (1- maxfields) do
8691 (setq len (nth i lengths))
8692 (loop for j from 0 upto (1- (length fields)) do
8693 (setq c (nthcdr i (car (nthcdr j fields))))
8694 (if (and (stringp (car c))
8695 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8696 ; (string-match org-bracket-link-regexp (car c))
8697 (< (org-string-width (car c)) len))
8698 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8700 ;; Compute the formats needed for output of the table
8701 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8702 (while (setq l (pop lengths))
8703 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8704 (setq rfmt (concat rfmt (format rfmt1 ty l))
8705 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8706 (setq rfmt (concat rfmt "\n")
8707 hfmt (concat (substring hfmt 0 -1) "|\n"))
8709 (setq new (mapconcat
8710 (lambda (l)
8711 (if l (apply 'format rfmt
8712 (append (pop fields) emptystrings))
8713 hfmt))
8714 lines ""))
8715 ;; Replace the old one
8716 (delete-region beg end)
8717 (move-marker end nil)
8718 (move-marker org-table-aligned-begin-marker (point))
8719 (insert new)
8720 (move-marker org-table-aligned-end-marker (point))
8721 (when (and orgtbl-mode (not (org-mode-p)))
8722 (goto-char org-table-aligned-begin-marker)
8723 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8724 ;; Try to move to the old location
8725 (goto-line winstartline)
8726 (setq winstart (point-at-bol))
8727 (goto-line linepos)
8728 (set-window-start (selected-window) winstart 'noforce)
8729 (org-table-goto-column colpos)
8730 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8731 (setq org-table-may-need-update nil)
8734 (defun org-string-width (s)
8735 "Compute width of string, ignoring invisible characters.
8736 This ignores character with invisibility property `org-link', and also
8737 characters with property `org-cwidth', because these will become invisible
8738 upon the next fontification round."
8739 (let (b l)
8740 (when (or (eq t buffer-invisibility-spec)
8741 (assq 'org-link buffer-invisibility-spec))
8742 (while (setq b (text-property-any 0 (length s)
8743 'invisible 'org-link s))
8744 (setq s (concat (substring s 0 b)
8745 (substring s (or (next-single-property-change
8746 b 'invisible s) (length s)))))))
8747 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8748 (setq s (concat (substring s 0 b)
8749 (substring s (or (next-single-property-change
8750 b 'org-cwidth s) (length s))))))
8751 (setq l (string-width s) b -1)
8752 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8753 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8756 (defun org-table-begin (&optional table-type)
8757 "Find the beginning of the table and return its position.
8758 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8759 (save-excursion
8760 (if (not (re-search-backward
8761 (if table-type org-table-any-border-regexp
8762 org-table-border-regexp)
8763 nil t))
8764 (progn (goto-char (point-min)) (point))
8765 (goto-char (match-beginning 0))
8766 (beginning-of-line 2)
8767 (point))))
8769 (defun org-table-end (&optional table-type)
8770 "Find the end of the table and return its position.
8771 With argument TABLE-TYPE, go to the end of a table.el-type table."
8772 (save-excursion
8773 (if (not (re-search-forward
8774 (if table-type org-table-any-border-regexp
8775 org-table-border-regexp)
8776 nil t))
8777 (goto-char (point-max))
8778 (goto-char (match-beginning 0)))
8779 (point-marker)))
8781 (defun org-table-justify-field-maybe (&optional new)
8782 "Justify the current field, text to left, number to right.
8783 Optional argument NEW may specify text to replace the current field content."
8784 (cond
8785 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8786 ((org-at-table-hline-p))
8787 ((and (not new)
8788 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8789 (current-buffer)))
8790 (< (point) org-table-aligned-begin-marker)
8791 (>= (point) org-table-aligned-end-marker)))
8792 ;; This is not the same table, force a full re-align
8793 (setq org-table-may-need-update t))
8794 (t ;; realign the current field, based on previous full realign
8795 (let* ((pos (point)) s
8796 (col (org-table-current-column))
8797 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8798 l f n o e)
8799 (when (> col 0)
8800 (skip-chars-backward "^|\n")
8801 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8802 (progn
8803 (setq s (match-string 1)
8804 o (match-string 0)
8805 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8806 e (not (= (match-beginning 2) (match-end 2))))
8807 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8808 l (if e "|" (setq org-table-may-need-update t) ""))
8809 n (format f s))
8810 (if new
8811 (if (<= (length new) l) ;; FIXME: length -> str-width?
8812 (setq n (format f new))
8813 (setq n (concat new "|") org-table-may-need-update t)))
8814 (or (equal n o)
8815 (let (org-table-may-need-update)
8816 (replace-match n t t))))
8817 (setq org-table-may-need-update t))
8818 (goto-char pos))))))
8820 (defun org-table-next-field ()
8821 "Go to the next field in the current table, creating new lines as needed.
8822 Before doing so, re-align the table if necessary."
8823 (interactive)
8824 (org-table-maybe-eval-formula)
8825 (org-table-maybe-recalculate-line)
8826 (if (and org-table-automatic-realign
8827 org-table-may-need-update)
8828 (org-table-align))
8829 (let ((end (org-table-end)))
8830 (if (org-at-table-hline-p)
8831 (end-of-line 1))
8832 (condition-case nil
8833 (progn
8834 (re-search-forward "|" end)
8835 (if (looking-at "[ \t]*$")
8836 (re-search-forward "|" end))
8837 (if (and (looking-at "-")
8838 org-table-tab-jumps-over-hlines
8839 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8840 (goto-char (match-beginning 1)))
8841 (if (looking-at "-")
8842 (progn
8843 (beginning-of-line 0)
8844 (org-table-insert-row 'below))
8845 (if (looking-at " ") (forward-char 1))))
8846 (error
8847 (org-table-insert-row 'below)))))
8849 (defun org-table-previous-field ()
8850 "Go to the previous field in the table.
8851 Before doing so, re-align the table if necessary."
8852 (interactive)
8853 (org-table-justify-field-maybe)
8854 (org-table-maybe-recalculate-line)
8855 (if (and org-table-automatic-realign
8856 org-table-may-need-update)
8857 (org-table-align))
8858 (if (org-at-table-hline-p)
8859 (end-of-line 1))
8860 (re-search-backward "|" (org-table-begin))
8861 (re-search-backward "|" (org-table-begin))
8862 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8863 (re-search-backward "|" (org-table-begin)))
8864 (if (looking-at "| ?")
8865 (goto-char (match-end 0))))
8867 (defun org-table-next-row ()
8868 "Go to the next row (same column) in the current table.
8869 Before doing so, re-align the table if necessary."
8870 (interactive)
8871 (org-table-maybe-eval-formula)
8872 (org-table-maybe-recalculate-line)
8873 (if (or (looking-at "[ \t]*$")
8874 (save-excursion (skip-chars-backward " \t") (bolp)))
8875 (newline)
8876 (if (and org-table-automatic-realign
8877 org-table-may-need-update)
8878 (org-table-align))
8879 (let ((col (org-table-current-column)))
8880 (beginning-of-line 2)
8881 (if (or (not (org-at-table-p))
8882 (org-at-table-hline-p))
8883 (progn
8884 (beginning-of-line 0)
8885 (org-table-insert-row 'below)))
8886 (org-table-goto-column col)
8887 (skip-chars-backward "^|\n\r")
8888 (if (looking-at " ") (forward-char 1)))))
8890 (defun org-table-copy-down (n)
8891 "Copy a field down in the current column.
8892 If the field at the cursor is empty, copy into it the content of the nearest
8893 non-empty field above. With argument N, use the Nth non-empty field.
8894 If the current field is not empty, it is copied down to the next row, and
8895 the cursor is moved with it. Therefore, repeating this command causes the
8896 column to be filled row-by-row.
8897 If the variable `org-table-copy-increment' is non-nil and the field is an
8898 integer or a timestamp, it will be incremented while copying. In the case of
8899 a timestamp, if the cursor is on the year, change the year. If it is on the
8900 month or the day, change that. Point will stay on the current date field
8901 in order to easily repeat the interval."
8902 (interactive "p")
8903 (let* ((colpos (org-table-current-column))
8904 (col (current-column))
8905 (field (org-table-get-field))
8906 (non-empty (string-match "[^ \t]" field))
8907 (beg (org-table-begin))
8908 txt)
8909 (org-table-check-inside-data-field)
8910 (if non-empty
8911 (progn
8912 (setq txt (org-trim field))
8913 (org-table-next-row)
8914 (org-table-blank-field))
8915 (save-excursion
8916 (setq txt
8917 (catch 'exit
8918 (while (progn (beginning-of-line 1)
8919 (re-search-backward org-table-dataline-regexp
8920 beg t))
8921 (org-table-goto-column colpos t)
8922 (if (and (looking-at
8923 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8924 (= (setq n (1- n)) 0))
8925 (throw 'exit (match-string 1))))))))
8926 (if txt
8927 (progn
8928 (if (and org-table-copy-increment
8929 (string-match "^[0-9]+$" txt))
8930 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8931 (insert txt)
8932 (move-to-column col)
8933 (if (and org-table-copy-increment (org-at-timestamp-p t))
8934 (org-timestamp-up 1)
8935 (org-table-maybe-recalculate-line))
8936 (org-table-align)
8937 (move-to-column col))
8938 (error "No non-empty field found"))))
8940 (defun org-table-check-inside-data-field ()
8941 "Is point inside a table data field?
8942 I.e. not on a hline or before the first or after the last column?
8943 This actually throws an error, so it aborts the current command."
8944 (if (or (not (org-at-table-p))
8945 (= (org-table-current-column) 0)
8946 (org-at-table-hline-p)
8947 (looking-at "[ \t]*$"))
8948 (error "Not in table data field")))
8950 (defvar org-table-clip nil
8951 "Clipboard for table regions.")
8953 (defun org-table-blank-field ()
8954 "Blank the current table field or active region."
8955 (interactive)
8956 (org-table-check-inside-data-field)
8957 (if (and (interactive-p) (org-region-active-p))
8958 (let (org-table-clip)
8959 (org-table-cut-region (region-beginning) (region-end)))
8960 (skip-chars-backward "^|")
8961 (backward-char 1)
8962 (if (looking-at "|[^|\n]+")
8963 (let* ((pos (match-beginning 0))
8964 (match (match-string 0))
8965 (len (org-string-width match)))
8966 (replace-match (concat "|" (make-string (1- len) ?\ )))
8967 (goto-char (+ 2 pos))
8968 (substring match 1)))))
8970 (defun org-table-get-field (&optional n replace)
8971 "Return the value of the field in column N of current row.
8972 N defaults to current field.
8973 If REPLACE is a string, replace field with this value. The return value
8974 is always the old value."
8975 (and n (org-table-goto-column n))
8976 (skip-chars-backward "^|\n")
8977 (backward-char 1)
8978 (if (looking-at "|[^|\r\n]*")
8979 (let* ((pos (match-beginning 0))
8980 (val (buffer-substring (1+ pos) (match-end 0))))
8981 (if replace
8982 (replace-match (concat "|" replace) t t))
8983 (goto-char (min (point-at-eol) (+ 2 pos)))
8984 val)
8985 (forward-char 1) ""))
8987 (defun org-table-field-info (arg)
8988 "Show info about the current field, and highlight any reference at point."
8989 (interactive "P")
8990 (org-table-get-specials)
8991 (save-excursion
8992 (let* ((pos (point))
8993 (col (org-table-current-column))
8994 (cname (car (rassoc (int-to-string col) org-table-column-names)))
8995 (name (car (rassoc (list (org-current-line) col)
8996 org-table-named-field-locations)))
8997 (eql (org-table-get-stored-formulas))
8998 (dline (org-table-current-dline))
8999 (ref (format "@%d$%d" dline col))
9000 (ref1 (org-table-convert-refs-to-an ref))
9001 (fequation (or (assoc name eql) (assoc ref eql)))
9002 (cequation (assoc (int-to-string col) eql))
9003 (eqn (or fequation cequation)))
9004 (goto-char pos)
9005 (condition-case nil
9006 (org-table-show-reference 'local)
9007 (error nil))
9008 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9009 dline col
9010 (if cname (concat " or $" cname) "")
9011 dline col ref1
9012 (if name (concat " or $" name) "")
9013 ;; FIXME: formula info not correct if special table line
9014 (if eqn
9015 (concat ", formula: "
9016 (org-table-formula-to-user
9017 (concat
9018 (if (string-match "^[$@]"(car eqn)) "" "$")
9019 (car eqn) "=" (cdr eqn))))
9020 "")))))
9022 (defun org-table-current-column ()
9023 "Find out which column we are in.
9024 When called interactively, column is also displayed in echo area."
9025 (interactive)
9026 (if (interactive-p) (org-table-check-inside-data-field))
9027 (save-excursion
9028 (let ((cnt 0) (pos (point)))
9029 (beginning-of-line 1)
9030 (while (search-forward "|" pos t)
9031 (setq cnt (1+ cnt)))
9032 (if (interactive-p) (message "This is table column %d" cnt))
9033 cnt)))
9035 (defun org-table-current-dline ()
9036 "Find out what table data line we are in.
9037 Only datalins count for this."
9038 (interactive)
9039 (if (interactive-p) (org-table-check-inside-data-field))
9040 (save-excursion
9041 (let ((cnt 0) (pos (point)))
9042 (goto-char (org-table-begin))
9043 (while (<= (point) pos)
9044 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9045 (beginning-of-line 2))
9046 (if (interactive-p) (message "This is table line %d" cnt))
9047 cnt)))
9049 (defun org-table-goto-column (n &optional on-delim force)
9050 "Move the cursor to the Nth column in the current table line.
9051 With optional argument ON-DELIM, stop with point before the left delimiter
9052 of the field.
9053 If there are less than N fields, just go to after the last delimiter.
9054 However, when FORCE is non-nil, create new columns if necessary."
9055 (interactive "p")
9056 (let ((pos (point-at-eol)))
9057 (beginning-of-line 1)
9058 (when (> n 0)
9059 (while (and (> (setq n (1- n)) -1)
9060 (or (search-forward "|" pos t)
9061 (and force
9062 (progn (end-of-line 1)
9063 (skip-chars-backward "^|")
9064 (insert " | "))))))
9065 ; (backward-char 2) t)))))
9066 (when (and force (not (looking-at ".*|")))
9067 (save-excursion (end-of-line 1) (insert " | ")))
9068 (if on-delim
9069 (backward-char 1)
9070 (if (looking-at " ") (forward-char 1))))))
9072 (defun org-at-table-p (&optional table-type)
9073 "Return t if the cursor is inside an org-type table.
9074 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9075 (if org-enable-table-editor
9076 (save-excursion
9077 (beginning-of-line 1)
9078 (looking-at (if table-type org-table-any-line-regexp
9079 org-table-line-regexp)))
9080 nil))
9082 (defun org-at-table.el-p ()
9083 "Return t if and only if we are at a table.el table."
9084 (and (org-at-table-p 'any)
9085 (save-excursion
9086 (goto-char (org-table-begin 'any))
9087 (looking-at org-table1-hline-regexp))))
9089 (defun org-table-recognize-table.el ()
9090 "If there is a table.el table nearby, recognize it and move into it."
9091 (if org-table-tab-recognizes-table.el
9092 (if (org-at-table.el-p)
9093 (progn
9094 (beginning-of-line 1)
9095 (if (looking-at org-table-dataline-regexp)
9097 (if (looking-at org-table1-hline-regexp)
9098 (progn
9099 (beginning-of-line 2)
9100 (if (looking-at org-table-any-border-regexp)
9101 (beginning-of-line -1)))))
9102 (if (re-search-forward "|" (org-table-end t) t)
9103 (progn
9104 (require 'table)
9105 (if (table--at-cell-p (point))
9107 (message "recognizing table.el table...")
9108 (table-recognize-table)
9109 (message "recognizing table.el table...done")))
9110 (error "This should not happen..."))
9112 nil)
9113 nil))
9115 (defun org-at-table-hline-p ()
9116 "Return t if the cursor is inside a hline in a table."
9117 (if org-enable-table-editor
9118 (save-excursion
9119 (beginning-of-line 1)
9120 (looking-at org-table-hline-regexp))
9121 nil))
9123 (defun org-table-insert-column ()
9124 "Insert a new column into the table."
9125 (interactive)
9126 (if (not (org-at-table-p))
9127 (error "Not at a table"))
9128 (org-table-find-dataline)
9129 (let* ((col (max 1 (org-table-current-column)))
9130 (beg (org-table-begin))
9131 (end (org-table-end))
9132 ;; Current cursor position
9133 (linepos (org-current-line))
9134 (colpos col))
9135 (goto-char beg)
9136 (while (< (point) end)
9137 (if (org-at-table-hline-p)
9139 (org-table-goto-column col t)
9140 (insert "| "))
9141 (beginning-of-line 2))
9142 (move-marker end nil)
9143 (goto-line linepos)
9144 (org-table-goto-column colpos)
9145 (org-table-align)
9146 (org-table-fix-formulas "$" nil (1- col) 1)))
9148 (defun org-table-find-dataline ()
9149 "Find a dataline in the current table, which is needed for column commands."
9150 (if (and (org-at-table-p)
9151 (not (org-at-table-hline-p)))
9153 (let ((col (current-column))
9154 (end (org-table-end)))
9155 (move-to-column col)
9156 (while (and (< (point) end)
9157 (or (not (= (current-column) col))
9158 (org-at-table-hline-p)))
9159 (beginning-of-line 2)
9160 (move-to-column col))
9161 (if (and (org-at-table-p)
9162 (not (org-at-table-hline-p)))
9164 (error
9165 "Please position cursor in a data line for column operations")))))
9167 (defun org-table-delete-column ()
9168 "Delete a column from the table."
9169 (interactive)
9170 (if (not (org-at-table-p))
9171 (error "Not at a table"))
9172 (org-table-find-dataline)
9173 (org-table-check-inside-data-field)
9174 (let* ((col (org-table-current-column))
9175 (beg (org-table-begin))
9176 (end (org-table-end))
9177 ;; Current cursor position
9178 (linepos (org-current-line))
9179 (colpos col))
9180 (goto-char beg)
9181 (while (< (point) end)
9182 (if (org-at-table-hline-p)
9184 (org-table-goto-column col t)
9185 (and (looking-at "|[^|\n]+|")
9186 (replace-match "|")))
9187 (beginning-of-line 2))
9188 (move-marker end nil)
9189 (goto-line linepos)
9190 (org-table-goto-column colpos)
9191 (org-table-align)
9192 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9193 col -1 col)))
9195 (defun org-table-move-column-right ()
9196 "Move column to the right."
9197 (interactive)
9198 (org-table-move-column nil))
9199 (defun org-table-move-column-left ()
9200 "Move column to the left."
9201 (interactive)
9202 (org-table-move-column 'left))
9204 (defun org-table-move-column (&optional left)
9205 "Move the current column to the right. With arg LEFT, move to the left."
9206 (interactive "P")
9207 (if (not (org-at-table-p))
9208 (error "Not at a table"))
9209 (org-table-find-dataline)
9210 (org-table-check-inside-data-field)
9211 (let* ((col (org-table-current-column))
9212 (col1 (if left (1- col) col))
9213 (beg (org-table-begin))
9214 (end (org-table-end))
9215 ;; Current cursor position
9216 (linepos (org-current-line))
9217 (colpos (if left (1- col) (1+ col))))
9218 (if (and left (= col 1))
9219 (error "Cannot move column further left"))
9220 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9221 (error "Cannot move column further right"))
9222 (goto-char beg)
9223 (while (< (point) end)
9224 (if (org-at-table-hline-p)
9226 (org-table-goto-column col1 t)
9227 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9228 (replace-match "|\\2|\\1|")))
9229 (beginning-of-line 2))
9230 (move-marker end nil)
9231 (goto-line linepos)
9232 (org-table-goto-column colpos)
9233 (org-table-align)
9234 (org-table-fix-formulas
9235 "$" (list (cons (number-to-string col) (number-to-string colpos))
9236 (cons (number-to-string colpos) (number-to-string col))))))
9238 (defun org-table-move-row-down ()
9239 "Move table row down."
9240 (interactive)
9241 (org-table-move-row nil))
9242 (defun org-table-move-row-up ()
9243 "Move table row up."
9244 (interactive)
9245 (org-table-move-row 'up))
9247 (defun org-table-move-row (&optional up)
9248 "Move the current table line down. With arg UP, move it up."
9249 (interactive "P")
9250 (let* ((col (current-column))
9251 (pos (point))
9252 (hline1p (save-excursion (beginning-of-line 1)
9253 (looking-at org-table-hline-regexp)))
9254 (dline1 (org-table-current-dline))
9255 (dline2 (+ dline1 (if up -1 1)))
9256 (tonew (if up 0 2))
9257 txt hline2p)
9258 (beginning-of-line tonew)
9259 (unless (org-at-table-p)
9260 (goto-char pos)
9261 (error "Cannot move row further"))
9262 (setq hline2p (looking-at org-table-hline-regexp))
9263 (goto-char pos)
9264 (beginning-of-line 1)
9265 (setq pos (point))
9266 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9267 (delete-region (point) (1+ (point-at-eol)))
9268 (beginning-of-line tonew)
9269 (insert txt)
9270 (beginning-of-line 0)
9271 (move-to-column col)
9272 (unless (or hline1p hline2p)
9273 (org-table-fix-formulas
9274 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9275 (cons (number-to-string dline2) (number-to-string dline1)))))))
9277 (defun org-table-insert-row (&optional arg)
9278 "Insert a new row above the current line into the table.
9279 With prefix ARG, insert below the current line."
9280 (interactive "P")
9281 (if (not (org-at-table-p))
9282 (error "Not at a table"))
9283 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9284 (new (org-table-clean-line line)))
9285 ;; Fix the first field if necessary
9286 (if (string-match "^[ \t]*| *[#$] *|" line)
9287 (setq new (replace-match (match-string 0 line) t t new)))
9288 (beginning-of-line (if arg 2 1))
9289 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9290 (beginning-of-line 0)
9291 (re-search-forward "| ?" (point-at-eol) t)
9292 (and (or org-table-may-need-update org-table-overlay-coordinates)
9293 (org-table-align))
9294 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9296 (defun org-table-insert-hline (&optional above)
9297 "Insert a horizontal-line below the current line into the table.
9298 With prefix ABOVE, insert above the current line."
9299 (interactive "P")
9300 (if (not (org-at-table-p))
9301 (error "Not at a table"))
9302 (let ((line (org-table-clean-line
9303 (buffer-substring (point-at-bol) (point-at-eol))))
9304 (col (current-column)))
9305 (while (string-match "|\\( +\\)|" line)
9306 (setq line (replace-match
9307 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9308 ?-) "|") t t line)))
9309 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9310 (beginning-of-line (if above 1 2))
9311 (insert line "\n")
9312 (beginning-of-line (if above 1 -1))
9313 (move-to-column col)
9314 (and org-table-overlay-coordinates (org-table-align))))
9316 (defun org-table-hline-and-move (&optional same-column)
9317 "Insert a hline and move to the row below that line."
9318 (interactive "P")
9319 (let ((col (org-table-current-column)))
9320 (org-table-maybe-eval-formula)
9321 (org-table-maybe-recalculate-line)
9322 (org-table-insert-hline)
9323 (end-of-line 2)
9324 (if (looking-at "\n[ \t]*|-")
9325 (progn (insert "\n|") (org-table-align))
9326 (org-table-next-field))
9327 (if same-column (org-table-goto-column col))))
9329 (defun org-table-clean-line (s)
9330 "Convert a table line S into a string with only \"|\" and space.
9331 In particular, this does handle wide and invisible characters."
9332 (if (string-match "^[ \t]*|-" s)
9333 ;; It's a hline, just map the characters
9334 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9335 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9336 (setq s (replace-match
9337 (concat "|" (make-string (org-string-width (match-string 1 s))
9338 ?\ ) "|")
9339 t t s)))
9342 (defun org-table-kill-row ()
9343 "Delete the current row or horizontal line from the table."
9344 (interactive)
9345 (if (not (org-at-table-p))
9346 (error "Not at a table"))
9347 (let ((col (current-column))
9348 (dline (org-table-current-dline)))
9349 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9350 (if (not (org-at-table-p)) (beginning-of-line 0))
9351 (move-to-column col)
9352 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9353 dline -1 dline)))
9355 (defun org-table-sort-lines (with-case &optional sorting-type)
9356 "Sort table lines according to the column at point.
9358 The position of point indicates the column to be used for
9359 sorting, and the range of lines is the range between the nearest
9360 horizontal separator lines, or the entire table of no such lines
9361 exist. If point is before the first column, you will be prompted
9362 for the sorting column. If there is an active region, the mark
9363 specifies the first line and the sorting column, while point
9364 should be in the last line to be included into the sorting.
9366 The command then prompts for the sorting type which can be
9367 alphabetically, numerically, or by time (as given in a time stamp
9368 in the field). Sorting in reverse order is also possible.
9370 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9372 If SORTING-TYPE is specified when this function is called from a Lisp
9373 program, no prompting will take place. SORTING-TYPE must be a character,
9374 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9375 should be done in reverse order."
9376 (interactive "P")
9377 (let* ((thisline (org-current-line))
9378 (thiscol (org-table-current-column))
9379 beg end bcol ecol tend tbeg column lns pos)
9380 (when (equal thiscol 0)
9381 (if (interactive-p)
9382 (setq thiscol
9383 (string-to-number
9384 (read-string "Use column N for sorting: ")))
9385 (setq thiscol 1))
9386 (org-table-goto-column thiscol))
9387 (org-table-check-inside-data-field)
9388 (if (org-region-active-p)
9389 (progn
9390 (setq beg (region-beginning) end (region-end))
9391 (goto-char beg)
9392 (setq column (org-table-current-column)
9393 beg (point-at-bol))
9394 (goto-char end)
9395 (setq end (point-at-bol 2)))
9396 (setq column (org-table-current-column)
9397 pos (point)
9398 tbeg (org-table-begin)
9399 tend (org-table-end))
9400 (if (re-search-backward org-table-hline-regexp tbeg t)
9401 (setq beg (point-at-bol 2))
9402 (goto-char tbeg)
9403 (setq beg (point-at-bol 1)))
9404 (goto-char pos)
9405 (if (re-search-forward org-table-hline-regexp tend t)
9406 (setq end (point-at-bol 1))
9407 (goto-char tend)
9408 (setq end (point-at-bol))))
9409 (setq beg (move-marker (make-marker) beg)
9410 end (move-marker (make-marker) end))
9411 (untabify beg end)
9412 (goto-char beg)
9413 (org-table-goto-column column)
9414 (skip-chars-backward "^|")
9415 (setq bcol (current-column))
9416 (org-table-goto-column (1+ column))
9417 (skip-chars-backward "^|")
9418 (setq ecol (1- (current-column)))
9419 (org-table-goto-column column)
9420 (setq lns (mapcar (lambda(x) (cons
9421 (org-sort-remove-invisible
9422 (nth (1- column)
9423 (org-split-string x "[ \t]*|[ \t]*")))
9425 (org-split-string (buffer-substring beg end) "\n")))
9426 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9427 (delete-region beg end)
9428 (move-marker beg nil)
9429 (move-marker end nil)
9430 (insert (mapconcat 'cdr lns "\n") "\n")
9431 (goto-line thisline)
9432 (org-table-goto-column thiscol)
9433 (message "%d lines sorted, based on column %d" (length lns) column)))
9435 ;; FIXME: maybe we will not need this? Table sorting is broken....
9436 (defun org-sort-remove-invisible (s)
9437 (remove-text-properties 0 (length s) org-rm-props s)
9438 (while (string-match org-bracket-link-regexp s)
9439 (setq s (replace-match (if (match-end 2)
9440 (match-string 3 s)
9441 (match-string 1 s)) t t s)))
9444 (defun org-table-cut-region (beg end)
9445 "Copy region in table to the clipboard and blank all relevant fields."
9446 (interactive "r")
9447 (org-table-copy-region beg end 'cut))
9449 (defun org-table-copy-region (beg end &optional cut)
9450 "Copy rectangular region in table to clipboard.
9451 A special clipboard is used which can only be accessed
9452 with `org-table-paste-rectangle'."
9453 (interactive "rP")
9454 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9455 region cols
9456 (rpl (if cut " " nil)))
9457 (goto-char beg)
9458 (org-table-check-inside-data-field)
9459 (setq l01 (org-current-line)
9460 c01 (org-table-current-column))
9461 (goto-char end)
9462 (org-table-check-inside-data-field)
9463 (setq l02 (org-current-line)
9464 c02 (org-table-current-column))
9465 (setq l1 (min l01 l02) l2 (max l01 l02)
9466 c1 (min c01 c02) c2 (max c01 c02))
9467 (catch 'exit
9468 (while t
9469 (catch 'nextline
9470 (if (> l1 l2) (throw 'exit t))
9471 (goto-line l1)
9472 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9473 (setq cols nil ic1 c1 ic2 c2)
9474 (while (< ic1 (1+ ic2))
9475 (push (org-table-get-field ic1 rpl) cols)
9476 (setq ic1 (1+ ic1)))
9477 (push (nreverse cols) region)
9478 (setq l1 (1+ l1)))))
9479 (setq org-table-clip (nreverse region))
9480 (if cut (org-table-align))
9481 org-table-clip))
9483 (defun org-table-paste-rectangle ()
9484 "Paste a rectangular region into a table.
9485 The upper right corner ends up in the current field. All involved fields
9486 will be overwritten. If the rectangle does not fit into the present table,
9487 the table is enlarged as needed. The process ignores horizontal separator
9488 lines."
9489 (interactive)
9490 (unless (and org-table-clip (listp org-table-clip))
9491 (error "First cut/copy a region to paste!"))
9492 (org-table-check-inside-data-field)
9493 (let* ((clip org-table-clip)
9494 (line (org-current-line))
9495 (col (org-table-current-column))
9496 (org-enable-table-editor t)
9497 (org-table-automatic-realign nil)
9498 c cols field)
9499 (while (setq cols (pop clip))
9500 (while (org-at-table-hline-p) (beginning-of-line 2))
9501 (if (not (org-at-table-p))
9502 (progn (end-of-line 0) (org-table-next-field)))
9503 (setq c col)
9504 (while (setq field (pop cols))
9505 (org-table-goto-column c nil 'force)
9506 (org-table-get-field nil field)
9507 (setq c (1+ c)))
9508 (beginning-of-line 2))
9509 (goto-line line)
9510 (org-table-goto-column col)
9511 (org-table-align)))
9513 (defun org-table-convert ()
9514 "Convert from `org-mode' table to table.el and back.
9515 Obviously, this only works within limits. When an Org-mode table is
9516 converted to table.el, all horizontal separator lines get lost, because
9517 table.el uses these as cell boundaries and has no notion of horizontal lines.
9518 A table.el table can be converted to an Org-mode table only if it does not
9519 do row or column spanning. Multiline cells will become multiple cells.
9520 Beware, Org-mode does not test if the table can be successfully converted - it
9521 blindly applies a recipe that works for simple tables."
9522 (interactive)
9523 (require 'table)
9524 (if (org-at-table.el-p)
9525 ;; convert to Org-mode table
9526 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9527 (end (move-marker (make-marker) (org-table-end t))))
9528 (table-unrecognize-region beg end)
9529 (goto-char beg)
9530 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9531 (replace-match ""))
9532 (goto-char beg))
9533 (if (org-at-table-p)
9534 ;; convert to table.el table
9535 (let ((beg (move-marker (make-marker) (org-table-begin)))
9536 (end (move-marker (make-marker) (org-table-end))))
9537 ;; first, get rid of all horizontal lines
9538 (goto-char beg)
9539 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9540 (replace-match ""))
9541 ;; insert a hline before first
9542 (goto-char beg)
9543 (org-table-insert-hline 'above)
9544 (beginning-of-line -1)
9545 ;; insert a hline after each line
9546 (while (progn (beginning-of-line 3) (< (point) end))
9547 (org-table-insert-hline))
9548 (goto-char beg)
9549 (setq end (move-marker end (org-table-end)))
9550 ;; replace "+" at beginning and ending of hlines
9551 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9552 (replace-match "\\1+-"))
9553 (goto-char beg)
9554 (while (re-search-forward "-|[ \t]*$" end t)
9555 (replace-match "-+"))
9556 (goto-char beg)))))
9558 (defun org-table-wrap-region (arg)
9559 "Wrap several fields in a column like a paragraph.
9560 This is useful if you'd like to spread the contents of a field over several
9561 lines, in order to keep the table compact.
9563 If there is an active region, and both point and mark are in the same column,
9564 the text in the column is wrapped to minimum width for the given number of
9565 lines. Generally, this makes the table more compact. A prefix ARG may be
9566 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9567 formats the selected text to two lines. If the region was longer than two
9568 lines, the remaining lines remain empty. A negative prefix argument reduces
9569 the current number of lines by that amount. The wrapped text is pasted back
9570 into the table. If you formatted it to more lines than it was before, fields
9571 further down in the table get overwritten - so you might need to make space in
9572 the table first.
9574 If there is no region, the current field is split at the cursor position and
9575 the text fragment to the right of the cursor is prepended to the field one
9576 line down.
9578 If there is no region, but you specify a prefix ARG, the current field gets
9579 blank, and the content is appended to the field above."
9580 (interactive "P")
9581 (org-table-check-inside-data-field)
9582 (if (org-region-active-p)
9583 ;; There is a region: fill as a paragraph
9584 (let* ((beg (region-beginning))
9585 (cline (save-excursion (goto-char beg) (org-current-line)))
9586 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9587 nlines)
9588 (org-table-cut-region (region-beginning) (region-end))
9589 (if (> (length (car org-table-clip)) 1)
9590 (error "Region must be limited to single column"))
9591 (setq nlines (if arg
9592 (if (< arg 1)
9593 (+ (length org-table-clip) arg)
9594 arg)
9595 (length org-table-clip)))
9596 (setq org-table-clip
9597 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9598 nil nlines)))
9599 (goto-line cline)
9600 (org-table-goto-column ccol)
9601 (org-table-paste-rectangle))
9602 ;; No region, split the current field at point
9603 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9604 (skip-chars-forward "^\r\n|"))
9605 (if arg
9606 ;; combine with field above
9607 (let ((s (org-table-blank-field))
9608 (col (org-table-current-column)))
9609 (beginning-of-line 0)
9610 (while (org-at-table-hline-p) (beginning-of-line 0))
9611 (org-table-goto-column col)
9612 (skip-chars-forward "^|")
9613 (skip-chars-backward " ")
9614 (insert " " (org-trim s))
9615 (org-table-align))
9616 ;; split field
9617 (if (looking-at "\\([^|]+\\)+|")
9618 (let ((s (match-string 1)))
9619 (replace-match " |")
9620 (goto-char (match-beginning 0))
9621 (org-table-next-row)
9622 (insert (org-trim s) " ")
9623 (org-table-align))
9624 (org-table-next-row)))))
9626 (defvar org-field-marker nil)
9628 (defun org-table-edit-field (arg)
9629 "Edit table field in a different window.
9630 This is mainly useful for fields that contain hidden parts.
9631 When called with a \\[universal-argument] prefix, just make the full field visible so that
9632 it can be edited in place."
9633 (interactive "P")
9634 (if arg
9635 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9636 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9637 (remove-text-properties b e '(org-cwidth t invisible t
9638 display t intangible t))
9639 (if (and (boundp 'font-lock-mode) font-lock-mode)
9640 (font-lock-fontify-block)))
9641 (let ((pos (move-marker (make-marker) (point)))
9642 (field (org-table-get-field))
9643 (cw (current-window-configuration))
9645 (org-switch-to-buffer-other-window "*Org tmp*")
9646 (erase-buffer)
9647 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9648 (let ((org-inhibit-startup t)) (org-mode))
9649 (goto-char (setq p (point-max)))
9650 (insert (org-trim field))
9651 (remove-text-properties p (point-max)
9652 '(invisible t org-cwidth t display t
9653 intangible t))
9654 (goto-char p)
9655 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9656 (org-set-local 'org-window-configuration cw)
9657 (org-set-local 'org-field-marker pos)
9658 (message "Edit and finish with C-c C-c"))))
9660 (defun org-table-finish-edit-field ()
9661 "Finish editing a table data field.
9662 Remove all newline characters, insert the result into the table, realign
9663 the table and kill the editing buffer."
9664 (let ((pos org-field-marker)
9665 (cw org-window-configuration)
9666 (cb (current-buffer))
9667 text)
9668 (goto-char (point-min))
9669 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9670 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9671 (replace-match " "))
9672 (setq text (org-trim (buffer-string)))
9673 (set-window-configuration cw)
9674 (kill-buffer cb)
9675 (select-window (get-buffer-window (marker-buffer pos)))
9676 (goto-char pos)
9677 (move-marker pos nil)
9678 (org-table-check-inside-data-field)
9679 (org-table-get-field nil text)
9680 (org-table-align)
9681 (message "New field value inserted")))
9683 (defun org-trim (s)
9684 "Remove whitespace at beginning and end of string."
9685 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9686 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9689 (defun org-wrap (string &optional width lines)
9690 "Wrap string to either a number of lines, or a width in characters.
9691 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9692 that costs. If there is a word longer than WIDTH, the text is actually
9693 wrapped to the length of that word.
9694 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9695 many lines, whatever width that takes.
9696 The return value is a list of lines, without newlines at the end."
9697 (let* ((words (org-split-string string "[ \t\n]+"))
9698 (maxword (apply 'max (mapcar 'org-string-width words)))
9699 w ll)
9700 (cond (width
9701 (org-do-wrap words (max maxword width)))
9702 (lines
9703 (setq w maxword)
9704 (setq ll (org-do-wrap words maxword))
9705 (if (<= (length ll) lines)
9707 (setq ll words)
9708 (while (> (length ll) lines)
9709 (setq w (1+ w))
9710 (setq ll (org-do-wrap words w)))
9711 ll))
9712 (t (error "Cannot wrap this")))))
9715 (defun org-do-wrap (words width)
9716 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9717 (let (lines line)
9718 (while words
9719 (setq line (pop words))
9720 (while (and words (< (+ (length line) (length (car words))) width))
9721 (setq line (concat line " " (pop words))))
9722 (setq lines (push line lines)))
9723 (nreverse lines)))
9725 (defun org-split-string (string &optional separators)
9726 "Splits STRING into substrings at SEPARATORS.
9727 No empty strings are returned if there are matches at the beginning
9728 and end of string."
9729 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9730 (start 0)
9731 notfirst
9732 (list nil))
9733 (while (and (string-match rexp string
9734 (if (and notfirst
9735 (= start (match-beginning 0))
9736 (< start (length string)))
9737 (1+ start) start))
9738 (< (match-beginning 0) (length string)))
9739 (setq notfirst t)
9740 (or (eq (match-beginning 0) 0)
9741 (and (eq (match-beginning 0) (match-end 0))
9742 (eq (match-beginning 0) start))
9743 (setq list
9744 (cons (substring string start (match-beginning 0))
9745 list)))
9746 (setq start (match-end 0)))
9747 (or (eq start (length string))
9748 (setq list
9749 (cons (substring string start)
9750 list)))
9751 (nreverse list)))
9753 (defun org-table-map-tables (function)
9754 "Apply FUNCTION to the start of all tables in the buffer."
9755 (save-excursion
9756 (save-restriction
9757 (widen)
9758 (goto-char (point-min))
9759 (while (re-search-forward org-table-any-line-regexp nil t)
9760 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9761 (beginning-of-line 1)
9762 (if (looking-at org-table-line-regexp)
9763 (save-excursion (funcall function)))
9764 (re-search-forward org-table-any-border-regexp nil 1))))
9765 (message "Mapping tables: done"))
9767 (defvar org-timecnt) ; dynamically scoped parameter
9769 (defun org-table-sum (&optional beg end nlast)
9770 "Sum numbers in region of current table column.
9771 The result will be displayed in the echo area, and will be available
9772 as kill to be inserted with \\[yank].
9774 If there is an active region, it is interpreted as a rectangle and all
9775 numbers in that rectangle will be summed. If there is no active
9776 region and point is located in a table column, sum all numbers in that
9777 column.
9779 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9780 numbers are assumed to be times as well (in decimal hours) and the
9781 numbers are added as such.
9783 If NLAST is a number, only the NLAST fields will actually be summed."
9784 (interactive)
9785 (save-excursion
9786 (let (col (org-timecnt 0) diff h m s org-table-clip)
9787 (cond
9788 ((and beg end)) ; beg and end given explicitly
9789 ((org-region-active-p)
9790 (setq beg (region-beginning) end (region-end)))
9792 (setq col (org-table-current-column))
9793 (goto-char (org-table-begin))
9794 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9795 (error "No table data"))
9796 (org-table-goto-column col)
9797 (setq beg (point))
9798 (goto-char (org-table-end))
9799 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9800 (error "No table data"))
9801 (org-table-goto-column col)
9802 (setq end (point))))
9803 (let* ((items (apply 'append (org-table-copy-region beg end)))
9804 (items1 (cond ((not nlast) items)
9805 ((>= nlast (length items)) items)
9806 (t (setq items (reverse items))
9807 (setcdr (nthcdr (1- nlast) items) nil)
9808 (nreverse items))))
9809 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9810 items1)))
9811 (res (apply '+ numbers))
9812 (sres (if (= org-timecnt 0)
9813 (format "%g" res)
9814 (setq diff (* 3600 res)
9815 h (floor (/ diff 3600)) diff (mod diff 3600)
9816 m (floor (/ diff 60)) diff (mod diff 60)
9817 s diff)
9818 (format "%d:%02d:%02d" h m s))))
9819 (kill-new sres)
9820 (if (interactive-p)
9821 (message "%s"
9822 (substitute-command-keys
9823 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9824 (length numbers) sres))))
9825 sres))))
9827 (defun org-table-get-number-for-summing (s)
9828 (let (n)
9829 (if (string-match "^ *|? *" s)
9830 (setq s (replace-match "" nil nil s)))
9831 (if (string-match " *|? *$" s)
9832 (setq s (replace-match "" nil nil s)))
9833 (setq n (string-to-number s))
9834 (cond
9835 ((and (string-match "0" s)
9836 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9837 ((string-match "\\`[ \t]+\\'" s) nil)
9838 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9839 (let ((h (string-to-number (or (match-string 1 s) "0")))
9840 (m (string-to-number (or (match-string 2 s) "0")))
9841 (s (string-to-number (or (match-string 4 s) "0"))))
9842 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9843 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9844 ((equal n 0) nil)
9845 (t n))))
9847 (defun org-table-current-field-formula (&optional key noerror)
9848 "Return the formula active for the current field.
9849 Assumes that specials are in place.
9850 If KEY is given, return the key to this formula.
9851 Otherwise return the formula preceeded with \"=\" or \":=\"."
9852 (let* ((name (car (rassoc (list (org-current-line)
9853 (org-table-current-column))
9854 org-table-named-field-locations)))
9855 (col (org-table-current-column))
9856 (scol (int-to-string col))
9857 (ref (format "@%d$%d" (org-table-current-dline) col))
9858 (stored-list (org-table-get-stored-formulas noerror))
9859 (ass (or (assoc name stored-list)
9860 (assoc ref stored-list)
9861 (assoc scol stored-list))))
9862 (if key
9863 (car ass)
9864 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9865 (cdr ass))))))
9867 (defun org-table-get-formula (&optional equation named)
9868 "Read a formula from the minibuffer, offer stored formula as default.
9869 When NAMED is non-nil, look for a named equation."
9870 (let* ((stored-list (org-table-get-stored-formulas))
9871 (name (car (rassoc (list (org-current-line)
9872 (org-table-current-column))
9873 org-table-named-field-locations)))
9874 (ref (format "@%d$%d" (org-table-current-dline)
9875 (org-table-current-column)))
9876 (refass (assoc ref stored-list))
9877 (scol (if named
9878 (if name name ref)
9879 (int-to-string (org-table-current-column))))
9880 (dummy (and (or name refass) (not named)
9881 (not (y-or-n-p "Replace field formula with column formula? " ))
9882 (error "Abort")))
9883 (name (or name ref))
9884 (org-table-may-need-update nil)
9885 (stored (cdr (assoc scol stored-list)))
9886 (eq (cond
9887 ((and stored equation (string-match "^ *=? *$" equation))
9888 stored)
9889 ((stringp equation)
9890 equation)
9891 (t (org-table-formula-from-user
9892 (read-string
9893 (org-table-formula-to-user
9894 (format "%s formula %s%s="
9895 (if named "Field" "Column")
9896 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9897 scol))
9898 (if stored (org-table-formula-to-user stored) "")
9899 'org-table-formula-history
9900 )))))
9901 mustsave)
9902 (when (not (string-match "\\S-" eq))
9903 ;; remove formula
9904 (setq stored-list (delq (assoc scol stored-list) stored-list))
9905 (org-table-store-formulas stored-list)
9906 (error "Formula removed"))
9907 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9908 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9909 (if (and name (not named))
9910 ;; We set the column equation, delete the named one.
9911 (setq stored-list (delq (assoc name stored-list) stored-list)
9912 mustsave t))
9913 (if stored
9914 (setcdr (assoc scol stored-list) eq)
9915 (setq stored-list (cons (cons scol eq) stored-list)))
9916 (if (or mustsave (not (equal stored eq)))
9917 (org-table-store-formulas stored-list))
9918 eq))
9920 (defun org-table-store-formulas (alist)
9921 "Store the list of formulas below the current table."
9922 (setq alist (sort alist 'org-table-formula-less-p))
9923 (save-excursion
9924 (goto-char (org-table-end))
9925 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
9926 (progn
9927 ;; don't overwrite TBLFM, we might use text properties to store stuff
9928 (goto-char (match-beginning 2))
9929 (delete-region (match-beginning 2) (match-end 0)))
9930 (insert "#+TBLFM:"))
9931 (insert " "
9932 (mapconcat (lambda (x)
9933 (concat
9934 (if (equal (string-to-char (car x)) ?@) "" "$")
9935 (car x) "=" (cdr x)))
9936 alist "::")
9937 "\n")))
9939 (defsubst org-table-formula-make-cmp-string (a)
9940 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
9941 (concat
9942 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
9943 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
9944 (if (match-end 5) (concat "@@" (match-string 5 a))))))
9946 (defun org-table-formula-less-p (a b)
9947 "Compare two formulas for sorting."
9948 (let ((as (org-table-formula-make-cmp-string (car a)))
9949 (bs (org-table-formula-make-cmp-string (car b))))
9950 (and as bs (string< as bs))))
9952 (defun org-table-get-stored-formulas (&optional noerror)
9953 "Return an alist with the stored formulas directly after current table."
9954 (interactive)
9955 (let (scol eq eq-alist strings string seen)
9956 (save-excursion
9957 (goto-char (org-table-end))
9958 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9959 (setq strings (org-split-string (match-string 2) " *:: *"))
9960 (while (setq string (pop strings))
9961 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
9962 (setq scol (if (match-end 2)
9963 (match-string 2 string)
9964 (match-string 1 string))
9965 eq (match-string 3 string)
9966 eq-alist (cons (cons scol eq) eq-alist))
9967 (if (member scol seen)
9968 (if noerror
9969 (progn
9970 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9971 (ding)
9972 (sit-for 2))
9973 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
9974 (push scol seen))))))
9975 (nreverse eq-alist)))
9977 (defun org-table-fix-formulas (key replace &optional limit delta remove)
9978 "Modify the equations after the table structure has been edited.
9979 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
9980 For all numbers larger than LIMIT, shift them by DELTA."
9981 (save-excursion
9982 (goto-char (org-table-end))
9983 (when (looking-at "#\\+TBLFM:")
9984 (let ((re (concat key "\\([0-9]+\\)"))
9985 (re2
9986 (when remove
9987 (if (equal key "$")
9988 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
9989 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
9990 s n a)
9991 (when remove
9992 (while (re-search-forward re2 (point-at-eol) t)
9993 (replace-match "")))
9994 (while (re-search-forward re (point-at-eol) t)
9995 (setq s (match-string 1) n (string-to-number s))
9996 (cond
9997 ((setq a (assoc s replace))
9998 (replace-match (concat key (cdr a)) t t))
9999 ((and limit (> n limit))
10000 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10002 (defun org-table-get-specials ()
10003 "Get the column names and local parameters for this table."
10004 (save-excursion
10005 (let ((beg (org-table-begin)) (end (org-table-end))
10006 names name fields fields1 field cnt
10007 c v l line col types dlines hlines)
10008 (setq org-table-column-names nil
10009 org-table-local-parameters nil
10010 org-table-named-field-locations nil
10011 org-table-current-begin-line nil
10012 org-table-current-begin-pos nil
10013 org-table-current-line-types nil)
10014 (goto-char beg)
10015 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10016 (setq names (org-split-string (match-string 1) " *| *")
10017 cnt 1)
10018 (while (setq name (pop names))
10019 (setq cnt (1+ cnt))
10020 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10021 (push (cons name (int-to-string cnt)) org-table-column-names))))
10022 (setq org-table-column-names (nreverse org-table-column-names))
10023 (setq org-table-column-name-regexp
10024 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10025 (goto-char beg)
10026 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10027 (setq fields (org-split-string (match-string 1) " *| *"))
10028 (while (setq field (pop fields))
10029 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10030 (push (cons (match-string 1 field) (match-string 2 field))
10031 org-table-local-parameters))))
10032 (goto-char beg)
10033 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10034 (setq c (match-string 1)
10035 fields (org-split-string (match-string 2) " *| *"))
10036 (save-excursion
10037 (beginning-of-line (if (equal c "_") 2 0))
10038 (setq line (org-current-line) col 1)
10039 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10040 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10041 (while (and fields1 (setq field (pop fields)))
10042 (setq v (pop fields1) col (1+ col))
10043 (when (and (stringp field) (stringp v)
10044 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10045 (push (cons field v) org-table-local-parameters)
10046 (push (list field line col) org-table-named-field-locations))))
10047 ;; Analyse the line types
10048 (goto-char beg)
10049 (setq org-table-current-begin-line (org-current-line)
10050 org-table-current-begin-pos (point)
10051 l org-table-current-begin-line)
10052 (while (looking-at "[ \t]*|\\(-\\)?")
10053 (push (if (match-end 1) 'hline 'dline) types)
10054 (if (match-end 1) (push l hlines) (push l dlines))
10055 (beginning-of-line 2)
10056 (setq l (1+ l)))
10057 (setq org-table-current-line-types (apply 'vector (nreverse types))
10058 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10059 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10061 (defun org-table-maybe-eval-formula ()
10062 "Check if the current field starts with \"=\" or \":=\".
10063 If yes, store the formula and apply it."
10064 ;; We already know we are in a table. Get field will only return a formula
10065 ;; when appropriate. It might return a separator line, but no problem.
10066 (when org-table-formula-evaluate-inline
10067 (let* ((field (org-trim (or (org-table-get-field) "")))
10068 named eq)
10069 (when (string-match "^:?=\\(.*\\)" field)
10070 (setq named (equal (string-to-char field) ?:)
10071 eq (match-string 1 field))
10072 (if (or (fboundp 'calc-eval)
10073 (equal (substring eq 0 (min 2 (length eq))) "'("))
10074 (org-table-eval-formula (if named '(4) nil)
10075 (org-table-formula-from-user eq))
10076 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10078 (defvar org-recalc-commands nil
10079 "List of commands triggering the recalculation of a line.
10080 Will be filled automatically during use.")
10082 (defvar org-recalc-marks
10083 '((" " . "Unmarked: no special line, no automatic recalculation")
10084 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10085 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10086 ("!" . "Column name definition line. Reference in formula as $name.")
10087 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10088 ("_" . "Names for values in row below this one.")
10089 ("^" . "Names for values in row above this one.")))
10091 (defun org-table-rotate-recalc-marks (&optional newchar)
10092 "Rotate the recalculation mark in the first column.
10093 If in any row, the first field is not consistent with a mark,
10094 insert a new column for the markers.
10095 When there is an active region, change all the lines in the region,
10096 after prompting for the marking character.
10097 After each change, a message will be displayed indicating the meaning
10098 of the new mark."
10099 (interactive)
10100 (unless (org-at-table-p) (error "Not at a table"))
10101 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10102 (beg (org-table-begin))
10103 (end (org-table-end))
10104 (l (org-current-line))
10105 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10106 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10107 (have-col
10108 (save-excursion
10109 (goto-char beg)
10110 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10111 (col (org-table-current-column))
10112 (forcenew (car (assoc newchar org-recalc-marks)))
10113 epos new)
10114 (when l1
10115 (message "Change region to what mark? Type # * ! $ or SPC: ")
10116 (setq newchar (char-to-string (read-char-exclusive))
10117 forcenew (car (assoc newchar org-recalc-marks))))
10118 (if (and newchar (not forcenew))
10119 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10120 newchar))
10121 (if l1 (goto-line l1))
10122 (save-excursion
10123 (beginning-of-line 1)
10124 (unless (looking-at org-table-dataline-regexp)
10125 (error "Not at a table data line")))
10126 (unless have-col
10127 (org-table-goto-column 1)
10128 (org-table-insert-column)
10129 (org-table-goto-column (1+ col)))
10130 (setq epos (point-at-eol))
10131 (save-excursion
10132 (beginning-of-line 1)
10133 (org-table-get-field
10134 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10135 (concat " "
10136 (setq new (or forcenew
10137 (cadr (member (match-string 1) marks))))
10138 " ")
10139 " # ")))
10140 (if (and l1 l2)
10141 (progn
10142 (goto-line l1)
10143 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10144 (and (looking-at org-table-dataline-regexp)
10145 (org-table-get-field 1 (concat " " new " "))))
10146 (goto-line l1)))
10147 (if (not (= epos (point-at-eol))) (org-table-align))
10148 (goto-line l)
10149 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10151 (defun org-table-maybe-recalculate-line ()
10152 "Recompute the current line if marked for it, and if we haven't just done it."
10153 (interactive)
10154 (and org-table-allow-automatic-line-recalculation
10155 (not (and (memq last-command org-recalc-commands)
10156 (equal org-last-recalc-line (org-current-line))))
10157 (save-excursion (beginning-of-line 1)
10158 (looking-at org-table-auto-recalculate-regexp))
10159 (org-table-recalculate) t))
10161 (defvar org-table-formula-debug nil
10162 "Non-nil means, debug table formulas.
10163 When nil, simply write \"#ERROR\" in corrupted fields.")
10164 (make-variable-buffer-local 'org-table-formula-debug)
10166 (defvar modes)
10167 (defsubst org-set-calc-mode (var &optional value)
10168 (if (stringp var)
10169 (setq var (assoc var '(("D" calc-angle-mode deg)
10170 ("R" calc-angle-mode rad)
10171 ("F" calc-prefer-frac t)
10172 ("S" calc-symbolic-mode t)))
10173 value (nth 2 var) var (nth 1 var)))
10174 (if (memq var modes)
10175 (setcar (cdr (memq var modes)) value)
10176 (cons var (cons value modes)))
10177 modes)
10179 (defun org-table-eval-formula (&optional arg equation
10180 suppress-align suppress-const
10181 suppress-store suppress-analysis)
10182 "Replace the table field value at the cursor by the result of a calculation.
10184 This function makes use of Dave Gillespie's Calc package, in my view the
10185 most exciting program ever written for GNU Emacs. So you need to have Calc
10186 installed in order to use this function.
10188 In a table, this command replaces the value in the current field with the
10189 result of a formula. It also installs the formula as the \"current\" column
10190 formula, by storing it in a special line below the table. When called
10191 with a `C-u' prefix, the current field must ba a named field, and the
10192 formula is installed as valid in only this specific field.
10194 When called with two `C-u' prefixes, insert the active equation
10195 for the field back into the current field, so that it can be
10196 edited there. This is useful in order to use \\[org-table-show-reference]
10197 to check the referenced fields.
10199 When called, the command first prompts for a formula, which is read in
10200 the minibuffer. Previously entered formulas are available through the
10201 history list, and the last used formula is offered as a default.
10202 These stored formulas are adapted correctly when moving, inserting, or
10203 deleting columns with the corresponding commands.
10205 The formula can be any algebraic expression understood by the Calc package.
10206 For details, see the Org-mode manual.
10208 This function can also be called from Lisp programs and offers
10209 additional arguments: EQUATION can be the formula to apply. If this
10210 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10211 used to speed-up recursive calls by by-passing unnecessary aligns.
10212 SUPPRESS-CONST suppresses the interpretation of constants in the
10213 formula, assuming that this has been done already outside the function.
10214 SUPPRESS-STORE means the formula should not be stored, either because
10215 it is already stored, or because it is a modified equation that should
10216 not overwrite the stored one."
10217 (interactive "P")
10218 (org-table-check-inside-data-field)
10219 (or suppress-analysis (org-table-get-specials))
10220 (if (equal arg '(16))
10221 (let ((eq (org-table-current-field-formula)))
10222 (or eq (error "No equation active for current field"))
10223 (org-table-get-field nil eq)
10224 (org-table-align)
10225 (setq org-table-may-need-update t))
10226 (let* (fields
10227 (ndown (if (integerp arg) arg 1))
10228 (org-table-automatic-realign nil)
10229 (case-fold-search nil)
10230 (down (> ndown 1))
10231 (formula (if (and equation suppress-store)
10232 equation
10233 (org-table-get-formula equation (equal arg '(4)))))
10234 (n0 (org-table-current-column))
10235 (modes (copy-sequence org-calc-default-modes))
10236 (numbers nil) ; was a variable, now fixed default
10237 (keep-empty nil)
10238 n form form0 bw fmt x ev orig c lispp literal)
10239 ;; Parse the format string. Since we have a lot of modes, this is
10240 ;; a lot of work. However, I think calc still uses most of the time.
10241 (if (string-match ";" formula)
10242 (let ((tmp (org-split-string formula ";")))
10243 (setq formula (car tmp)
10244 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10245 (nth 1 tmp)))
10246 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10247 (setq c (string-to-char (match-string 1 fmt))
10248 n (string-to-number (match-string 2 fmt)))
10249 (if (= c ?p)
10250 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10251 (setq modes (org-set-calc-mode
10252 'calc-float-format
10253 (list (cdr (assoc c '((?n . float) (?f . fix)
10254 (?s . sci) (?e . eng))))
10255 n))))
10256 (setq fmt (replace-match "" t t fmt)))
10257 (if (string-match "[NT]" fmt)
10258 (setq numbers (equal (match-string 0 fmt) "N")
10259 fmt (replace-match "" t t fmt)))
10260 (if (string-match "L" fmt)
10261 (setq literal t
10262 fmt (replace-match "" t t fmt)))
10263 (if (string-match "E" fmt)
10264 (setq keep-empty t
10265 fmt (replace-match "" t t fmt)))
10266 (while (string-match "[DRFS]" fmt)
10267 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10268 (setq fmt (replace-match "" t t fmt)))
10269 (unless (string-match "\\S-" fmt)
10270 (setq fmt nil))))
10271 (if (and (not suppress-const) org-table-formula-use-constants)
10272 (setq formula (org-table-formula-substitute-names formula)))
10273 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10274 (while (> ndown 0)
10275 (setq fields (org-split-string
10276 (org-no-properties
10277 (buffer-substring (point-at-bol) (point-at-eol)))
10278 " *| *"))
10279 (if (eq numbers t)
10280 (setq fields (mapcar
10281 (lambda (x) (number-to-string (string-to-number x)))
10282 fields)))
10283 (setq ndown (1- ndown))
10284 (setq form (copy-sequence formula)
10285 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10286 (if (and lispp literal) (setq lispp 'literal))
10287 ;; Check for old vertical references
10288 (setq form (org-rewrite-old-row-references form))
10289 ;; Insert complex ranges
10290 (while (string-match org-table-range-regexp form)
10291 (setq form
10292 (replace-match
10293 (save-match-data
10294 (org-table-make-reference
10295 (org-table-get-range (match-string 0 form) nil n0)
10296 keep-empty numbers lispp))
10297 t t form)))
10298 ;; Insert simple ranges
10299 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10300 (setq form
10301 (replace-match
10302 (save-match-data
10303 (org-table-make-reference
10304 (org-sublist
10305 fields (string-to-number (match-string 1 form))
10306 (string-to-number (match-string 2 form)))
10307 keep-empty numbers lispp))
10308 t t form)))
10309 (setq form0 form)
10310 ;; Insert the references to fields in same row
10311 (while (string-match "\\$\\([0-9]+\\)" form)
10312 (setq n (string-to-number (match-string 1 form))
10313 x (nth (1- (if (= n 0) n0 n)) fields))
10314 (unless x (error "Invalid field specifier \"%s\""
10315 (match-string 0 form)))
10316 (setq form (replace-match
10317 (save-match-data
10318 (org-table-make-reference x nil numbers lispp))
10319 t t form)))
10321 (if lispp
10322 (setq ev (condition-case nil
10323 (eval (eval (read form)))
10324 (error "#ERROR"))
10325 ev (if (numberp ev) (number-to-string ev) ev))
10326 (or (fboundp 'calc-eval)
10327 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10328 (setq ev (calc-eval (cons form modes)
10329 (if numbers 'num))))
10331 (when org-table-formula-debug
10332 (with-output-to-temp-buffer "*Substitution History*"
10333 (princ (format "Substitution history of formula
10334 Orig: %s
10335 $xyz-> %s
10336 @r$c-> %s
10337 $1-> %s\n" orig formula form0 form))
10338 (if (listp ev)
10339 (princ (format " %s^\nError: %s"
10340 (make-string (car ev) ?\-) (nth 1 ev)))
10341 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10342 ev (or fmt "NONE")
10343 (if fmt (format fmt (string-to-number ev)) ev)))))
10344 (setq bw (get-buffer-window "*Substitution History*"))
10345 (shrink-window-if-larger-than-buffer bw)
10346 (unless (and (interactive-p) (not ndown))
10347 (unless (let (inhibit-redisplay)
10348 (y-or-n-p "Debugging Formula. Continue to next? "))
10349 (org-table-align)
10350 (error "Abort"))
10351 (delete-window bw)
10352 (message "")))
10353 (if (listp ev) (setq fmt nil ev "#ERROR"))
10354 (org-table-justify-field-maybe
10355 (if fmt (format fmt (string-to-number ev)) ev))
10356 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10357 (call-interactively 'org-return)
10358 (setq ndown 0)))
10359 (and down (org-table-maybe-recalculate-line))
10360 (or suppress-align (and org-table-may-need-update
10361 (org-table-align))))))
10363 (defun org-table-put-field-property (prop value)
10364 (save-excursion
10365 (put-text-property (progn (skip-chars-backward "^|") (point))
10366 (progn (skip-chars-forward "^|") (point))
10367 prop value)))
10369 (defun org-table-get-range (desc &optional tbeg col highlight)
10370 "Get a calc vector from a column, accorting to descriptor DESC.
10371 Optional arguments TBEG and COL can give the beginning of the table and
10372 the current column, to avoid unnecessary parsing.
10373 HIGHLIGHT means, just highlight the range."
10374 (if (not (equal (string-to-char desc) ?@))
10375 (setq desc (concat "@" desc)))
10376 (save-excursion
10377 (or tbeg (setq tbeg (org-table-begin)))
10378 (or col (setq col (org-table-current-column)))
10379 (let ((thisline (org-current-line))
10380 beg end c1 c2 r1 r2 rangep tmp)
10381 (unless (string-match org-table-range-regexp desc)
10382 (error "Invalid table range specifier `%s'" desc))
10383 (setq rangep (match-end 3)
10384 r1 (and (match-end 1) (match-string 1 desc))
10385 r2 (and (match-end 4) (match-string 4 desc))
10386 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10387 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10389 (and c1 (setq c1 (+ (string-to-number c1)
10390 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10391 (and c2 (setq c2 (+ (string-to-number c2)
10392 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10393 (if (equal r1 "") (setq r1 nil))
10394 (if (equal r2 "") (setq r2 nil))
10395 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10396 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10397 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10398 (if (not r1) (setq r1 thisline))
10399 (if (not r2) (setq r2 thisline))
10400 (if (not c1) (setq c1 col))
10401 (if (not c2) (setq c2 col))
10402 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10403 ;; just one field
10404 (progn
10405 (goto-line r1)
10406 (while (not (looking-at org-table-dataline-regexp))
10407 (beginning-of-line 2))
10408 (prog1 (org-trim (org-table-get-field c1))
10409 (if highlight (org-table-highlight-rectangle (point) (point)))))
10410 ;; A range, return a vector
10411 ;; First sort the numbers to get a regular ractangle
10412 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10413 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10414 (goto-line r1)
10415 (while (not (looking-at org-table-dataline-regexp))
10416 (beginning-of-line 2))
10417 (org-table-goto-column c1)
10418 (setq beg (point))
10419 (goto-line r2)
10420 (while (not (looking-at org-table-dataline-regexp))
10421 (beginning-of-line 0))
10422 (org-table-goto-column c2)
10423 (setq end (point))
10424 (if highlight
10425 (org-table-highlight-rectangle
10426 beg (progn (skip-chars-forward "^|\n") (point))))
10427 ;; return string representation of calc vector
10428 (mapcar 'org-trim
10429 (apply 'append (org-table-copy-region beg end)))))))
10431 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10432 "Analyze descriptor DESC and retrieve the corresponding line number.
10433 The cursor is currently in line CLINE, the table begins in line BLINE,
10434 and TABLE is a vector with line types."
10435 (if (string-match "^[0-9]+$" desc)
10436 (aref org-table-dlines (string-to-number desc))
10437 (setq cline (or cline (org-current-line))
10438 bline (or bline org-table-current-begin-line)
10439 table (or table org-table-current-line-types))
10440 (if (or
10441 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10442 ;; 1 2 3 4 5 6
10443 (and (not (match-end 3)) (not (match-end 6)))
10444 (and (match-end 3) (match-end 6) (not (match-end 5))))
10445 (error "invalid row descriptor `%s'" desc))
10446 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10447 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10448 (odir (and (match-end 5) (match-string 5 desc)))
10449 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10450 (i (- cline bline))
10451 (rel (and (match-end 6)
10452 (or (and (match-end 1) (not (match-end 3)))
10453 (match-end 5)))))
10454 (if (and hn (not hdir))
10455 (progn
10456 (setq i 0 hdir "+")
10457 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10458 (if (and (not hn) on (not odir))
10459 (error "should never happen");;(aref org-table-dlines on)
10460 (if (and hn (> hn 0))
10461 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10462 (if on
10463 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10464 (+ bline i)))))
10466 (defun org-find-row-type (table i type backwards relative n)
10467 (let ((l (length table)))
10468 (while (> n 0)
10469 (while (and (setq i (+ i (if backwards -1 1)))
10470 (>= i 0) (< i l)
10471 (not (eq (aref table i) type))
10472 (if (and relative (eq (aref table i) 'hline))
10473 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10474 t)))
10475 (setq n (1- n)))
10476 (if (or (< i 0) (>= i l))
10477 (error "Row descriptior leads outside table")
10478 i)))
10480 (defun org-rewrite-old-row-references (s)
10481 (if (string-match "&[-+0-9I]" s)
10482 (error "Formula contains old &row reference, please rewrite using @-syntax")
10485 (defun org-table-make-reference (elements keep-empty numbers lispp)
10486 "Convert list ELEMENTS to something appropriate to insert into formula.
10487 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10488 NUMBERS indicates that everything should be converted to numbers.
10489 LISPP means to return something appropriate for a Lisp list."
10490 (if (stringp elements) ; just a single val
10491 (if lispp
10492 (if (eq lispp 'literal)
10493 elements
10494 (prin1-to-string (if numbers (string-to-number elements) elements)))
10495 (if (equal elements "") (setq elements "0"))
10496 (if numbers (number-to-string (string-to-number elements)) elements))
10497 (unless keep-empty
10498 (setq elements
10499 (delq nil
10500 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10501 elements))))
10502 (setq elements (or elements '("0")))
10503 (if lispp
10504 (mapconcat
10505 (lambda (x)
10506 (if (eq lispp 'literal)
10508 (prin1-to-string (if numbers (string-to-number x) x))))
10509 elements " ")
10510 (concat "[" (mapconcat
10511 (lambda (x)
10512 (if numbers (number-to-string (string-to-number x)) x))
10513 elements
10514 ",") "]"))))
10516 (defun org-table-recalculate (&optional all noalign)
10517 "Recalculate the current table line by applying all stored formulas.
10518 With prefix arg ALL, do this for all lines in the table."
10519 (interactive "P")
10520 (or (memq this-command org-recalc-commands)
10521 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10522 (unless (org-at-table-p) (error "Not at a table"))
10523 (if (equal all '(16))
10524 (org-table-iterate)
10525 (org-table-get-specials)
10526 (let* ((eqlist (sort (org-table-get-stored-formulas)
10527 (lambda (a b) (string< (car a) (car b)))))
10528 (inhibit-redisplay (not debug-on-error))
10529 (line-re org-table-dataline-regexp)
10530 (thisline (org-current-line))
10531 (thiscol (org-table-current-column))
10532 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10533 ;; Insert constants in all formulas
10534 (setq eqlist
10535 (mapcar (lambda (x)
10536 (setcdr x (org-table-formula-substitute-names (cdr x)))
10538 eqlist))
10539 ;; Split the equation list
10540 (while (setq eq (pop eqlist))
10541 (if (<= (string-to-char (car eq)) ?9)
10542 (push eq eqlnum)
10543 (push eq eqlname)))
10544 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10545 (if all
10546 (progn
10547 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10548 (goto-char (setq beg (org-table-begin)))
10549 (if (re-search-forward org-table-calculate-mark-regexp end t)
10550 ;; This is a table with marked lines, compute selected lines
10551 (setq line-re org-table-recalculate-regexp)
10552 ;; Move forward to the first non-header line
10553 (if (and (re-search-forward org-table-dataline-regexp end t)
10554 (re-search-forward org-table-hline-regexp end t)
10555 (re-search-forward org-table-dataline-regexp end t))
10556 (setq beg (match-beginning 0))
10557 nil))) ;; just leave beg where it is
10558 (setq beg (point-at-bol)
10559 end (move-marker (make-marker) (1+ (point-at-eol)))))
10560 (goto-char beg)
10561 (and all (message "Re-applying formulas to full table..."))
10563 ;; First find the named fields, and mark them untouchanble
10564 (remove-text-properties beg end '(org-untouchable t))
10565 (while (setq eq (pop eqlname))
10566 (setq name (car eq)
10567 a (assoc name org-table-named-field-locations))
10568 (and (not a)
10569 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10570 (setq a (list name
10571 (aref org-table-dlines
10572 (string-to-number (match-string 1 name)))
10573 (string-to-number (match-string 2 name)))))
10574 (when (and a (or all (equal (nth 1 a) thisline)))
10575 (message "Re-applying formula to field: %s" name)
10576 (goto-line (nth 1 a))
10577 (org-table-goto-column (nth 2 a))
10578 (push (append a (list (cdr eq))) eqlname1)
10579 (org-table-put-field-property :org-untouchable t)))
10581 ;; Now evauluate the column formulas, but skip fields covered by
10582 ;; field formulas
10583 (goto-char beg)
10584 (while (re-search-forward line-re end t)
10585 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10586 ;; Unprotected line, recalculate
10587 (and all (message "Re-applying formulas to full table...(line %d)"
10588 (setq cnt (1+ cnt))))
10589 (setq org-last-recalc-line (org-current-line))
10590 (setq eql eqlnum)
10591 (while (setq entry (pop eql))
10592 (goto-line org-last-recalc-line)
10593 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10594 (unless (get-text-property (point) :org-untouchable)
10595 (org-table-eval-formula nil (cdr entry)
10596 'noalign 'nocst 'nostore 'noanalysis)))))
10598 ;; Now evaluate the field formulas
10599 (while (setq eq (pop eqlname1))
10600 (message "Re-applying formula to field: %s" (car eq))
10601 (goto-line (nth 1 eq))
10602 (org-table-goto-column (nth 2 eq))
10603 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10604 'nostore 'noanalysis))
10606 (goto-line thisline)
10607 (org-table-goto-column thiscol)
10608 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10609 (or noalign (and org-table-may-need-update (org-table-align))
10610 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10612 ;; back to initial position
10613 (message "Re-applying formulas...done")
10614 (goto-line thisline)
10615 (org-table-goto-column thiscol)
10616 (or noalign (and org-table-may-need-update (org-table-align))
10617 (and all (message "Re-applying formulas...done"))))))
10619 (defun org-table-iterate (&optional arg)
10620 "Recalculate the table until it does not change anymore."
10621 (interactive "P")
10622 (let ((imax (if arg (prefix-numeric-value arg) 10))
10623 (i 0)
10624 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10625 thistbl)
10626 (catch 'exit
10627 (while (< i imax)
10628 (setq i (1+ i))
10629 (org-table-recalculate 'all)
10630 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10631 (if (not (string= lasttbl thistbl))
10632 (setq lasttbl thistbl)
10633 (if (> i 1)
10634 (message "Convergence after %d iterations" i)
10635 (message "Table was already stable"))
10636 (throw 'exit t)))
10637 (error "No convergence after %d iterations" i))))
10639 (defun org-table-formula-substitute-names (f)
10640 "Replace $const with values in string F."
10641 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10642 ;; First, check for column names
10643 (while (setq start (string-match org-table-column-name-regexp f start))
10644 (setq start (1+ start))
10645 (setq a (assoc (match-string 1 f) org-table-column-names))
10646 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10647 ;; Parameters and constants
10648 (setq start 0)
10649 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10650 (setq start (1+ start))
10651 (if (setq a (save-match-data
10652 (org-table-get-constant (match-string 1 f))))
10653 (setq f (replace-match
10654 (concat (if pp "(") a (if pp ")")) t t f))))
10655 (if org-table-formula-debug
10656 (put-text-property 0 (length f) :orig-formula f1 f))
10659 (defun org-table-get-constant (const)
10660 "Find the value for a parameter or constant in a formula.
10661 Parameters get priority."
10662 (or (cdr (assoc const org-table-local-parameters))
10663 (cdr (assoc const org-table-formula-constants-local))
10664 (cdr (assoc const org-table-formula-constants))
10665 (and (fboundp 'constants-get) (constants-get const))
10666 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10667 (org-entry-get nil (substring const 5) 'inherit))
10668 "#UNDEFINED_NAME"))
10670 (defvar org-table-fedit-map
10671 (let ((map (make-sparse-keymap)))
10672 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10673 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10674 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10675 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10676 (org-defkey map "\C-c?" 'org-table-show-reference)
10677 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10678 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10679 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10680 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10681 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10682 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10683 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10684 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10685 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10686 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10687 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10688 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10689 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10690 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10691 map))
10693 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10694 '("Edit-Formulas"
10695 ["Finish and Install" org-table-fedit-finish t]
10696 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10697 ["Abort" org-table-fedit-abort t]
10698 "--"
10699 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10700 ["Complete Lisp Symbol" lisp-complete-symbol t]
10701 "--"
10702 "Shift Reference at Point"
10703 ["Up" org-table-fedit-ref-up t]
10704 ["Down" org-table-fedit-ref-down t]
10705 ["Left" org-table-fedit-ref-left t]
10706 ["Right" org-table-fedit-ref-right t]
10708 "Change Test Row for Column Formulas"
10709 ["Up" org-table-fedit-line-up t]
10710 ["Down" org-table-fedit-line-down t]
10711 "--"
10712 ["Scroll Table Window" org-table-fedit-scroll t]
10713 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10714 ["Show Table Grid" org-table-fedit-toggle-coordinates
10715 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10716 org-table-overlay-coordinates)]
10717 "--"
10718 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10719 :style toggle :selected org-table-buffer-is-an]))
10721 (defvar org-pos)
10723 (defun org-table-edit-formulas ()
10724 "Edit the formulas of the current table in a separate buffer."
10725 (interactive)
10726 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10727 (beginning-of-line 0))
10728 (unless (org-at-table-p) (error "Not at a table"))
10729 (org-table-get-specials)
10730 (let ((key (org-table-current-field-formula 'key 'noerror))
10731 (eql (sort (org-table-get-stored-formulas 'noerror)
10732 'org-table-formula-less-p))
10733 (pos (move-marker (make-marker) (point)))
10734 (startline 1)
10735 (wc (current-window-configuration))
10736 (titles '((column . "# Column Formulas\n")
10737 (field . "# Field Formulas\n")
10738 (named . "# Named Field Formulas\n")))
10739 entry s type title)
10740 (org-switch-to-buffer-other-window "*Edit Formulas*")
10741 (erase-buffer)
10742 ;; Keep global-font-lock-mode from turning on font-lock-mode
10743 (let ((font-lock-global-modes '(not fundamental-mode)))
10744 (fundamental-mode))
10745 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10746 (org-set-local 'org-pos pos)
10747 (org-set-local 'org-window-configuration wc)
10748 (use-local-map org-table-fedit-map)
10749 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10750 (easy-menu-add org-table-fedit-menu)
10751 (setq startline (org-current-line))
10752 (while (setq entry (pop eql))
10753 (setq type (cond
10754 ((equal (string-to-char (car entry)) ?@) 'field)
10755 ((string-match "^[0-9]" (car entry)) 'column)
10756 (t 'named)))
10757 (when (setq title (assq type titles))
10758 (or (bobp) (insert "\n"))
10759 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10760 (setq titles (delq title titles)))
10761 (if (equal key (car entry)) (setq startline (org-current-line)))
10762 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10763 (car entry) " = " (cdr entry) "\n"))
10764 (remove-text-properties 0 (length s) '(face nil) s)
10765 (insert s))
10766 (if (eq org-table-use-standard-references t)
10767 (org-table-fedit-toggle-ref-type))
10768 (goto-line startline)
10769 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10771 (defun org-table-fedit-post-command ()
10772 (when (not (memq this-command '(lisp-complete-symbol)))
10773 (let ((win (selected-window)))
10774 (save-excursion
10775 (condition-case nil
10776 (org-table-show-reference)
10777 (error nil))
10778 (select-window win)))))
10780 (defun org-table-formula-to-user (s)
10781 "Convert a formula from internal to user representation."
10782 (if (eq org-table-use-standard-references t)
10783 (org-table-convert-refs-to-an s)
10786 (defun org-table-formula-from-user (s)
10787 "Convert a formula from user to internal representation."
10788 (if org-table-use-standard-references
10789 (org-table-convert-refs-to-rc s)
10792 (defun org-table-convert-refs-to-rc (s)
10793 "Convert spreadsheet references from AB7 to @7$28.
10794 Works for single references, but also for entire formulas and even the
10795 full TBLFM line."
10796 (let ((start 0))
10797 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10798 (cond
10799 ((match-end 3)
10800 ;; format match, just advance
10801 (setq start (match-end 0)))
10802 ((and (> (match-beginning 0) 0)
10803 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10804 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10805 ;; 3.e5 or something like this.
10806 (setq start (match-end 0)))
10808 (setq start (match-beginning 0)
10809 s (replace-match
10810 (if (equal (match-string 2 s) "&")
10811 (format "$%d" (org-letters-to-number (match-string 1 s)))
10812 (format "@%d$%d"
10813 (string-to-number (match-string 2 s))
10814 (org-letters-to-number (match-string 1 s))))
10815 t t s)))))
10818 (defun org-table-convert-refs-to-an (s)
10819 "Convert spreadsheet references from to @7$28 to AB7.
10820 Works for single references, but also for entire formulas and even the
10821 full TBLFM line."
10822 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10823 (setq s (replace-match
10824 (format "%s%d"
10825 (org-number-to-letters
10826 (string-to-number (match-string 2 s)))
10827 (string-to-number (match-string 1 s)))
10828 t t s)))
10829 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10830 (setq s (replace-match (concat "\\1"
10831 (org-number-to-letters
10832 (string-to-number (match-string 2 s))) "&")
10833 t nil s)))
10836 (defun org-letters-to-number (s)
10837 "Convert a base 26 number represented by letters into an integer.
10838 For example: AB -> 28."
10839 (let ((n 0))
10840 (setq s (upcase s))
10841 (while (> (length s) 0)
10842 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10843 s (substring s 1)))
10846 (defun org-number-to-letters (n)
10847 "Convert an integer into a base 26 number represented by letters.
10848 For example: 28 -> AB."
10849 (let ((s ""))
10850 (while (> n 0)
10851 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10852 n (/ (1- n) 26)))
10855 (defun org-table-fedit-convert-buffer (function)
10856 "Convert all references in this buffer, using FUNTION."
10857 (let ((line (org-current-line)))
10858 (goto-char (point-min))
10859 (while (not (eobp))
10860 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10861 (delete-region (point) (point-at-eol))
10862 (or (eobp) (forward-char 1)))
10863 (goto-line line)))
10865 (defun org-table-fedit-toggle-ref-type ()
10866 "Convert all references in the buffer from B3 to @3$2 and back."
10867 (interactive)
10868 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10869 (org-table-fedit-convert-buffer
10870 (if org-table-buffer-is-an
10871 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10872 (message "Reference type switched to %s"
10873 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10875 (defun org-table-fedit-ref-up ()
10876 "Shift the reference at point one row/hline up."
10877 (interactive)
10878 (org-table-fedit-shift-reference 'up))
10879 (defun org-table-fedit-ref-down ()
10880 "Shift the reference at point one row/hline down."
10881 (interactive)
10882 (org-table-fedit-shift-reference 'down))
10883 (defun org-table-fedit-ref-left ()
10884 "Shift the reference at point one field to the left."
10885 (interactive)
10886 (org-table-fedit-shift-reference 'left))
10887 (defun org-table-fedit-ref-right ()
10888 "Shift the reference at point one field to the right."
10889 (interactive)
10890 (org-table-fedit-shift-reference 'right))
10892 (defun org-table-fedit-shift-reference (dir)
10893 (cond
10894 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10895 (if (memq dir '(left right))
10896 (org-rematch-and-replace 1 (eq dir 'left))
10897 (error "Cannot shift reference in this direction")))
10898 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10899 ;; A B3-like reference
10900 (if (memq dir '(up down))
10901 (org-rematch-and-replace 2 (eq dir 'up))
10902 (org-rematch-and-replace 1 (eq dir 'left))))
10903 ((org-at-regexp-p
10904 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10905 ;; An internal reference
10906 (if (memq dir '(up down))
10907 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10908 (org-rematch-and-replace 5 (eq dir 'left))))))
10910 (defun org-rematch-and-replace (n &optional decr hline)
10911 "Re-match the group N, and replace it with the shifted refrence."
10912 (or (match-end n) (error "Cannot shift reference in this direction"))
10913 (goto-char (match-beginning n))
10914 (and (looking-at (regexp-quote (match-string n)))
10915 (replace-match (org-shift-refpart (match-string 0) decr hline)
10916 t t)))
10918 (defun org-shift-refpart (ref &optional decr hline)
10919 "Shift a refrence part REF.
10920 If DECR is set, decrease the references row/column, else increase.
10921 If HLINE is set, this may be a hline reference, it certainly is not
10922 a translation reference."
10923 (save-match-data
10924 (let* ((sign (string-match "^[-+]" ref)) n)
10926 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
10927 (cond
10928 ((and hline (string-match "^I+" ref))
10929 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
10930 (setq n (+ n (if decr -1 1)))
10931 (if (= n 0) (setq n (+ n (if decr -1 1))))
10932 (if sign
10933 (setq sign (if (< n 0) "-" "+") n (abs n))
10934 (setq n (max 1 n)))
10935 (concat sign (make-string n ?I)))
10937 ((string-match "^[0-9]+" ref)
10938 (setq n (string-to-number (concat sign ref)))
10939 (setq n (+ n (if decr -1 1)))
10940 (if sign
10941 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
10942 (number-to-string (max 1 n))))
10944 ((string-match "^[a-zA-Z]+" ref)
10945 (org-number-to-letters
10946 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
10948 (t (error "Cannot shift reference"))))))
10950 (defun org-table-fedit-toggle-coordinates ()
10951 "Toggle the display of coordinates in the refrenced table."
10952 (interactive)
10953 (let ((pos (marker-position org-pos)))
10954 (with-current-buffer (marker-buffer org-pos)
10955 (save-excursion
10956 (goto-char pos)
10957 (org-table-toggle-coordinate-overlays)))))
10959 (defun org-table-fedit-finish (&optional arg)
10960 "Parse the buffer for formula definitions and install them.
10961 With prefix ARG, apply the new formulas to the table."
10962 (interactive "P")
10963 (org-table-remove-rectangle-highlight)
10964 (if org-table-use-standard-references
10965 (progn
10966 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
10967 (setq org-table-buffer-is-an nil)))
10968 (let ((pos org-pos) eql var form)
10969 (goto-char (point-min))
10970 (while (re-search-forward
10971 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
10972 nil t)
10973 (setq var (if (match-end 2) (match-string 2) (match-string 1))
10974 form (match-string 3))
10975 (setq form (org-trim form))
10976 (when (not (equal form ""))
10977 (while (string-match "[ \t]*\n[ \t]*" form)
10978 (setq form (replace-match " " t t form)))
10979 (when (assoc var eql)
10980 (error "Double formulas for %s" var))
10981 (push (cons var form) eql)))
10982 (setq org-pos nil)
10983 (set-window-configuration org-window-configuration)
10984 (select-window (get-buffer-window (marker-buffer pos)))
10985 (goto-char pos)
10986 (unless (org-at-table-p)
10987 (error "Lost table position - cannot install formulae"))
10988 (org-table-store-formulas eql)
10989 (move-marker pos nil)
10990 (kill-buffer "*Edit Formulas*")
10991 (if arg
10992 (org-table-recalculate 'all)
10993 (message "New formulas installed - press C-u C-c C-c to apply."))))
10995 (defun org-table-fedit-abort ()
10996 "Abort editing formulas, without installing the changes."
10997 (interactive)
10998 (org-table-remove-rectangle-highlight)
10999 (let ((pos org-pos))
11000 (set-window-configuration org-window-configuration)
11001 (select-window (get-buffer-window (marker-buffer pos)))
11002 (goto-char pos)
11003 (move-marker pos nil)
11004 (message "Formula editing aborted without installing changes")))
11006 (defun org-table-fedit-lisp-indent ()
11007 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11008 (interactive)
11009 (let ((pos (point)) beg end ind)
11010 (beginning-of-line 1)
11011 (cond
11012 ((looking-at "[ \t]")
11013 (goto-char pos)
11014 (call-interactively 'lisp-indent-line))
11015 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11016 ((not (fboundp 'pp-buffer))
11017 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11018 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11019 (goto-char (- (match-end 0) 2))
11020 (setq beg (point))
11021 (setq ind (make-string (current-column) ?\ ))
11022 (condition-case nil (forward-sexp 1)
11023 (error
11024 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11025 (setq end (point))
11026 (save-restriction
11027 (narrow-to-region beg end)
11028 (if (eq last-command this-command)
11029 (progn
11030 (goto-char (point-min))
11031 (setq this-command nil)
11032 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11033 (replace-match " ")))
11034 (pp-buffer)
11035 (untabify (point-min) (point-max))
11036 (goto-char (1+ (point-min)))
11037 (while (re-search-forward "^." nil t)
11038 (beginning-of-line 1)
11039 (insert ind))
11040 (goto-char (point-max))
11041 (backward-delete-char 1)))
11042 (goto-char beg))
11043 (t nil))))
11045 (defvar org-show-positions nil)
11047 (defun org-table-show-reference (&optional local)
11048 "Show the location/value of the $ expression at point."
11049 (interactive)
11050 (org-table-remove-rectangle-highlight)
11051 (catch 'exit
11052 (let ((pos (if local (point) org-pos))
11053 (face2 'highlight)
11054 (org-inhibit-highlight-removal t)
11055 (win (selected-window))
11056 (org-show-positions nil)
11057 var name e what match dest)
11058 (if local (org-table-get-specials))
11059 (setq what (cond
11060 ((or (org-at-regexp-p org-table-range-regexp2)
11061 (org-at-regexp-p org-table-translate-regexp)
11062 (org-at-regexp-p org-table-range-regexp))
11063 (setq match
11064 (save-match-data
11065 (org-table-convert-refs-to-rc (match-string 0))))
11066 'range)
11067 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11068 ((org-at-regexp-p "\\$[0-9]+") 'column)
11069 ((not local) nil)
11070 (t (error "No reference at point")))
11071 match (and what (or match (match-string 0))))
11072 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11073 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11074 'secondary-selection))
11075 (org-add-hook 'before-change-functions
11076 'org-table-remove-rectangle-highlight)
11077 (if (eq what 'name) (setq var (substring match 1)))
11078 (when (eq what 'range)
11079 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11080 (setq match (org-table-formula-substitute-names match)))
11081 (unless local
11082 (save-excursion
11083 (end-of-line 1)
11084 (re-search-backward "^\\S-" nil t)
11085 (beginning-of-line 1)
11086 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11087 (setq dest
11088 (save-match-data
11089 (org-table-convert-refs-to-rc (match-string 1))))
11090 (org-table-add-rectangle-overlay
11091 (match-beginning 1) (match-end 1) face2))))
11092 (if (and (markerp pos) (marker-buffer pos))
11093 (if (get-buffer-window (marker-buffer pos))
11094 (select-window (get-buffer-window (marker-buffer pos)))
11095 (org-switch-to-buffer-other-window (get-buffer-window
11096 (marker-buffer pos)))))
11097 (goto-char pos)
11098 (org-table-force-dataline)
11099 (when dest
11100 (setq name (substring dest 1))
11101 (cond
11102 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11103 (setq e (assoc name org-table-named-field-locations))
11104 (goto-line (nth 1 e))
11105 (org-table-goto-column (nth 2 e)))
11106 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11107 (let ((l (string-to-number (match-string 1 dest)))
11108 (c (string-to-number (match-string 2 dest))))
11109 (goto-line (aref org-table-dlines l))
11110 (org-table-goto-column c)))
11111 (t (org-table-goto-column (string-to-number name))))
11112 (move-marker pos (point))
11113 (org-table-highlight-rectangle nil nil face2))
11114 (cond
11115 ((equal dest match))
11116 ((not match))
11117 ((eq what 'range)
11118 (condition-case nil
11119 (save-excursion
11120 (org-table-get-range match nil nil 'highlight))
11121 (error nil)))
11122 ((setq e (assoc var org-table-named-field-locations))
11123 (goto-line (nth 1 e))
11124 (org-table-goto-column (nth 2 e))
11125 (org-table-highlight-rectangle (point) (point))
11126 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11127 ((setq e (assoc var org-table-column-names))
11128 (org-table-goto-column (string-to-number (cdr e)))
11129 (org-table-highlight-rectangle (point) (point))
11130 (goto-char (org-table-begin))
11131 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11132 (org-table-end) t)
11133 (progn
11134 (goto-char (match-beginning 1))
11135 (org-table-highlight-rectangle)
11136 (message "Named column (column %s)" (cdr e)))
11137 (error "Column name not found")))
11138 ((eq what 'column)
11139 ;; column number
11140 (org-table-goto-column (string-to-number (substring match 1)))
11141 (org-table-highlight-rectangle (point) (point))
11142 (message "Column %s" (substring match 1)))
11143 ((setq e (assoc var org-table-local-parameters))
11144 (goto-char (org-table-begin))
11145 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11146 (progn
11147 (goto-char (match-beginning 1))
11148 (org-table-highlight-rectangle)
11149 (message "Local parameter."))
11150 (error "Parameter not found")))
11152 (cond
11153 ((not var) (error "No reference at point"))
11154 ((setq e (assoc var org-table-formula-constants-local))
11155 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11156 var (cdr e)))
11157 ((setq e (assoc var org-table-formula-constants))
11158 (message "Constant: $%s=%s in `org-table-formula-constants'."
11159 var (cdr e)))
11160 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11161 (message "Constant: $%s=%s, from `constants.el'%s."
11162 var e (format " (%s units)" constants-unit-system)))
11163 (t (error "Undefined name $%s" var)))))
11164 (goto-char pos)
11165 (when (and org-show-positions
11166 (not (memq this-command '(org-table-fedit-scroll
11167 org-table-fedit-scroll-down))))
11168 (push pos org-show-positions)
11169 (push org-table-current-begin-pos org-show-positions)
11170 (let ((min (apply 'min org-show-positions))
11171 (max (apply 'max org-show-positions)))
11172 (goto-char min) (recenter 0)
11173 (goto-char max)
11174 (or (pos-visible-in-window-p max) (recenter -1))))
11175 (select-window win))))
11177 (defun org-table-force-dataline ()
11178 "Make sure the cursor is in a dataline in a table."
11179 (unless (save-excursion
11180 (beginning-of-line 1)
11181 (looking-at org-table-dataline-regexp))
11182 (let* ((re org-table-dataline-regexp)
11183 (p1 (save-excursion (re-search-forward re nil 'move)))
11184 (p2 (save-excursion (re-search-backward re nil 'move))))
11185 (cond ((and p1 p2)
11186 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11187 p1 p2)))
11188 ((or p1 p2) (goto-char (or p1 p2)))
11189 (t (error "No table dataline around here"))))))
11191 (defun org-table-fedit-line-up ()
11192 "Move cursor one line up in the window showing the table."
11193 (interactive)
11194 (org-table-fedit-move 'previous-line))
11196 (defun org-table-fedit-line-down ()
11197 "Move cursor one line down in the window showing the table."
11198 (interactive)
11199 (org-table-fedit-move 'next-line))
11201 (defun org-table-fedit-move (command)
11202 "Move the cursor in the window shoinw the table.
11203 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11204 (let ((org-table-allow-automatic-line-recalculation nil)
11205 (pos org-pos) (win (selected-window)) p)
11206 (select-window (get-buffer-window (marker-buffer org-pos)))
11207 (setq p (point))
11208 (call-interactively command)
11209 (while (and (org-at-table-p)
11210 (org-at-table-hline-p))
11211 (call-interactively command))
11212 (or (org-at-table-p) (goto-char p))
11213 (move-marker pos (point))
11214 (select-window win)))
11216 (defun org-table-fedit-scroll (N)
11217 (interactive "p")
11218 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11219 (scroll-other-window N)))
11221 (defun org-table-fedit-scroll-down (N)
11222 (interactive "p")
11223 (org-table-fedit-scroll (- N)))
11225 (defvar org-table-rectangle-overlays nil)
11227 (defun org-table-add-rectangle-overlay (beg end &optional face)
11228 "Add a new overlay."
11229 (let ((ov (org-make-overlay beg end)))
11230 (org-overlay-put ov 'face (or face 'secondary-selection))
11231 (push ov org-table-rectangle-overlays)))
11233 (defun org-table-highlight-rectangle (&optional beg end face)
11234 "Highlight rectangular region in a table."
11235 (setq beg (or beg (point)) end (or end (point)))
11236 (let ((b (min beg end))
11237 (e (max beg end))
11238 l1 c1 l2 c2 tmp)
11239 (and (boundp 'org-show-positions)
11240 (setq org-show-positions (cons b (cons e org-show-positions))))
11241 (goto-char (min beg end))
11242 (setq l1 (org-current-line)
11243 c1 (org-table-current-column))
11244 (goto-char (max beg end))
11245 (setq l2 (org-current-line)
11246 c2 (org-table-current-column))
11247 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11248 (goto-line l1)
11249 (beginning-of-line 1)
11250 (loop for line from l1 to l2 do
11251 (when (looking-at org-table-dataline-regexp)
11252 (org-table-goto-column c1)
11253 (skip-chars-backward "^|\n") (setq beg (point))
11254 (org-table-goto-column c2)
11255 (skip-chars-forward "^|\n") (setq end (point))
11256 (org-table-add-rectangle-overlay beg end face))
11257 (beginning-of-line 2))
11258 (goto-char b))
11259 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11261 (defun org-table-remove-rectangle-highlight (&rest ignore)
11262 "Remove the rectangle overlays."
11263 (unless org-inhibit-highlight-removal
11264 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11265 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11266 (setq org-table-rectangle-overlays nil)))
11268 (defvar org-table-coordinate-overlays nil
11269 "Collects the cooordinate grid overlays, so that they can be removed.")
11270 (make-variable-buffer-local 'org-table-coordinate-overlays)
11272 (defun org-table-overlay-coordinates ()
11273 "Add overlays to the table at point, to show row/column coordinates."
11274 (interactive)
11275 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11276 (setq org-table-coordinate-overlays nil)
11277 (save-excursion
11278 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11279 (goto-char (org-table-begin))
11280 (while (org-at-table-p)
11281 (setq eol (point-at-eol))
11282 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11283 (push ov org-table-coordinate-overlays)
11284 (setq hline (looking-at org-table-hline-regexp))
11285 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11286 (format "%4d" (setq id (1+ id)))))
11287 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11288 (when hline
11289 (setq ic 0)
11290 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11291 (setq beg (1+ (match-beginning 0))
11292 ic (1+ ic)
11293 s1 (concat "$" (int-to-string ic))
11294 s2 (org-number-to-letters ic)
11295 str (if (eq org-table-use-standard-references t) s2 s1))
11296 (setq ov (org-make-overlay beg (+ beg (length str))))
11297 (push ov org-table-coordinate-overlays)
11298 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11299 (beginning-of-line 2)))))
11301 (defun org-table-toggle-coordinate-overlays ()
11302 "Toggle the display of Row/Column numbers in tables."
11303 (interactive)
11304 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11305 (message "Row/Column number display turned %s"
11306 (if org-table-overlay-coordinates "on" "off"))
11307 (if (and (org-at-table-p) org-table-overlay-coordinates)
11308 (org-table-align))
11309 (unless org-table-overlay-coordinates
11310 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11311 (setq org-table-coordinate-overlays nil)))
11313 (defun org-table-toggle-formula-debugger ()
11314 "Toggle the formula debugger in tables."
11315 (interactive)
11316 (setq org-table-formula-debug (not org-table-formula-debug))
11317 (message "Formula debugging has been turned %s"
11318 (if org-table-formula-debug "on" "off")))
11320 ;;; The orgtbl minor mode
11322 ;; Define a minor mode which can be used in other modes in order to
11323 ;; integrate the org-mode table editor.
11325 ;; This is really a hack, because the org-mode table editor uses several
11326 ;; keys which normally belong to the major mode, for example the TAB and
11327 ;; RET keys. Here is how it works: The minor mode defines all the keys
11328 ;; necessary to operate the table editor, but wraps the commands into a
11329 ;; function which tests if the cursor is currently inside a table. If that
11330 ;; is the case, the table editor command is executed. However, when any of
11331 ;; those keys is used outside a table, the function uses `key-binding' to
11332 ;; look up if the key has an associated command in another currently active
11333 ;; keymap (minor modes, major mode, global), and executes that command.
11334 ;; There might be problems if any of the keys used by the table editor is
11335 ;; otherwise used as a prefix key.
11337 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11338 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11339 ;; addresses this by checking explicitly for both bindings.
11341 ;; The optimized version (see variable `orgtbl-optimized') takes over
11342 ;; all keys which are bound to `self-insert-command' in the *global map*.
11343 ;; Some modes bind other commands to simple characters, for example
11344 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11345 ;; active, this binding is ignored inside tables and replaced with a
11346 ;; modified self-insert.
11348 (defvar orgtbl-mode nil
11349 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11350 table editor in arbitrary modes.")
11351 (make-variable-buffer-local 'orgtbl-mode)
11353 (defvar orgtbl-mode-map (make-keymap)
11354 "Keymap for `orgtbl-mode'.")
11356 ;;;###autoload
11357 (defun turn-on-orgtbl ()
11358 "Unconditionally turn on `orgtbl-mode'."
11359 (orgtbl-mode 1))
11361 (defvar org-old-auto-fill-inhibit-regexp nil
11362 "Local variable used by `orgtbl-mode'")
11364 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11365 "Matches a line belonging to an orgtbl.")
11367 (defconst orgtbl-extra-font-lock-keywords
11368 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11369 0 (quote 'org-table) 'prepend))
11370 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11372 ;;;###autoload
11373 (defun orgtbl-mode (&optional arg)
11374 "The `org-mode' table editor as a minor mode for use in other modes."
11375 (interactive)
11376 (if (org-mode-p)
11377 ;; Exit without error, in case some hook functions calls this
11378 ;; by accident in org-mode.
11379 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11380 (setq orgtbl-mode
11381 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11382 (if orgtbl-mode
11383 (progn
11384 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11385 ;; Make sure we are first in minor-mode-map-alist
11386 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11387 (and c (setq minor-mode-map-alist
11388 (cons c (delq c minor-mode-map-alist)))))
11389 (org-set-local (quote org-table-may-need-update) t)
11390 (org-add-hook 'before-change-functions 'org-before-change-function
11391 nil 'local)
11392 (org-set-local 'org-old-auto-fill-inhibit-regexp
11393 auto-fill-inhibit-regexp)
11394 (org-set-local 'auto-fill-inhibit-regexp
11395 (if auto-fill-inhibit-regexp
11396 (concat orgtbl-line-start-regexp "\\|"
11397 auto-fill-inhibit-regexp)
11398 orgtbl-line-start-regexp))
11399 (org-add-to-invisibility-spec '(org-cwidth))
11400 (when (fboundp 'font-lock-add-keywords)
11401 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11402 (org-restart-font-lock))
11403 (easy-menu-add orgtbl-mode-menu)
11404 (run-hooks 'orgtbl-mode-hook))
11405 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11406 (org-cleanup-narrow-column-properties)
11407 (org-remove-from-invisibility-spec '(org-cwidth))
11408 (remove-hook 'before-change-functions 'org-before-change-function t)
11409 (when (fboundp 'font-lock-remove-keywords)
11410 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11411 (org-restart-font-lock))
11412 (easy-menu-remove orgtbl-mode-menu)
11413 (force-mode-line-update 'all))))
11415 (defun org-cleanup-narrow-column-properties ()
11416 "Remove all properties related to narrow-column invisibility."
11417 (let ((s 1))
11418 (while (setq s (text-property-any s (point-max)
11419 'display org-narrow-column-arrow))
11420 (remove-text-properties s (1+ s) '(display t)))
11421 (setq s 1)
11422 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11423 (remove-text-properties s (1+ s) '(org-cwidth t)))
11424 (setq s 1)
11425 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11426 (remove-text-properties s (1+ s) '(invisible t)))))
11428 ;; Install it as a minor mode.
11429 (put 'orgtbl-mode :included t)
11430 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11431 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11433 (defun orgtbl-make-binding (fun n &rest keys)
11434 "Create a function for binding in the table minor mode.
11435 FUN is the command to call inside a table. N is used to create a unique
11436 command name. KEYS are keys that should be checked in for a command
11437 to execute outside of tables."
11438 (eval
11439 (list 'defun
11440 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11441 '(arg)
11442 (concat "In tables, run `" (symbol-name fun) "'.\n"
11443 "Outside of tables, run the binding of `"
11444 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11445 "'.")
11446 '(interactive "p")
11447 (list 'if
11448 '(org-at-table-p)
11449 (list 'call-interactively (list 'quote fun))
11450 (list 'let '(orgtbl-mode)
11451 (list 'call-interactively
11452 (append '(or)
11453 (mapcar (lambda (k)
11454 (list 'key-binding k))
11455 keys)
11456 '('orgtbl-error))))))))
11458 (defun orgtbl-error ()
11459 "Error when there is no default binding for a table key."
11460 (interactive)
11461 (error "This key has no function outside tables"))
11463 (defun orgtbl-setup ()
11464 "Setup orgtbl keymaps."
11465 (let ((nfunc 0)
11466 (bindings
11467 (list
11468 '([(meta shift left)] org-table-delete-column)
11469 '([(meta left)] org-table-move-column-left)
11470 '([(meta right)] org-table-move-column-right)
11471 '([(meta shift right)] org-table-insert-column)
11472 '([(meta shift up)] org-table-kill-row)
11473 '([(meta shift down)] org-table-insert-row)
11474 '([(meta up)] org-table-move-row-up)
11475 '([(meta down)] org-table-move-row-down)
11476 '("\C-c\C-w" org-table-cut-region)
11477 '("\C-c\M-w" org-table-copy-region)
11478 '("\C-c\C-y" org-table-paste-rectangle)
11479 '("\C-c-" org-table-insert-hline)
11480 '("\C-c}" org-table-toggle-coordinate-overlays)
11481 '("\C-c{" org-table-toggle-formula-debugger)
11482 '("\C-m" org-table-next-row)
11483 '([(shift return)] org-table-copy-down)
11484 '("\C-c\C-q" org-table-wrap-region)
11485 '("\C-c?" org-table-field-info)
11486 '("\C-c " org-table-blank-field)
11487 '("\C-c+" org-table-sum)
11488 '("\C-c=" org-table-eval-formula)
11489 '("\C-c'" org-table-edit-formulas)
11490 '("\C-c`" org-table-edit-field)
11491 '("\C-c*" org-table-recalculate)
11492 '("\C-c|" org-table-create-or-convert-from-region)
11493 '("\C-c^" org-table-sort-lines)
11494 '([(control ?#)] org-table-rotate-recalc-marks)))
11495 elt key fun cmd)
11496 (while (setq elt (pop bindings))
11497 (setq nfunc (1+ nfunc))
11498 (setq key (org-key (car elt))
11499 fun (nth 1 elt)
11500 cmd (orgtbl-make-binding fun nfunc key))
11501 (org-defkey orgtbl-mode-map key cmd))
11503 ;; Special treatment needed for TAB and RET
11504 (org-defkey orgtbl-mode-map [(return)]
11505 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11506 (org-defkey orgtbl-mode-map "\C-m"
11507 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11509 (org-defkey orgtbl-mode-map [(tab)]
11510 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11511 (org-defkey orgtbl-mode-map "\C-i"
11512 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11514 (org-defkey orgtbl-mode-map [(shift tab)]
11515 (orgtbl-make-binding 'org-table-previous-field 104
11516 [(shift tab)] [(tab)] "\C-i"))
11518 (org-defkey orgtbl-mode-map "\M-\C-m"
11519 (orgtbl-make-binding 'org-table-wrap-region 105
11520 "\M-\C-m" [(meta return)]))
11521 (org-defkey orgtbl-mode-map [(meta return)]
11522 (orgtbl-make-binding 'org-table-wrap-region 106
11523 [(meta return)] "\M-\C-m"))
11525 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11526 (when orgtbl-optimized
11527 ;; If the user wants maximum table support, we need to hijack
11528 ;; some standard editing functions
11529 (org-remap orgtbl-mode-map
11530 'self-insert-command 'orgtbl-self-insert-command
11531 'delete-char 'org-delete-char
11532 'delete-backward-char 'org-delete-backward-char)
11533 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11534 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11535 '("OrgTbl"
11536 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11537 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11538 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11539 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11540 "--"
11541 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11542 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11543 ["Copy Field from Above"
11544 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11545 "--"
11546 ("Column"
11547 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11548 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11549 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11550 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11551 ("Row"
11552 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11553 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11554 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11555 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11556 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11557 "--"
11558 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11559 ("Rectangle"
11560 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11561 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11562 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11563 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11564 "--"
11565 ("Radio tables"
11566 ["Insert table template" orgtbl-insert-radio-table
11567 (assq major-mode orgtbl-radio-table-templates)]
11568 ["Comment/uncomment table" orgtbl-toggle-comment t])
11569 "--"
11570 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11571 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11572 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11573 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11574 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11575 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11576 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11577 ["Sum Column/Rectangle" org-table-sum
11578 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11579 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11580 ["Debug Formulas"
11581 org-table-toggle-formula-debugger :active (org-at-table-p)
11582 :keys "C-c {"
11583 :style toggle :selected org-table-formula-debug]
11584 ["Show Col/Row Numbers"
11585 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11586 :keys "C-c }"
11587 :style toggle :selected org-table-overlay-coordinates]
11591 (defun orgtbl-ctrl-c-ctrl-c (arg)
11592 "If the cursor is inside a table, realign the table.
11593 It it is a table to be sent away to a receiver, do it.
11594 With prefix arg, also recompute table."
11595 (interactive "P")
11596 (let ((pos (point)) action)
11597 (save-excursion
11598 (beginning-of-line 1)
11599 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11600 ((looking-at "[ \t]*|") pos)
11601 ((looking-at "#\\+TBLFM:") 'recalc))))
11602 (cond
11603 ((integerp action)
11604 (goto-char action)
11605 (org-table-maybe-eval-formula)
11606 (if arg
11607 (call-interactively 'org-table-recalculate)
11608 (org-table-maybe-recalculate-line))
11609 (call-interactively 'org-table-align)
11610 (orgtbl-send-table 'maybe))
11611 ((eq action 'recalc)
11612 (save-excursion
11613 (beginning-of-line 1)
11614 (skip-chars-backward " \r\n\t")
11615 (if (org-at-table-p)
11616 (org-call-with-arg 'org-table-recalculate t))))
11617 (t (let (orgtbl-mode)
11618 (call-interactively (key-binding "\C-c\C-c")))))))
11620 (defun orgtbl-tab (arg)
11621 "Justification and field motion for `orgtbl-mode'."
11622 (interactive "P")
11623 (if arg (org-table-edit-field t)
11624 (org-table-justify-field-maybe)
11625 (org-table-next-field)))
11627 (defun orgtbl-ret ()
11628 "Justification and field motion for `orgtbl-mode'."
11629 (interactive)
11630 (org-table-justify-field-maybe)
11631 (org-table-next-row))
11633 (defun orgtbl-self-insert-command (N)
11634 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11635 If the cursor is in a table looking at whitespace, the whitespace is
11636 overwritten, and the table is not marked as requiring realignment."
11637 (interactive "p")
11638 (if (and (org-at-table-p)
11640 (and org-table-auto-blank-field
11641 (member last-command
11642 '(orgtbl-hijacker-command-100
11643 orgtbl-hijacker-command-101
11644 orgtbl-hijacker-command-102
11645 orgtbl-hijacker-command-103
11646 orgtbl-hijacker-command-104
11647 orgtbl-hijacker-command-105))
11648 (org-table-blank-field))
11650 (eq N 1)
11651 (looking-at "[^|\n]* +|"))
11652 (let (org-table-may-need-update)
11653 (goto-char (1- (match-end 0)))
11654 (delete-backward-char 1)
11655 (goto-char (match-beginning 0))
11656 (self-insert-command N))
11657 (setq org-table-may-need-update t)
11658 (let (orgtbl-mode)
11659 (call-interactively (key-binding (vector last-input-event))))))
11661 (defun org-force-self-insert (N)
11662 "Needed to enforce self-insert under remapping."
11663 (interactive "p")
11664 (self-insert-command N))
11666 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11667 "Regula expression matching exponentials as produced by calc.")
11669 (defvar org-table-clean-did-remove-column nil)
11671 (defun orgtbl-export (table target)
11672 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11673 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11674 org-table-last-alignment org-table-last-column-widths
11675 maxcol column)
11676 (if (not (fboundp func))
11677 (error "Cannot export orgtbl table to %s" target))
11678 (setq lines (org-table-clean-before-export lines))
11679 (setq table
11680 (mapcar
11681 (lambda (x)
11682 (if (string-match org-table-hline-regexp x)
11683 'hline
11684 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11685 lines))
11686 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11687 table)))
11688 (loop for i from (1- maxcol) downto 0 do
11689 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11690 (setq column (delq nil column))
11691 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11692 (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))
11693 (funcall func table nil)))
11695 (defun orgtbl-send-table (&optional maybe)
11696 "Send a tranformed version of this table to the receiver position.
11697 With argument MAYBE, fail quietly if no transformation is defined for
11698 this table."
11699 (interactive)
11700 (catch 'exit
11701 (unless (org-at-table-p) (error "Not at a table"))
11702 ;; when non-interactive, we assume align has just happened.
11703 (when (interactive-p) (org-table-align))
11704 (save-excursion
11705 (goto-char (org-table-begin))
11706 (beginning-of-line 0)
11707 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11708 (if maybe
11709 (throw 'exit nil)
11710 (error "Don't know how to transform this table."))))
11711 (let* ((name (match-string 1))
11713 (transform (intern (match-string 2)))
11714 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11715 (skip (plist-get params :skip))
11716 (skipcols (plist-get params :skipcols))
11717 (txt (buffer-substring-no-properties
11718 (org-table-begin) (org-table-end)))
11719 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11720 (lines (org-table-clean-before-export lines))
11721 (i0 (if org-table-clean-did-remove-column 2 1))
11722 (table (mapcar
11723 (lambda (x)
11724 (if (string-match org-table-hline-regexp x)
11725 'hline
11726 (org-remove-by-index
11727 (org-split-string (org-trim x) "\\s-*|\\s-*")
11728 skipcols i0)))
11729 lines))
11730 (fun (if (= i0 2) 'cdr 'identity))
11731 (org-table-last-alignment
11732 (org-remove-by-index (funcall fun org-table-last-alignment)
11733 skipcols i0))
11734 (org-table-last-column-widths
11735 (org-remove-by-index (funcall fun org-table-last-column-widths)
11736 skipcols i0)))
11738 (unless (fboundp transform)
11739 (error "No such transformation function %s" transform))
11740 (setq txt (funcall transform table params))
11741 ;; Find the insertion place
11742 (save-excursion
11743 (goto-char (point-min))
11744 (unless (re-search-forward
11745 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11746 (error "Don't know where to insert translated table"))
11747 (goto-char (match-beginning 0))
11748 (beginning-of-line 2)
11749 (setq beg (point))
11750 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11751 (error "Cannot find end of insertion region"))
11752 (beginning-of-line 1)
11753 (delete-region beg (point))
11754 (goto-char beg)
11755 (insert txt "\n"))
11756 (message "Table converted and installed at receiver location"))))
11758 (defun org-remove-by-index (list indices &optional i0)
11759 "Remove the elements in LIST with indices in INDICES.
11760 First element has index 0, or I0 if given."
11761 (if (not indices)
11762 list
11763 (if (integerp indices) (setq indices (list indices)))
11764 (setq i0 (1- (or i0 0)))
11765 (delq :rm (mapcar (lambda (x)
11766 (setq i0 (1+ i0))
11767 (if (memq i0 indices) :rm x))
11768 list))))
11770 (defun orgtbl-toggle-comment ()
11771 "Comment or uncomment the orgtbl at point."
11772 (interactive)
11773 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11774 (re2 (concat "^" orgtbl-line-start-regexp))
11775 (commented (save-excursion (beginning-of-line 1)
11776 (cond ((looking-at re1) t)
11777 ((looking-at re2) nil)
11778 (t (error "Not at an org table")))))
11779 (re (if commented re1 re2))
11780 beg end)
11781 (save-excursion
11782 (beginning-of-line 1)
11783 (while (looking-at re) (beginning-of-line 0))
11784 (beginning-of-line 2)
11785 (setq beg (point))
11786 (while (looking-at re) (beginning-of-line 2))
11787 (setq end (point)))
11788 (comment-region beg end (if commented '(4) nil))))
11790 (defun orgtbl-insert-radio-table ()
11791 "Insert a radio table template appropriate for this major mode."
11792 (interactive)
11793 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11794 (txt (nth 1 e))
11795 name pos)
11796 (unless e (error "No radio table setup defined for %s" major-mode))
11797 (setq name (read-string "Table name: "))
11798 (while (string-match "%n" txt)
11799 (setq txt (replace-match name t t txt)))
11800 (or (bolp) (insert "\n"))
11801 (setq pos (point))
11802 (insert txt)
11803 (goto-char pos)))
11805 (defun org-get-param (params header i sym &optional hsym)
11806 "Get parameter value for symbol SYM.
11807 If this is a header line, actually get the value for the symbol with an
11808 additional \"h\" inserted after the colon.
11809 If the value is a protperty list, get the element for the current column.
11810 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11811 (let ((val (plist-get params sym)))
11812 (and hsym header (setq val (or (plist-get params hsym) val)))
11813 (if (consp val) (plist-get val i) val)))
11815 (defun orgtbl-to-generic (table params)
11816 "Convert the orgtbl-mode TABLE to some other format.
11817 This generic routine can be used for many standard cases.
11818 TABLE is a list, each entry either the symbol `hline' for a horizontal
11819 separator line, or a list of fields for that line.
11820 PARAMS is a property list of parameters that can influence the conversion.
11821 For the generic converter, some parameters are obligatory: You need to
11822 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11823 :splice, you must have :tstart and :tend.
11825 Valid parameters are
11827 :tstart String to start the table. Ignored when :splice is t.
11828 :tend String to end the table. Ignored when :splice is t.
11830 :splice When set to t, return only table body lines, don't wrap
11831 them into :tstart and :tend. Default is nil.
11833 :hline String to be inserted on horizontal separation lines.
11834 May be nil to ignore hlines.
11836 :lstart String to start a new table line.
11837 :lend String to end a table line
11838 :sep Separator between two fields
11839 :lfmt Format for entire line, with enough %s to capture all fields.
11840 If this is present, :lstart, :lend, and :sep are ignored.
11841 :fmt A format to be used to wrap the field, should contain
11842 %s for the original field value. For example, to wrap
11843 everything in dollars, you could use :fmt \"$%s$\".
11844 This may also be a property list with column numbers and
11845 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11847 :hlstart :hlend :hlsep :hlfmt :hfmt
11848 Same as above, specific for the header lines in the table.
11849 All lines before the first hline are treated as header.
11850 If any of these is not present, the data line value is used.
11852 :efmt Use this format to print numbers with exponentials.
11853 The format should have %s twice for inserting mantissa
11854 and exponent, for example \"%s\\\\times10^{%s}\". This
11855 may also be a property list with column numbers and
11856 formats. :fmt will still be applied after :efmt.
11858 In addition to this, the parameters :skip and :skipcols are always handled
11859 directly by `orgtbl-send-table'. See manual."
11860 (interactive)
11861 (let* ((p params)
11862 (splicep (plist-get p :splice))
11863 (hline (plist-get p :hline))
11864 rtn line i fm efm lfmt h)
11866 ;; Do we have a header?
11867 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11868 (setq h t))
11870 ;; Put header
11871 (unless splicep
11872 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11874 ;; Now loop over all lines
11875 (while (setq line (pop table))
11876 (if (eq line 'hline)
11877 ;; A horizontal separator line
11878 (progn (if hline (push hline rtn))
11879 (setq h nil)) ; no longer in header
11880 ;; A normal line. Convert the fields, push line onto the result list
11881 (setq i 0)
11882 (setq line
11883 (mapcar
11884 (lambda (f)
11885 (setq i (1+ i)
11886 fm (org-get-param p h i :fmt :hfmt)
11887 efm (org-get-param p h i :efmt))
11888 (if (and efm (string-match orgtbl-exp-regexp f))
11889 (setq f (format
11890 efm (match-string 1 f) (match-string 2 f))))
11891 (if fm (setq f (format fm f)))
11893 line))
11894 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11895 (push (apply 'format lfmt line) rtn)
11896 (push (concat
11897 (org-get-param p h i :lstart :hlstart)
11898 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11899 (org-get-param p h i :lend :hlend))
11900 rtn))))
11902 (unless splicep
11903 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11905 (mapconcat 'identity (nreverse rtn) "\n")))
11907 (defun orgtbl-to-latex (table params)
11908 "Convert the orgtbl-mode TABLE to LaTeX.
11909 TABLE is a list, each entry either the symbol `hline' for a horizontal
11910 separator line, or a list of fields for that line.
11911 PARAMS is a property list of parameters that can influence the conversion.
11912 Supports all parameters from `orgtbl-to-generic'. Most important for
11913 LaTeX are:
11915 :splice When set to t, return only table body lines, don't wrap
11916 them into a tabular environment. Default is nil.
11918 :fmt A format to be used to wrap the field, should contain %s for the
11919 original field value. For example, to wrap everything in dollars,
11920 use :fmt \"$%s$\". This may also be a property list with column
11921 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11923 :efmt Format for transforming numbers with exponentials. The format
11924 should have %s twice for inserting mantissa and exponent, for
11925 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
11926 This may also be a property list with column numbers and formats.
11928 The general parameters :skip and :skipcols have already been applied when
11929 this function is called."
11930 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
11931 org-table-last-alignment ""))
11932 (params2
11933 (list
11934 :tstart (concat "\\begin{tabular}{" alignment "}")
11935 :tend "\\end{tabular}"
11936 :lstart "" :lend " \\\\" :sep " & "
11937 :efmt "%s\\,(%s)" :hline "\\hline")))
11938 (orgtbl-to-generic table (org-combine-plists params2 params))))
11940 (defun orgtbl-to-html (table params)
11941 "Convert the orgtbl-mode TABLE to LaTeX.
11942 TABLE is a list, each entry either the symbol `hline' for a horizontal
11943 separator line, or a list of fields for that line.
11944 PARAMS is a property list of parameters that can influence the conversion.
11945 Currently this function recognizes the following parameters:
11947 :splice When set to t, return only table body lines, don't wrap
11948 them into a <table> environment. Default is nil.
11950 The general parameters :skip and :skipcols have already been applied when
11951 this function is called. The function does *not* use `orgtbl-to-generic',
11952 so you cannot specify parameters for it."
11953 (let* ((splicep (plist-get params :splice))
11954 html)
11955 ;; Just call the formatter we already have
11956 ;; We need to make text lines for it, so put the fields back together.
11957 (setq html (org-format-org-table-html
11958 (mapcar
11959 (lambda (x)
11960 (if (eq x 'hline)
11961 "|----+----|"
11962 (concat "| " (mapconcat 'identity x " | ") " |")))
11963 table)
11964 splicep))
11965 (if (string-match "\n+\\'" html)
11966 (setq html (replace-match "" t t html)))
11967 html))
11969 (defun orgtbl-to-texinfo (table params)
11970 "Convert the orgtbl-mode TABLE to TeXInfo.
11971 TABLE is a list, each entry either the symbol `hline' for a horizontal
11972 separator line, or a list of fields for that line.
11973 PARAMS is a property list of parameters that can influence the conversion.
11974 Supports all parameters from `orgtbl-to-generic'. Most important for
11975 TeXInfo are:
11977 :splice nil/t When set to t, return only table body lines, don't wrap
11978 them into a multitable environment. Default is nil.
11980 :fmt fmt A format to be used to wrap the field, should contain
11981 %s for the original field value. For example, to wrap
11982 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
11983 This may also be a property list with column numbers and
11984 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
11986 :cf \"f1 f2..\" The column fractions for the table. By default these
11987 are computed automatically from the width of the columns
11988 under org-mode.
11990 The general parameters :skip and :skipcols have already been applied when
11991 this function is called."
11992 (let* ((total (float (apply '+ org-table-last-column-widths)))
11993 (colfrac (or (plist-get params :cf)
11994 (mapconcat
11995 (lambda (x) (format "%.3f" (/ (float x) total)))
11996 org-table-last-column-widths " ")))
11997 (params2
11998 (list
11999 :tstart (concat "@multitable @columnfractions " colfrac)
12000 :tend "@end multitable"
12001 :lstart "@item " :lend "" :sep " @tab "
12002 :hlstart "@headitem ")))
12003 (orgtbl-to-generic table (org-combine-plists params2 params))))
12005 ;;;; Link Stuff
12007 ;;; Link abbreviations
12009 (defun org-link-expand-abbrev (link)
12010 "Apply replacements as defined in `org-link-abbrev-alist."
12011 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12012 (let* ((key (match-string 1 link))
12013 (as (or (assoc key org-link-abbrev-alist-local)
12014 (assoc key org-link-abbrev-alist)))
12015 (tag (and (match-end 2) (match-string 3 link)))
12016 rpl)
12017 (if (not as)
12018 link
12019 (setq rpl (cdr as))
12020 (cond
12021 ((symbolp rpl) (funcall rpl tag))
12022 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12023 (t (concat rpl tag)))))
12024 link))
12026 ;;; Storing and inserting links
12028 (defvar org-insert-link-history nil
12029 "Minibuffer history for links inserted with `org-insert-link'.")
12031 (defvar org-stored-links nil
12032 "Contains the links stored with `org-store-link'.")
12034 (defvar org-store-link-plist nil
12035 "Plist with info about the most recently link created with `org-store-link'.")
12037 (defvar org-link-protocols nil
12038 "Link protocols added to Org-mode using `org-add-link-type'.")
12040 (defvar org-store-link-functions nil
12041 "List of functions that are called to create and store a link.
12042 Each function will be called in turn until one returns a non-nil
12043 value. Each function should check if it is responsible for creating
12044 this link (for example by looking at the major mode).
12045 If not, it must exit and return nil.
12046 If yes, it should return a non-nil value after a calling
12047 `org-store-link-props' with a list of properties and values.
12048 Special properties are:
12050 :type The link prefix. like \"http\". This must be given.
12051 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12052 This is obligatory as well.
12053 :description Optional default description for the second pair
12054 of brackets in an Org-mode link. The user can still change
12055 this when inserting this link into an Org-mode buffer.
12057 In addition to these, any additional properties can be specified
12058 and then used in remember templates.")
12060 (defun org-add-link-type (type &optional follow publish)
12061 "Add TYPE to the list of `org-link-types'.
12062 Re-compute all regular expressions depending on `org-link-types'
12063 FOLLOW and PUBLISH are two functions. Both take the link path as
12064 an argument.
12065 FOLLOW should do whatever is necessary to follow the link, for example
12066 to find a file or display a mail message.
12068 PUBLISH takes the path and retuns the string that should be used when
12069 this document is published. FIMXE: This is actually not yet implemented."
12070 (add-to-list 'org-link-types type t)
12071 (org-make-link-regexps)
12072 (add-to-list 'org-link-protocols
12073 (list type follow publish)))
12075 (defun org-add-agenda-custom-command (entry)
12076 "Replace or add a command in `org-agenda-custom-commands'.
12077 This is mostly for hacking and trying a new command - once the command
12078 works you probably want to add it to `org-agenda-custom-commands' for good."
12079 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12080 (if ass
12081 (setcdr ass (cdr entry))
12082 (push entry org-agenda-custom-commands))))
12084 ;;;###autoload
12085 (defun org-store-link (arg)
12086 "\\<org-mode-map>Store an org-link to the current location.
12087 This link is added to `org-stored-links' and can later be inserted
12088 into an org-buffer with \\[org-insert-link].
12090 For some link types, a prefix arg is interpreted:
12091 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12092 For file links, arg negates `org-context-in-file-links'."
12093 (interactive "P")
12094 (setq org-store-link-plist nil) ; reset
12095 (let (link cpltxt desc description search txt)
12096 (cond
12098 ((run-hook-with-args-until-success 'org-store-link-functions)
12099 (setq link (plist-get org-store-link-plist :link)
12100 desc (or (plist-get org-store-link-plist :description) link)))
12102 ((eq major-mode 'bbdb-mode)
12103 (let ((name (bbdb-record-name (bbdb-current-record)))
12104 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12105 (setq cpltxt (concat "bbdb:" (or name company))
12106 link (org-make-link cpltxt))
12107 (org-store-link-props :type "bbdb" :name name :company company)))
12109 ((eq major-mode 'Info-mode)
12110 (setq link (org-make-link "info:"
12111 (file-name-nondirectory Info-current-file)
12112 ":" Info-current-node))
12113 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12114 ":" Info-current-node))
12115 (org-store-link-props :type "info" :file Info-current-file
12116 :node Info-current-node))
12118 ((eq major-mode 'calendar-mode)
12119 (let ((cd (calendar-cursor-to-date)))
12120 (setq link
12121 (format-time-string
12122 (car org-time-stamp-formats)
12123 (apply 'encode-time
12124 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12125 nil nil nil))))
12126 (org-store-link-props :type "calendar" :date cd)))
12128 ((or (eq major-mode 'vm-summary-mode)
12129 (eq major-mode 'vm-presentation-mode))
12130 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12131 (vm-follow-summary-cursor)
12132 (save-excursion
12133 (vm-select-folder-buffer)
12134 (let* ((message (car vm-message-pointer))
12135 (folder buffer-file-name)
12136 (subject (vm-su-subject message))
12137 (to (vm-get-header-contents message "To"))
12138 (from (vm-get-header-contents message "From"))
12139 (message-id (vm-su-message-id message)))
12140 (org-store-link-props :type "vm" :from from :to to :subject subject
12141 :message-id message-id)
12142 (setq message-id (org-remove-angle-brackets message-id))
12143 (setq folder (abbreviate-file-name folder))
12144 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12145 folder)
12146 (setq folder (replace-match "" t t folder)))
12147 (setq cpltxt (org-email-link-description))
12148 (setq link (org-make-link "vm:" folder "#" message-id)))))
12150 ((eq major-mode 'wl-summary-mode)
12151 (let* ((msgnum (wl-summary-message-number))
12152 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12153 msgnum 'message-id))
12154 (wl-message-entity
12155 (if (fboundp 'elmo-message-entity)
12156 (elmo-message-entity
12157 wl-summary-buffer-elmo-folder msgnum)
12158 (elmo-msgdb-overview-get-entity
12159 msgnum (wl-summary-buffer-msgdb))))
12160 (from (wl-summary-line-from))
12161 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12162 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12163 (wl-summary-line-subject))))
12164 (org-store-link-props :type "wl" :from from :to to
12165 :subject subject :message-id message-id)
12166 (setq message-id (org-remove-angle-brackets message-id))
12167 (setq cpltxt (org-email-link-description))
12168 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12169 "#" message-id))))
12171 ((or (equal major-mode 'mh-folder-mode)
12172 (equal major-mode 'mh-show-mode))
12173 (let ((from (org-mhe-get-header "From:"))
12174 (to (org-mhe-get-header "To:"))
12175 (message-id (org-mhe-get-header "Message-Id:"))
12176 (subject (org-mhe-get-header "Subject:")))
12177 (org-store-link-props :type "mh" :from from :to to
12178 :subject subject :message-id message-id)
12179 (setq cpltxt (org-email-link-description))
12180 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12181 (org-remove-angle-brackets message-id)))))
12183 ((or (eq major-mode 'rmail-mode)
12184 (eq major-mode 'rmail-summary-mode))
12185 (save-window-excursion
12186 (save-restriction
12187 (when (eq major-mode 'rmail-summary-mode)
12188 (rmail-show-message rmail-current-message))
12189 (rmail-narrow-to-non-pruned-header)
12190 (let ((folder buffer-file-name)
12191 (message-id (mail-fetch-field "message-id"))
12192 (from (mail-fetch-field "from"))
12193 (to (mail-fetch-field "to"))
12194 (subject (mail-fetch-field "subject")))
12195 (org-store-link-props
12196 :type "rmail" :from from :to to
12197 :subject subject :message-id message-id)
12198 (setq message-id (org-remove-angle-brackets message-id))
12199 (setq cpltxt (org-email-link-description))
12200 (setq link (org-make-link "rmail:" folder "#" message-id)))
12201 (rmail-show-message rmail-current-message))))
12203 ((eq major-mode 'gnus-group-mode)
12204 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12205 (gnus-group-group-name)) ; version
12206 ((fboundp 'gnus-group-name)
12207 (gnus-group-name))
12208 (t "???"))))
12209 (unless group (error "Not on a group"))
12210 (org-store-link-props :type "gnus" :group group)
12211 (setq cpltxt (concat
12212 (if (org-xor arg org-usenet-links-prefer-google)
12213 "http://groups.google.com/groups?group="
12214 "gnus:")
12215 group)
12216 link (org-make-link cpltxt))))
12218 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12219 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12220 (let* ((group gnus-newsgroup-name)
12221 (article (gnus-summary-article-number))
12222 (header (gnus-summary-article-header article))
12223 (from (mail-header-from header))
12224 (message-id (mail-header-id header))
12225 (date (mail-header-date header))
12226 (subject (gnus-summary-subject-string)))
12227 (org-store-link-props :type "gnus" :from from :subject subject
12228 :message-id message-id :group group)
12229 (setq cpltxt (org-email-link-description))
12230 (if (org-xor arg org-usenet-links-prefer-google)
12231 (setq link
12232 (concat
12233 cpltxt "\n "
12234 (format "http://groups.google.com/groups?as_umsgid=%s"
12235 (org-fixup-message-id-for-http message-id))))
12236 (setq link (org-make-link "gnus:" group
12237 "#" (number-to-string article))))))
12239 ((eq major-mode 'w3-mode)
12240 (setq cpltxt (url-view-url t)
12241 link (org-make-link cpltxt))
12242 (org-store-link-props :type "w3" :url (url-view-url t)))
12244 ((eq major-mode 'w3m-mode)
12245 (setq cpltxt (or w3m-current-title w3m-current-url)
12246 link (org-make-link w3m-current-url))
12247 (org-store-link-props :type "w3m" :url (url-view-url t)))
12249 ((setq search (run-hook-with-args-until-success
12250 'org-create-file-search-functions))
12251 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12252 "::" search))
12253 (setq cpltxt (or description link)))
12255 ((eq major-mode 'image-mode)
12256 (setq cpltxt (concat "file:"
12257 (abbreviate-file-name buffer-file-name))
12258 link (org-make-link cpltxt))
12259 (org-store-link-props :type "image" :file buffer-file-name))
12261 ((eq major-mode 'dired-mode)
12262 ;; link to the file in the current line
12263 (setq cpltxt (concat "file:"
12264 (abbreviate-file-name
12265 (expand-file-name
12266 (dired-get-filename nil t))))
12267 link (org-make-link cpltxt)))
12269 ((and buffer-file-name (org-mode-p))
12270 ;; Just link to current headline
12271 (setq cpltxt (concat "file:"
12272 (abbreviate-file-name buffer-file-name)))
12273 ;; Add a context search string
12274 (when (org-xor org-context-in-file-links arg)
12275 ;; Check if we are on a target
12276 (if (org-in-regexp "<<\\(.*?\\)>>")
12277 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12278 (setq txt (cond
12279 ((org-on-heading-p) nil)
12280 ((org-region-active-p)
12281 (buffer-substring (region-beginning) (region-end)))
12282 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12283 (when (or (null txt) (string-match "\\S-" txt))
12284 (setq cpltxt
12285 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12286 desc "NONE"))))
12287 (if (string-match "::\\'" cpltxt)
12288 (setq cpltxt (substring cpltxt 0 -2)))
12289 (setq link (org-make-link cpltxt)))
12291 ((buffer-file-name (buffer-base-buffer))
12292 ;; Just link to this file here.
12293 (setq cpltxt (concat "file:"
12294 (abbreviate-file-name
12295 (buffer-file-name (buffer-base-buffer)))))
12296 ;; Add a context string
12297 (when (org-xor org-context-in-file-links arg)
12298 (setq txt (if (org-region-active-p)
12299 (buffer-substring (region-beginning) (region-end))
12300 (buffer-substring (point-at-bol) (point-at-eol))))
12301 ;; Only use search option if there is some text.
12302 (when (string-match "\\S-" txt)
12303 (setq cpltxt
12304 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12305 desc "NONE")))
12306 (setq link (org-make-link cpltxt)))
12308 ((interactive-p)
12309 (error "Cannot link to a buffer which is not visiting a file"))
12311 (t (setq link nil)))
12313 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12314 (setq link (or link cpltxt)
12315 desc (or desc cpltxt))
12316 (if (equal desc "NONE") (setq desc nil))
12318 (if (and (interactive-p) link)
12319 (progn
12320 (setq org-stored-links
12321 (cons (list link desc) org-stored-links))
12322 (message "Stored: %s" (or desc link)))
12323 (and link (org-make-link-string link desc)))))
12325 (defun org-store-link-props (&rest plist)
12326 "Store link properties, extract names and addresses."
12327 (let (x adr)
12328 (when (setq x (plist-get plist :from))
12329 (setq adr (mail-extract-address-components x))
12330 (plist-put plist :fromname (car adr))
12331 (plist-put plist :fromaddress (nth 1 adr)))
12332 (when (setq x (plist-get plist :to))
12333 (setq adr (mail-extract-address-components x))
12334 (plist-put plist :toname (car adr))
12335 (plist-put plist :toaddress (nth 1 adr))))
12336 (let ((from (plist-get plist :from))
12337 (to (plist-get plist :to)))
12338 (when (and from to org-from-is-user-regexp)
12339 (plist-put plist :fromto
12340 (if (string-match org-from-is-user-regexp from)
12341 (concat "to %t")
12342 (concat "from %f")))))
12343 (setq org-store-link-plist plist))
12345 (defun org-email-link-description (&optional fmt)
12346 "Return the description part of an email link.
12347 This takes information from `org-store-link-plist' and formats it
12348 according to FMT (default from `org-email-link-description-format')."
12349 (setq fmt (or fmt org-email-link-description-format))
12350 (let* ((p org-store-link-plist)
12351 (to (plist-get p :toaddress))
12352 (from (plist-get p :fromaddress))
12353 (table
12354 (list
12355 (cons "%c" (plist-get p :fromto))
12356 (cons "%F" (plist-get p :from))
12357 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12358 (cons "%T" (plist-get p :to))
12359 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12360 (cons "%s" (plist-get p :subject))
12361 (cons "%m" (plist-get p :message-id)))))
12362 (when (string-match "%c" fmt)
12363 ;; Check if the user wrote this message
12364 (if (and org-from-is-user-regexp from to
12365 (save-match-data (string-match org-from-is-user-regexp from)))
12366 (setq fmt (replace-match "to %t" t t fmt))
12367 (setq fmt (replace-match "from %f" t t fmt))))
12368 (org-replace-escapes fmt table)))
12370 (defun org-make-org-heading-search-string (&optional string heading)
12371 "Make search string for STRING or current headline."
12372 (interactive)
12373 (let ((s (or string (org-get-heading))))
12374 (unless (and string (not heading))
12375 ;; We are using a headline, clean up garbage in there.
12376 (if (string-match org-todo-regexp s)
12377 (setq s (replace-match "" t t s)))
12378 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12379 (setq s (replace-match "" t t s)))
12380 (setq s (org-trim s))
12381 (if (string-match (concat "^\\(" org-quote-string "\\|"
12382 org-comment-string "\\)") s)
12383 (setq s (replace-match "" t t s)))
12384 (while (string-match org-ts-regexp s)
12385 (setq s (replace-match "" t t s))))
12386 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12387 (setq s (replace-match " " t t s)))
12388 (or string (setq s (concat "*" s))) ; Add * for headlines
12389 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12391 (defun org-make-link (&rest strings)
12392 "Concatenate STRINGS."
12393 (apply 'concat strings))
12395 (defun org-make-link-string (link &optional description)
12396 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12397 (unless (string-match "\\S-" link)
12398 (error "Empty link"))
12399 (when (stringp description)
12400 ;; Remove brackets from the description, they are fatal.
12401 (while (string-match "\\[" description)
12402 (setq description (replace-match "{" t t description)))
12403 (while (string-match "\\]" description)
12404 (setq description (replace-match "}" t t description))))
12405 (when (equal (org-link-escape link) description)
12406 ;; No description needed, it is identical
12407 (setq description nil))
12408 (when (and (not description)
12409 (not (equal link (org-link-escape link))))
12410 (setq description link))
12411 (concat "[[" (org-link-escape link) "]"
12412 (if description (concat "[" description "]") "")
12413 "]"))
12415 (defconst org-link-escape-chars
12416 '((?\ . "%20")
12417 (?\[ . "%5B")
12418 (?\] . "%5D")
12419 (?\340 . "%E0") ; `a
12420 (?\342 . "%E2") ; ^a
12421 (?\347 . "%E7") ; ,c
12422 (?\350 . "%E8") ; `e
12423 (?\351 . "%E9") ; 'e
12424 (?\352 . "%EA") ; ^e
12425 (?\356 . "%EE") ; ^i
12426 (?\364 . "%F4") ; ^o
12427 (?\371 . "%F9") ; `u
12428 (?\373 . "%FB") ; ^u
12429 (?\; . "%3B")
12430 (?? . "%3F")
12431 (?= . "%3D")
12432 (?+ . "%2B")
12434 "Association list of escapes for some characters problematic in links.
12435 This is the list that is used for internal purposes.")
12437 (defconst org-link-escape-chars-browser
12438 '((?\ . "%20")) ; 32 for the SPC char
12439 "Association list of escapes for some characters problematic in links.
12440 This is the list that is used before handing over to the browser.")
12442 (defun org-link-escape (text &optional table)
12443 "Escape charaters in TEXT that are problematic for links."
12444 (setq table (or table org-link-escape-chars))
12445 (when text
12446 (let ((re (mapconcat (lambda (x) (regexp-quote
12447 (char-to-string (car x))))
12448 table "\\|")))
12449 (while (string-match re text)
12450 (setq text
12451 (replace-match
12452 (cdr (assoc (string-to-char (match-string 0 text))
12453 table))
12454 t t text)))
12455 text)))
12457 (defun org-link-unescape (text &optional table)
12458 "Reverse the action of `org-link-escape'."
12459 (setq table (or table org-link-escape-chars))
12460 (when text
12461 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12462 table "\\|")))
12463 (while (string-match re text)
12464 (setq text
12465 (replace-match
12466 (char-to-string (car (rassoc (match-string 0 text) table)))
12467 t t text)))
12468 text)))
12470 (defun org-xor (a b)
12471 "Exclusive or."
12472 (if a (not b) b))
12474 (defun org-get-header (header)
12475 "Find a header field in the current buffer."
12476 (save-excursion
12477 (goto-char (point-min))
12478 (let ((case-fold-search t) s)
12479 (cond
12480 ((eq header 'from)
12481 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12482 (setq s (match-string 1)))
12483 (while (string-match "\"" s)
12484 (setq s (replace-match "" t t s)))
12485 (if (string-match "[<(].*" s)
12486 (setq s (replace-match "" t t s))))
12487 ((eq header 'message-id)
12488 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12489 (setq s (match-string 1))))
12490 ((eq header 'subject)
12491 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12492 (setq s (match-string 1)))))
12493 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12494 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12495 s)))
12498 (defun org-fixup-message-id-for-http (s)
12499 "Replace special characters in a message id, so it can be used in an http query."
12500 (while (string-match "<" s)
12501 (setq s (replace-match "%3C" t t s)))
12502 (while (string-match ">" s)
12503 (setq s (replace-match "%3E" t t s)))
12504 (while (string-match "@" s)
12505 (setq s (replace-match "%40" t t s)))
12508 ;;;###autoload
12509 (defun org-insert-link-global ()
12510 "Insert a link like Org-mode does.
12511 This command can be called in any mode to insert a link in Org-mode syntax."
12512 (interactive)
12513 (org-run-like-in-org-mode 'org-insert-link))
12515 (defun org-insert-link (&optional complete-file)
12516 "Insert a link. At the prompt, enter the link.
12518 Completion can be used to select a link previously stored with
12519 `org-store-link'. When the empty string is entered (i.e. if you just
12520 press RET at the prompt), the link defaults to the most recently
12521 stored link. As SPC triggers completion in the minibuffer, you need to
12522 use M-SPC or C-q SPC to force the insertion of a space character.
12524 You will also be prompted for a description, and if one is given, it will
12525 be displayed in the buffer instead of the link.
12527 If there is already a link at point, this command will allow you to edit link
12528 and description parts.
12530 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12531 selected using completion. The path to the file will be relative to
12532 the current directory if the file is in the current directory or a
12533 subdirectory. Otherwise, the link will be the absolute path as
12534 completed in the minibuffer (i.e. normally ~/path/to/file).
12536 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12537 is in the current directory or below.
12538 With three \\[universal-argument] prefixes, negate the meaning of
12539 `org-keep-stored-link-after-insertion'."
12540 (interactive "P")
12541 (let* ((wcf (current-window-configuration))
12542 (region (if (org-region-active-p)
12543 (buffer-substring (region-beginning) (region-end))))
12544 (remove (and region (list (region-beginning) (region-end))))
12545 (desc region)
12546 tmphist ; byte-compile incorrectly complains about this
12547 link entry file)
12548 (cond
12549 ((org-in-regexp org-bracket-link-regexp 1)
12550 ;; We do have a link at point, and we are going to edit it.
12551 (setq remove (list (match-beginning 0) (match-end 0)))
12552 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12553 (setq link (read-string "Link: "
12554 (org-link-unescape
12555 (org-match-string-no-properties 1)))))
12556 ((or (org-in-regexp org-angle-link-re)
12557 (org-in-regexp org-plain-link-re))
12558 ;; Convert to bracket link
12559 (setq remove (list (match-beginning 0) (match-end 0))
12560 link (read-string "Link: "
12561 (org-remove-angle-brackets (match-string 0)))))
12562 ((equal complete-file '(4))
12563 ;; Completing read for file names.
12564 (setq file (read-file-name "File: "))
12565 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12566 (pwd1 (file-name-as-directory (abbreviate-file-name
12567 (expand-file-name ".")))))
12568 (cond
12569 ((equal complete-file '(16))
12570 (setq link (org-make-link
12571 "file:"
12572 (abbreviate-file-name (expand-file-name file)))))
12573 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12574 (setq link (org-make-link "file:" (match-string 1 file))))
12575 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12576 (expand-file-name file))
12577 (setq link (org-make-link
12578 "file:" (match-string 1 (expand-file-name file)))))
12579 (t (setq link (org-make-link "file:" file))))))
12581 ;; Read link, with completion for stored links.
12582 (with-output-to-temp-buffer "*Org Links*"
12583 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12584 (when org-stored-links
12585 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12586 (princ (mapconcat
12587 (lambda (x)
12588 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12589 (reverse org-stored-links) "\n"))))
12590 (let ((cw (selected-window)))
12591 (select-window (get-buffer-window "*Org Links*"))
12592 (shrink-window-if-larger-than-buffer)
12593 (setq truncate-lines t)
12594 (select-window cw))
12595 ;; Fake a link history, containing the stored links.
12596 (setq tmphist (append (mapcar 'car org-stored-links)
12597 org-insert-link-history))
12598 (unwind-protect
12599 (setq link (org-completing-read
12600 "Link: "
12601 (append
12602 (mapcar (lambda (x) (list (concat (car x) ":")))
12603 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12604 (mapcar (lambda (x) (list (concat x ":")))
12605 org-link-types))
12606 nil nil nil
12607 'tmphist
12608 (or (car (car org-stored-links)))))
12609 (set-window-configuration wcf)
12610 (kill-buffer "*Org Links*"))
12611 (setq entry (assoc link org-stored-links))
12612 (or entry (push link org-insert-link-history))
12613 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12614 (not org-keep-stored-link-after-insertion))
12615 (setq org-stored-links (delq (assoc link org-stored-links)
12616 org-stored-links)))
12617 (setq desc (or desc (nth 1 entry)))))
12619 (if (string-match org-plain-link-re link)
12620 ;; URL-like link, normalize the use of angular brackets.
12621 (setq link (org-make-link (org-remove-angle-brackets link))))
12623 ;; Check if we are linking to the current file with a search option
12624 ;; If yes, simplify the link by using only the search option.
12625 (when (and buffer-file-name
12626 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12627 (let* ((path (match-string 1 link))
12628 (case-fold-search nil)
12629 (search (match-string 2 link)))
12630 (save-match-data
12631 (if (equal (file-truename buffer-file-name) (file-truename path))
12632 ;; We are linking to this same file, with a search option
12633 (setq link search)))))
12635 ;; Check if we can/should use a relative path. If yes, simplify the link
12636 (when (string-match "\\<file:\\(.*\\)" link)
12637 (let* ((path (match-string 1 link))
12638 (origpath path)
12639 (case-fold-search nil))
12640 (cond
12641 ((eq org-link-file-path-type 'absolute)
12642 (setq path (abbreviate-file-name (expand-file-name path))))
12643 ((eq org-link-file-path-type 'noabbrev)
12644 (setq path (expand-file-name path)))
12645 ((eq org-link-file-path-type 'relative)
12646 (setq path (file-relative-name path)))
12648 (save-match-data
12649 (if (string-match (concat "^" (regexp-quote
12650 (file-name-as-directory
12651 (expand-file-name "."))))
12652 (expand-file-name path))
12653 ;; We are linking a file with relative path name.
12654 (setq path (substring (expand-file-name path)
12655 (match-end 0)))))))
12656 (setq link (concat "file:" path))
12657 (if (equal desc origpath)
12658 (setq desc path))))
12660 (setq desc (read-string "Description: " desc))
12661 (unless (string-match "\\S-" desc) (setq desc nil))
12662 (if remove (apply 'delete-region remove))
12663 (insert (org-make-link-string link desc))))
12665 (defun org-completing-read (&rest args)
12666 (let ((minibuffer-local-completion-map
12667 (copy-keymap minibuffer-local-completion-map)))
12668 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12669 (apply 'completing-read args)))
12671 ;;; Opening/following a link
12672 (defvar org-link-search-failed nil)
12674 (defun org-next-link ()
12675 "Move forward to the next link.
12676 If the link is in hidden text, expose it."
12677 (interactive)
12678 (when (and org-link-search-failed (eq this-command last-command))
12679 (goto-char (point-min))
12680 (message "Link search wrapped back to beginning of buffer"))
12681 (setq org-link-search-failed nil)
12682 (let* ((pos (point))
12683 (ct (org-context))
12684 (a (assoc :link ct)))
12685 (if a (goto-char (nth 2 a)))
12686 (if (re-search-forward org-any-link-re nil t)
12687 (progn
12688 (goto-char (match-beginning 0))
12689 (if (org-invisible-p) (org-show-context)))
12690 (goto-char pos)
12691 (setq org-link-search-failed t)
12692 (error "No further link found"))))
12694 (defun org-previous-link ()
12695 "Move backward to the previous link.
12696 If the link is in hidden text, expose it."
12697 (interactive)
12698 (when (and org-link-search-failed (eq this-command last-command))
12699 (goto-char (point-max))
12700 (message "Link search wrapped back to end of buffer"))
12701 (setq org-link-search-failed nil)
12702 (let* ((pos (point))
12703 (ct (org-context))
12704 (a (assoc :link ct)))
12705 (if a (goto-char (nth 1 a)))
12706 (if (re-search-backward org-any-link-re nil t)
12707 (progn
12708 (goto-char (match-beginning 0))
12709 (if (org-invisible-p) (org-show-context)))
12710 (goto-char pos)
12711 (setq org-link-search-failed t)
12712 (error "No further link found"))))
12714 (defun org-find-file-at-mouse (ev)
12715 "Open file link or URL at mouse."
12716 (interactive "e")
12717 (mouse-set-point ev)
12718 (org-open-at-point 'in-emacs))
12720 (defun org-open-at-mouse (ev)
12721 "Open file link or URL at mouse."
12722 (interactive "e")
12723 (mouse-set-point ev)
12724 (org-open-at-point))
12726 (defvar org-window-config-before-follow-link nil
12727 "The window configuration before following a link.
12728 This is saved in case the need arises to restore it.")
12730 (defvar org-open-link-marker (make-marker)
12731 "Marker pointing to the location where `org-open-at-point; was called.")
12733 ;;;###autoload
12734 (defun org-open-at-point-global ()
12735 "Follow a link like Org-mode does.
12736 This command can be called in any mode to follow a link that has
12737 Org-mode syntax."
12738 (interactive)
12739 (org-run-like-in-org-mode 'org-open-at-point))
12741 (defun org-open-at-point (&optional in-emacs)
12742 "Open link at or after point.
12743 If there is no link at point, this function will search forward up to
12744 the end of the current subtree.
12745 Normally, files will be opened by an appropriate application. If the
12746 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12747 (interactive "P")
12748 (move-marker org-open-link-marker (point))
12749 (setq org-window-config-before-follow-link (current-window-configuration))
12750 (org-remove-occur-highlights nil nil t)
12751 (if (org-at-timestamp-p t)
12752 (org-follow-timestamp-link)
12753 (let (type path link line search (pos (point)))
12754 (catch 'match
12755 (save-excursion
12756 (skip-chars-forward "^]\n\r")
12757 (when (org-in-regexp org-bracket-link-regexp)
12758 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12759 (while (string-match " *\n *" link)
12760 (setq link (replace-match " " t t link)))
12761 (setq link (org-link-expand-abbrev link))
12762 (if (string-match org-link-re-with-space2 link)
12763 (setq type (match-string 1 link) path (match-string 2 link))
12764 (setq type "thisfile" path link))
12765 (throw 'match t)))
12767 (when (get-text-property (point) 'org-linked-text)
12768 (setq type "thisfile"
12769 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12770 (1+ (point)) (point))
12771 path (buffer-substring
12772 (previous-single-property-change pos 'org-linked-text)
12773 (next-single-property-change pos 'org-linked-text)))
12774 (throw 'match t))
12776 (save-excursion
12777 (when (or (org-in-regexp org-angle-link-re)
12778 (org-in-regexp org-plain-link-re))
12779 (setq type (match-string 1) path (match-string 2))
12780 (throw 'match t)))
12781 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12782 (setq type "tree-match"
12783 path (match-string 1))
12784 (throw 'match t))
12785 (save-excursion
12786 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12787 (setq type "tags"
12788 path (match-string 1))
12789 (while (string-match ":" path)
12790 (setq path (replace-match "+" t t path)))
12791 (throw 'match t))))
12792 (unless path
12793 (error "No link found"))
12794 ;; Remove any trailing spaces in path
12795 (if (string-match " +\\'" path)
12796 (setq path (replace-match "" t t path)))
12798 (cond
12800 ((assoc type org-link-protocols)
12801 (funcall (nth 1 (assoc type org-link-protocols)) path))
12803 ((equal type "mailto")
12804 (let ((cmd (car org-link-mailto-program))
12805 (args (cdr org-link-mailto-program)) args1
12806 (address path) (subject "") a)
12807 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12808 (setq address (match-string 1 path)
12809 subject (org-link-escape (match-string 2 path))))
12810 (while args
12811 (cond
12812 ((not (stringp (car args))) (push (pop args) args1))
12813 (t (setq a (pop args))
12814 (if (string-match "%a" a)
12815 (setq a (replace-match address t t a)))
12816 (if (string-match "%s" a)
12817 (setq a (replace-match subject t t a)))
12818 (push a args1))))
12819 (apply cmd (nreverse args1))))
12821 ((member type '("http" "https" "ftp" "news"))
12822 (browse-url (concat type ":" (org-link-escape
12823 path org-link-escape-chars-browser))))
12825 ((member type '("message"))
12826 (browse-url (concat type ":" path)))
12828 ((string= type "tags")
12829 (org-tags-view in-emacs path))
12830 ((string= type "thisfile")
12831 (if in-emacs
12832 (switch-to-buffer-other-window
12833 (org-get-buffer-for-internal-link (current-buffer)))
12834 (org-mark-ring-push))
12835 (let ((cmd `(org-link-search
12836 ,path
12837 ,(cond ((equal in-emacs '(4)) 'occur)
12838 ((equal in-emacs '(16)) 'org-occur)
12839 (t nil))
12840 ,pos)))
12841 (condition-case nil (eval cmd)
12842 (error (progn (widen) (eval cmd))))))
12844 ((string= type "tree-match")
12845 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12847 ((string= type "file")
12848 (if (string-match "::\\([0-9]+\\)\\'" path)
12849 (setq line (string-to-number (match-string 1 path))
12850 path (substring path 0 (match-beginning 0)))
12851 (if (string-match "::\\(.+\\)\\'" path)
12852 (setq search (match-string 1 path)
12853 path (substring path 0 (match-beginning 0)))))
12854 (if (string-match "[*?{]" (file-name-nondirectory path))
12855 (dired path)
12856 (org-open-file path in-emacs line search)))
12858 ((string= type "news")
12859 (org-follow-gnus-link path))
12861 ((string= type "bbdb")
12862 (org-follow-bbdb-link path))
12864 ((string= type "info")
12865 (org-follow-info-link path))
12867 ((string= type "gnus")
12868 (let (group article)
12869 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12870 (error "Error in Gnus link"))
12871 (setq group (match-string 1 path)
12872 article (match-string 3 path))
12873 (org-follow-gnus-link group article)))
12875 ((string= type "vm")
12876 (let (folder article)
12877 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12878 (error "Error in VM link"))
12879 (setq folder (match-string 1 path)
12880 article (match-string 3 path))
12881 ;; in-emacs is the prefix arg, will be interpreted as read-only
12882 (org-follow-vm-link folder article in-emacs)))
12884 ((string= type "wl")
12885 (let (folder article)
12886 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12887 (error "Error in Wanderlust link"))
12888 (setq folder (match-string 1 path)
12889 article (match-string 3 path))
12890 (org-follow-wl-link folder article)))
12892 ((string= type "mhe")
12893 (let (folder article)
12894 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12895 (error "Error in MHE link"))
12896 (setq folder (match-string 1 path)
12897 article (match-string 3 path))
12898 (org-follow-mhe-link folder article)))
12900 ((string= type "rmail")
12901 (let (folder article)
12902 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12903 (error "Error in RMAIL link"))
12904 (setq folder (match-string 1 path)
12905 article (match-string 3 path))
12906 (org-follow-rmail-link folder article)))
12908 ((string= type "shell")
12909 (let ((cmd path))
12910 (if (or (not org-confirm-shell-link-function)
12911 (funcall org-confirm-shell-link-function
12912 (format "Execute \"%s\" in shell? "
12913 (org-add-props cmd nil
12914 'face 'org-warning))))
12915 (progn
12916 (message "Executing %s" cmd)
12917 (shell-command cmd))
12918 (error "Abort"))))
12920 ((string= type "elisp")
12921 (let ((cmd path))
12922 (if (or (not org-confirm-elisp-link-function)
12923 (funcall org-confirm-elisp-link-function
12924 (format "Execute \"%s\" as elisp? "
12925 (org-add-props cmd nil
12926 'face 'org-warning))))
12927 (message "%s => %s" cmd (eval (read cmd)))
12928 (error "Abort"))))
12931 (browse-url-at-point)))))
12932 (move-marker org-open-link-marker nil))
12934 ;;; File search
12936 (defvar org-create-file-search-functions nil
12937 "List of functions to construct the right search string for a file link.
12938 These functions are called in turn with point at the location to
12939 which the link should point.
12941 A function in the hook should first test if it would like to
12942 handle this file type, for example by checking the major-mode or
12943 the file extension. If it decides not to handle this file, it
12944 should just return nil to give other functions a chance. If it
12945 does handle the file, it must return the search string to be used
12946 when following the link. The search string will be part of the
12947 file link, given after a double colon, and `org-open-at-point'
12948 will automatically search for it. If special measures must be
12949 taken to make the search successful, another function should be
12950 added to the companion hook `org-execute-file-search-functions',
12951 which see.
12953 A function in this hook may also use `setq' to set the variable
12954 `description' to provide a suggestion for the descriptive text to
12955 be used for this link when it gets inserted into an Org-mode
12956 buffer with \\[org-insert-link].")
12958 (defvar org-execute-file-search-functions nil
12959 "List of functions to execute a file search triggered by a link.
12961 Functions added to this hook must accept a single argument, the
12962 search string that was part of the file link, the part after the
12963 double colon. The function must first check if it would like to
12964 handle this search, for example by checking the major-mode or the
12965 file extension. If it decides not to handle this search, it
12966 should just return nil to give other functions a chance. If it
12967 does handle the search, it must return a non-nil value to keep
12968 other functions from trying.
12970 Each function can access the current prefix argument through the
12971 variable `current-prefix-argument'. Note that a single prefix is
12972 used to force opening a link in Emacs, so it may be good to only
12973 use a numeric or double prefix to guide the search function.
12975 In case this is needed, a function in this hook can also restore
12976 the window configuration before `org-open-at-point' was called using:
12978 (set-window-configuration org-window-config-before-follow-link)")
12980 (defun org-link-search (s &optional type avoid-pos)
12981 "Search for a link search option.
12982 If S is surrounded by forward slashes, it is interpreted as a
12983 regular expression. In org-mode files, this will create an `org-occur'
12984 sparse tree. In ordinary files, `occur' will be used to list matches.
12985 If the current buffer is in `dired-mode', grep will be used to search
12986 in all files. If AVOID-POS is given, ignore matches near that position."
12987 (let ((case-fold-search t)
12988 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
12989 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
12990 (append '(("") (" ") ("\t") ("\n"))
12991 org-emphasis-alist)
12992 "\\|") "\\)"))
12993 (pos (point))
12994 (pre "") (post "")
12995 words re0 re1 re2 re3 re4 re5 re2a reall)
12996 (cond
12997 ;; First check if there are any special
12998 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
12999 ;; Now try the builtin stuff
13000 ((save-excursion
13001 (goto-char (point-min))
13002 (and
13003 (re-search-forward
13004 (concat "<<" (regexp-quote s0) ">>") nil t)
13005 (setq pos (match-beginning 0))))
13006 ;; There is an exact target for this
13007 (goto-char pos))
13008 ((string-match "^/\\(.*\\)/$" s)
13009 ;; A regular expression
13010 (cond
13011 ((org-mode-p)
13012 (org-occur (match-string 1 s)))
13013 ;;((eq major-mode 'dired-mode)
13014 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13015 (t (org-do-occur (match-string 1 s)))))
13017 ;; A normal search strings
13018 (when (equal (string-to-char s) ?*)
13019 ;; Anchor on headlines, post may include tags.
13020 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13021 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13022 s (substring s 1)))
13023 (remove-text-properties
13024 0 (length s)
13025 '(face nil mouse-face nil keymap nil fontified nil) s)
13026 ;; Make a series of regular expressions to find a match
13027 (setq words (org-split-string s "[ \n\r\t]+")
13028 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13029 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13030 "\\)" markers)
13031 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13032 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13033 re1 (concat pre re2 post)
13034 re3 (concat pre re4 post)
13035 re5 (concat pre ".*" re4)
13036 re2 (concat pre re2)
13037 re2a (concat pre re2a)
13038 re4 (concat pre re4)
13039 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13040 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13041 re5 "\\)"
13043 (cond
13044 ((eq type 'org-occur) (org-occur reall))
13045 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13046 (t (goto-char (point-min))
13047 (if (or (org-search-not-self 1 re0 nil t)
13048 (org-search-not-self 1 re1 nil t)
13049 (org-search-not-self 1 re2 nil t)
13050 (org-search-not-self 1 re2a nil t)
13051 (org-search-not-self 1 re3 nil t)
13052 (org-search-not-self 1 re4 nil t)
13053 (org-search-not-self 1 re5 nil t)
13055 (goto-char (match-beginning 1))
13056 (goto-char pos)
13057 (error "No match")))))
13059 ;; Normal string-search
13060 (goto-char (point-min))
13061 (if (search-forward s nil t)
13062 (goto-char (match-beginning 0))
13063 (error "No match"))))
13064 (and (org-mode-p) (org-show-context 'link-search))))
13066 (defun org-search-not-self (group &rest args)
13067 "Execute `re-search-forward', but only accept matches that do not
13068 enclose the position of `org-open-link-marker'."
13069 (let ((m org-open-link-marker))
13070 (catch 'exit
13071 (while (apply 're-search-forward args)
13072 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13073 (goto-char (match-end group))
13074 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13075 (> (match-beginning 0) (marker-position m))
13076 (< (match-end 0) (marker-position m)))
13077 (save-match-data
13078 (or (not (org-in-regexp
13079 org-bracket-link-analytic-regexp 1))
13080 (not (match-end 4)) ; no description
13081 (and (<= (match-beginning 4) (point))
13082 (>= (match-end 4) (point))))))
13083 (throw 'exit (point))))))))
13085 (defun org-get-buffer-for-internal-link (buffer)
13086 "Return a buffer to be used for displaying the link target of internal links."
13087 (cond
13088 ((not org-display-internal-link-with-indirect-buffer)
13089 buffer)
13090 ((string-match "(Clone)$" (buffer-name buffer))
13091 (message "Buffer is already a clone, not making another one")
13092 ;; we also do not modify visibility in this case
13093 buffer)
13094 (t ; make a new indirect buffer for displaying the link
13095 (let* ((bn (buffer-name buffer))
13096 (ibn (concat bn "(Clone)"))
13097 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13098 (with-current-buffer ib (org-overview))
13099 ib))))
13101 (defun org-do-occur (regexp &optional cleanup)
13102 "Call the Emacs command `occur'.
13103 If CLEANUP is non-nil, remove the printout of the regular expression
13104 in the *Occur* buffer. This is useful if the regex is long and not useful
13105 to read."
13106 (occur regexp)
13107 (when cleanup
13108 (let ((cwin (selected-window)) win beg end)
13109 (when (setq win (get-buffer-window "*Occur*"))
13110 (select-window win))
13111 (goto-char (point-min))
13112 (when (re-search-forward "match[a-z]+" nil t)
13113 (setq beg (match-end 0))
13114 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13115 (setq end (1- (match-beginning 0)))))
13116 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13117 (goto-char (point-min))
13118 (select-window cwin))))
13120 ;;; The mark ring for links jumps
13122 (defvar org-mark-ring nil
13123 "Mark ring for positions before jumps in Org-mode.")
13124 (defvar org-mark-ring-last-goto nil
13125 "Last position in the mark ring used to go back.")
13126 ;; Fill and close the ring
13127 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13128 (loop for i from 1 to org-mark-ring-length do
13129 (push (make-marker) org-mark-ring))
13130 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13131 org-mark-ring)
13133 (defun org-mark-ring-push (&optional pos buffer)
13134 "Put the current position or POS into the mark ring and rotate it."
13135 (interactive)
13136 (setq pos (or pos (point)))
13137 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13138 (move-marker (car org-mark-ring)
13139 (or pos (point))
13140 (or buffer (current-buffer)))
13141 (message "%s"
13142 (substitute-command-keys
13143 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13145 (defun org-mark-ring-goto (&optional n)
13146 "Jump to the previous position in the mark ring.
13147 With prefix arg N, jump back that many stored positions. When
13148 called several times in succession, walk through the entire ring.
13149 Org-mode commands jumping to a different position in the current file,
13150 or to another Org-mode file, automatically push the old position
13151 onto the ring."
13152 (interactive "p")
13153 (let (p m)
13154 (if (eq last-command this-command)
13155 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13156 (setq p org-mark-ring))
13157 (setq org-mark-ring-last-goto p)
13158 (setq m (car p))
13159 (switch-to-buffer (marker-buffer m))
13160 (goto-char m)
13161 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13163 (defun org-remove-angle-brackets (s)
13164 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13165 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13167 (defun org-add-angle-brackets (s)
13168 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13169 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13172 ;;; Following specific links
13174 (defun org-follow-timestamp-link ()
13175 (cond
13176 ((org-at-date-range-p t)
13177 (let ((org-agenda-start-on-weekday)
13178 (t1 (match-string 1))
13179 (t2 (match-string 2)))
13180 (setq t1 (time-to-days (org-time-string-to-time t1))
13181 t2 (time-to-days (org-time-string-to-time t2)))
13182 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13183 ((org-at-timestamp-p t)
13184 (org-agenda-list nil (time-to-days (org-time-string-to-time
13185 (substring (match-string 1) 0 10)))
13187 (t (error "This should not happen"))))
13190 (defun org-follow-bbdb-link (name)
13191 "Follow a BBDB link to NAME."
13192 (require 'bbdb)
13193 (let ((inhibit-redisplay (not debug-on-error))
13194 (bbdb-electric-p nil))
13195 (catch 'exit
13196 ;; Exact match on name
13197 (bbdb-name (concat "\\`" name "\\'") nil)
13198 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13199 ;; Exact match on name
13200 (bbdb-company (concat "\\`" name "\\'") nil)
13201 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13202 ;; Partial match on name
13203 (bbdb-name name nil)
13204 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13205 ;; Partial match on company
13206 (bbdb-company name nil)
13207 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13208 ;; General match including network address and notes
13209 (bbdb name nil)
13210 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13211 (delete-window (get-buffer-window "*BBDB*"))
13212 (error "No matching BBDB record")))))
13214 (defun org-follow-info-link (name)
13215 "Follow an info file & node link to NAME."
13216 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13217 (string-match "\\(.*\\)" name))
13218 (progn
13219 (require 'info)
13220 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13221 (Info-find-node (match-string 1 name) (match-string 2 name))
13222 (Info-find-node (match-string 1 name) "Top")))
13223 (message "Could not open: %s" name)))
13225 (defun org-follow-gnus-link (&optional group article)
13226 "Follow a Gnus link to GROUP and ARTICLE."
13227 (require 'gnus)
13228 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13229 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13230 (cond ((and group article)
13231 (gnus-group-read-group 1 nil group)
13232 (gnus-summary-goto-article (string-to-number article) nil t))
13233 (group (gnus-group-jump-to-group group))))
13235 (defun org-follow-vm-link (&optional folder article readonly)
13236 "Follow a VM link to FOLDER and ARTICLE."
13237 (require 'vm)
13238 (setq article (org-add-angle-brackets article))
13239 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13240 ;; ange-ftp or efs or tramp access
13241 (let ((user (or (match-string 1 folder) (user-login-name)))
13242 (host (match-string 2 folder))
13243 (file (match-string 3 folder)))
13244 (cond
13245 ((featurep 'tramp)
13246 ;; use tramp to access the file
13247 (if (featurep 'xemacs)
13248 (setq folder (format "[%s@%s]%s" user host file))
13249 (setq folder (format "/%s@%s:%s" user host file))))
13251 ;; use ange-ftp or efs
13252 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13253 (setq folder (format "/%s@%s:%s" user host file))))))
13254 (when folder
13255 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13256 (sit-for 0.1)
13257 (when article
13258 (vm-select-folder-buffer)
13259 (widen)
13260 (let ((case-fold-search t))
13261 (goto-char (point-min))
13262 (if (not (re-search-forward
13263 (concat "^" "message-id: *" (regexp-quote article))))
13264 (error "Could not find the specified message in this folder"))
13265 (vm-isearch-update)
13266 (vm-isearch-narrow)
13267 (vm-beginning-of-message)
13268 (vm-summarize)))))
13270 (defun org-follow-wl-link (folder article)
13271 "Follow a Wanderlust link to FOLDER and ARTICLE."
13272 (if (and (string= folder "%")
13273 article
13274 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13275 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13276 ;; Thus, we recompose folder and article ids.
13277 (setq folder (format "%s#%s" folder (match-string 1 article))
13278 article (match-string 3 article)))
13279 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13280 (error "No such folder: %s" folder))
13281 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13282 (and article
13283 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13284 (wl-summary-redisplay)))
13286 (defun org-follow-rmail-link (folder article)
13287 "Follow an RMAIL link to FOLDER and ARTICLE."
13288 (setq article (org-add-angle-brackets article))
13289 (let (message-number)
13290 (save-excursion
13291 (save-window-excursion
13292 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13293 (setq message-number
13294 (save-restriction
13295 (widen)
13296 (goto-char (point-max))
13297 (if (re-search-backward
13298 (concat "^Message-ID:\\s-+" (regexp-quote
13299 (or article "")))
13300 nil t)
13301 (rmail-what-message))))))
13302 (if message-number
13303 (progn
13304 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13305 (rmail-show-message message-number)
13306 message-number)
13307 (error "Message not found"))))
13309 ;;; mh-e integration based on planner-mode
13310 (defun org-mhe-get-message-real-folder ()
13311 "Return the name of the current message real folder, so if you use
13312 sequences, it will now work."
13313 (save-excursion
13314 (let* ((folder
13315 (if (equal major-mode 'mh-folder-mode)
13316 mh-current-folder
13317 ;; Refer to the show buffer
13318 mh-show-folder-buffer))
13319 (end-index
13320 (if (boundp 'mh-index-folder)
13321 (min (length mh-index-folder) (length folder))))
13323 ;; a simple test on mh-index-data does not work, because
13324 ;; mh-index-data is always nil in a show buffer.
13325 (if (and (boundp 'mh-index-folder)
13326 (string= mh-index-folder (substring folder 0 end-index)))
13327 (if (equal major-mode 'mh-show-mode)
13328 (save-window-excursion
13329 (let (pop-up-frames)
13330 (when (buffer-live-p (get-buffer folder))
13331 (progn
13332 (pop-to-buffer folder)
13333 (org-mhe-get-message-folder-from-index)
13336 (org-mhe-get-message-folder-from-index)
13338 folder
13342 (defun org-mhe-get-message-folder-from-index ()
13343 "Returns the name of the message folder in a index folder buffer."
13344 (save-excursion
13345 (mh-index-previous-folder)
13346 (re-search-forward "^\\(+.*\\)$" nil t)
13347 (message "%s" (match-string 1))))
13349 (defun org-mhe-get-message-folder ()
13350 "Return the name of the current message folder. Be careful if you
13351 use sequences."
13352 (save-excursion
13353 (if (equal major-mode 'mh-folder-mode)
13354 mh-current-folder
13355 ;; Refer to the show buffer
13356 mh-show-folder-buffer)))
13358 (defun org-mhe-get-message-num ()
13359 "Return the number of the current message. Be careful if you
13360 use sequences."
13361 (save-excursion
13362 (if (equal major-mode 'mh-folder-mode)
13363 (mh-get-msg-num nil)
13364 ;; Refer to the show buffer
13365 (mh-show-buffer-message-number))))
13367 (defun org-mhe-get-header (header)
13368 "Return a header of the message in folder mode. This will create a
13369 show buffer for the corresponding message. If you have a more clever
13370 idea..."
13371 (let* ((folder (org-mhe-get-message-folder))
13372 (num (org-mhe-get-message-num))
13373 (buffer (get-buffer-create (concat "show-" folder)))
13374 (header-field))
13375 (with-current-buffer buffer
13376 (mh-display-msg num folder)
13377 (if (equal major-mode 'mh-folder-mode)
13378 (mh-header-display)
13379 (mh-show-header-display))
13380 (set-buffer buffer)
13381 (setq header-field (mh-get-header-field header))
13382 (if (equal major-mode 'mh-folder-mode)
13383 (mh-show)
13384 (mh-show-show))
13385 header-field)))
13387 (defun org-follow-mhe-link (folder article)
13388 "Follow an MHE link to FOLDER and ARTICLE.
13389 If ARTICLE is nil FOLDER is shown. If the configuration variable
13390 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13391 ARTICLE is searched in all folders. Indexed searches (swish++,
13392 namazu, and others supported by MH-E) will always search in all
13393 folders."
13394 (require 'mh-e)
13395 (require 'mh-search)
13396 (require 'mh-utils)
13397 (mh-find-path)
13398 (if (not article)
13399 (mh-visit-folder (mh-normalize-folder-name folder))
13400 (setq article (org-add-angle-brackets article))
13401 (mh-search-choose)
13402 (if (equal mh-searcher 'pick)
13403 (progn
13404 (mh-search folder (list "--message-id" article))
13405 (when (and org-mhe-search-all-folders
13406 (not (org-mhe-get-message-real-folder)))
13407 (kill-this-buffer)
13408 (mh-search "+" (list "--message-id" article))))
13409 (mh-search "+" article))
13410 (if (org-mhe-get-message-real-folder)
13411 (mh-show-msg 1)
13412 (kill-this-buffer)
13413 (error "Message not found"))))
13415 ;;; BibTeX links
13417 ;; Use the custom search meachnism to construct and use search strings for
13418 ;; file links to BibTeX database entries.
13420 (defun org-create-file-search-in-bibtex ()
13421 "Create the search string and description for a BibTeX database entry."
13422 (when (eq major-mode 'bibtex-mode)
13423 ;; yes, we want to construct this search string.
13424 ;; Make a good description for this entry, using names, year and the title
13425 ;; Put it into the `description' variable which is dynamically scoped.
13426 (let ((bibtex-autokey-names 1)
13427 (bibtex-autokey-names-stretch 1)
13428 (bibtex-autokey-name-case-convert-function 'identity)
13429 (bibtex-autokey-name-separator " & ")
13430 (bibtex-autokey-additional-names " et al.")
13431 (bibtex-autokey-year-length 4)
13432 (bibtex-autokey-name-year-separator " ")
13433 (bibtex-autokey-titlewords 3)
13434 (bibtex-autokey-titleword-separator " ")
13435 (bibtex-autokey-titleword-case-convert-function 'identity)
13436 (bibtex-autokey-titleword-length 'infty)
13437 (bibtex-autokey-year-title-separator ": "))
13438 (setq description (bibtex-generate-autokey)))
13439 ;; Now parse the entry, get the key and return it.
13440 (save-excursion
13441 (bibtex-beginning-of-entry)
13442 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13444 (defun org-execute-file-search-in-bibtex (s)
13445 "Find the link search string S as a key for a database entry."
13446 (when (eq major-mode 'bibtex-mode)
13447 ;; Yes, we want to do the search in this file.
13448 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13449 (goto-char (point-min))
13450 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13451 (regexp-quote s) "[ \t\n]*,") nil t)
13452 (goto-char (match-beginning 0)))
13453 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13454 ;; Use double prefix to indicate that any web link should be browsed
13455 (let ((b (current-buffer)) (p (point)))
13456 ;; Restore the window configuration because we just use the web link
13457 (set-window-configuration org-window-config-before-follow-link)
13458 (save-excursion (set-buffer b) (goto-char p)
13459 (bibtex-url)))
13460 (recenter 0)) ; Move entry start to beginning of window
13461 ;; return t to indicate that the search is done.
13464 ;; Finally add the functions to the right hooks.
13465 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13466 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13468 ;; end of Bibtex link setup
13470 ;;; Following file links
13472 (defun org-open-file (path &optional in-emacs line search)
13473 "Open the file at PATH.
13474 First, this expands any special file name abbreviations. Then the
13475 configuration variable `org-file-apps' is checked if it contains an
13476 entry for this file type, and if yes, the corresponding command is launched.
13477 If no application is found, Emacs simply visits the file.
13478 With optional argument IN-EMACS, Emacs will visit the file.
13479 Optional LINE specifies a line to go to, optional SEARCH a string to
13480 search for. If LINE or SEARCH is given, the file will always be
13481 opened in Emacs.
13482 If the file does not exist, an error is thrown."
13483 (setq in-emacs (or in-emacs line search))
13484 (let* ((file (if (equal path "")
13485 buffer-file-name
13486 (substitute-in-file-name (expand-file-name path))))
13487 (apps (append org-file-apps (org-default-apps)))
13488 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13489 (dirp (if remp nil (file-directory-p file)))
13490 (dfile (downcase file))
13491 (old-buffer (current-buffer))
13492 (old-pos (point))
13493 (old-mode major-mode)
13494 ext cmd)
13495 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13496 (setq ext (match-string 1 dfile))
13497 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13498 (setq ext (match-string 1 dfile))))
13499 (if in-emacs
13500 (setq cmd 'emacs)
13501 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13502 (and dirp (cdr (assoc 'directory apps)))
13503 (cdr (assoc ext apps))
13504 (cdr (assoc t apps)))))
13505 (when (eq cmd 'mailcap)
13506 (require 'mailcap)
13507 (mailcap-parse-mailcaps)
13508 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13509 (command (mailcap-mime-info mime-type)))
13510 (if (stringp command)
13511 (setq cmd command)
13512 (setq cmd 'emacs))))
13513 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13514 (not (file-exists-p file))
13515 (not org-open-non-existing-files))
13516 (error "No such file: %s" file))
13517 (cond
13518 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13519 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13520 (while (string-match "['\"]%s['\"]" cmd)
13521 (setq cmd (replace-match "%s" t t cmd)))
13522 (while (string-match "%s" cmd)
13523 (setq cmd (replace-match
13524 (save-match-data (shell-quote-argument file))
13525 t t cmd)))
13526 (save-window-excursion
13527 (start-process-shell-command cmd nil cmd)))
13528 ((or (stringp cmd)
13529 (eq cmd 'emacs))
13530 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13531 (widen)
13532 (if line (goto-line line)
13533 (if search (org-link-search search))))
13534 ((consp cmd)
13535 (eval cmd))
13536 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13537 (and (org-mode-p) (eq old-mode 'org-mode)
13538 (or (not (equal old-buffer (current-buffer)))
13539 (not (equal old-pos (point))))
13540 (org-mark-ring-push old-pos old-buffer))))
13542 (defun org-default-apps ()
13543 "Return the default applications for this operating system."
13544 (cond
13545 ((eq system-type 'darwin)
13546 org-file-apps-defaults-macosx)
13547 ((eq system-type 'windows-nt)
13548 org-file-apps-defaults-windowsnt)
13549 (t org-file-apps-defaults-gnu)))
13551 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13552 (defun org-file-remote-p (file)
13553 "Test whether FILE specifies a location on a remote system.
13554 Return non-nil if the location is indeed remote.
13556 For example, the filename \"/user@host:/foo\" specifies a location
13557 on the system \"/user@host:\"."
13558 (cond ((fboundp 'file-remote-p)
13559 (file-remote-p file))
13560 ((fboundp 'tramp-handle-file-remote-p)
13561 (tramp-handle-file-remote-p file))
13562 ((and (boundp 'ange-ftp-name-format)
13563 (string-match (car ange-ftp-name-format) file))
13565 (t nil)))
13568 ;;;; Hooks for remember.el, and refiling
13570 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13571 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13573 ;;;###autoload
13574 (defun org-remember-insinuate ()
13575 "Setup remember.el for use wiht Org-mode."
13576 (require 'remember)
13577 (setq remember-annotation-functions '(org-remember-annotation))
13578 (setq remember-handler-functions '(org-remember-handler))
13579 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13581 ;;;###autoload
13582 (defun org-remember-annotation ()
13583 "Return a link to the current location as an annotation for remember.el.
13584 If you are using Org-mode files as target for data storage with
13585 remember.el, then the annotations should include a link compatible with the
13586 conventions in Org-mode. This function returns such a link."
13587 (org-store-link nil))
13589 (defconst org-remember-help
13590 "Select a destination location for the note.
13591 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13592 RET on headline -> Store as sublevel entry to current headline
13593 RET at beg-of-buf -> Append to file as level 2 headline
13594 <left>/<right> -> before/after current headline, same headings level")
13596 (defvar org-remember-previous-location nil)
13597 (defvar org-force-remember-template-char) ;; dynamically scoped
13599 ;; Save the major mode of the buffer we called remember from
13600 (defvar org-select-template-temp-major-mode nil)
13602 ;; Temporary store the buffer where remember was called from
13603 (defvar org-select-template-original-buffer nil)
13605 (defun org-select-remember-template (&optional use-char)
13606 (when org-remember-templates
13607 (let* ((pre-selected-templates
13608 (mapcar
13609 (lambda (tpl)
13610 (let ((ctxt (nth 5 tpl))
13611 (mode org-select-template-temp-major-mode)
13612 (buf org-select-template-original-buffer))
13613 (if (or (and (functionp ctxt)
13614 (save-excursion
13615 (set-buffer buf)
13616 ;; Protect the user-defined function from error
13617 (condition-case nil (funcall ctxt) (error nil))))
13618 (and ctxt (listp ctxt)
13619 (delq nil (mapcar (lambda(x) (eq mode x)) ctxt))))
13620 tpl)))
13621 org-remember-templates))
13622 ;; If no template at this point, add the default templates:
13623 (pre-selected-templates1
13624 (if (not (delq nil pre-selected-templates))
13625 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13626 org-remember-templates)
13627 pre-selected-templates))
13628 ;; Then unconditionnally add template for any contexts
13629 (pre-selected-templates2
13630 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13631 org-remember-templates)
13632 (delq nil pre-selected-templates1)))
13633 (templates (mapcar (lambda (x)
13634 (if (stringp (car x))
13635 (append (list (nth 1 x) (car x)) (cddr x))
13636 (append (list (car x) "") (cdr x))))
13637 (delq nil pre-selected-templates2)))
13638 (char (or use-char
13639 (cond
13640 ((= (length templates) 1)
13641 (caar templates))
13642 ((and (boundp 'org-force-remember-template-char)
13643 org-force-remember-template-char)
13644 (if (stringp org-force-remember-template-char)
13645 (string-to-char org-force-remember-template-char)
13646 org-force-remember-template-char))
13648 (message "Select template: %s"
13649 (mapconcat
13650 (lambda (x)
13651 (cond
13652 ((not (string-match "\\S-" (nth 1 x)))
13653 (format "[%c]" (car x)))
13654 ((equal (downcase (car x))
13655 (downcase (aref (nth 1 x) 0)))
13656 (format "[%c]%s" (car x)
13657 (substring (nth 1 x) 1)))
13658 (t (format "[%c]%s" (car x) (nth 1 x)))))
13659 templates " "))
13660 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13661 (when (equal char0 ?\C-g)
13662 (jump-to-register remember-register)
13663 (kill-buffer remember-buffer))
13664 char0))))))
13665 (cddr (assoc char templates)))))
13667 (defvar x-last-selected-text)
13668 (defvar x-last-selected-text-primary)
13670 ;;;###autoload
13671 (defun org-remember-apply-template (&optional use-char skip-interactive)
13672 "Initialize *remember* buffer with template, invoke `org-mode'.
13673 This function should be placed into `remember-mode-hook' and in fact requires
13674 to be run from that hook to function properly."
13675 (if org-remember-templates
13676 (let* ((entry (org-select-remember-template use-char))
13677 (tpl (car entry))
13678 (plist-p (if org-store-link-plist t nil))
13679 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13680 (string-match "\\S-" (nth 1 entry)))
13681 (nth 1 entry)
13682 org-default-notes-file))
13683 (headline (nth 2 entry))
13684 (v-c (or (and (eq window-system 'x)
13685 (fboundp 'x-cut-buffer-or-selection-value)
13686 (x-cut-buffer-or-selection-value))
13687 (org-bound-and-true-p x-last-selected-text)
13688 (org-bound-and-true-p x-last-selected-text-primary)
13689 (and (> (length kill-ring) 0) (current-kill 0))))
13690 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13691 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13692 (v-u (concat "[" (substring v-t 1 -1) "]"))
13693 (v-U (concat "[" (substring v-T 1 -1) "]"))
13694 ;; `initial' and `annotation' are bound in `remember'
13695 (v-i (if (boundp 'initial) initial))
13696 (v-a (if (and (boundp 'annotation) annotation)
13697 (if (equal annotation "[[]]") "" annotation)
13698 ""))
13699 (v-A (if (and v-a
13700 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13701 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13702 v-a))
13703 (v-n user-full-name)
13704 (org-startup-folded nil)
13705 org-time-was-given org-end-time-was-given x
13706 prompt completions char time pos default histvar)
13707 (setq org-store-link-plist
13708 (append (list :annotation v-a :initial v-i)
13709 org-store-link-plist))
13710 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13711 (erase-buffer)
13712 (insert (substitute-command-keys
13713 (format
13714 "## Filing location: Select interactively, default, or last used:
13715 ## %s to select file and header location interactively.
13716 ## %s \"%s\" -> \"* %s\"
13717 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13718 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13719 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13720 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13721 (abbreviate-file-name (or file org-default-notes-file))
13722 (or headline "")
13723 (or (car org-remember-previous-location) "???")
13724 (or (cdr org-remember-previous-location) "???"))))
13725 (insert tpl) (goto-char (point-min))
13726 ;; Simple %-escapes
13727 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13728 (when (and initial (equal (match-string 0) "%i"))
13729 (save-match-data
13730 (let* ((lead (buffer-substring
13731 (point-at-bol) (match-beginning 0))))
13732 (setq v-i (mapconcat 'identity
13733 (org-split-string initial "\n")
13734 (concat "\n" lead))))))
13735 (replace-match
13736 (or (eval (intern (concat "v-" (match-string 1)))) "")
13737 t t))
13739 ;; %[] Insert contents of a file.
13740 (goto-char (point-min))
13741 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13742 (let ((start (match-beginning 0))
13743 (end (match-end 0))
13744 (filename (expand-file-name (match-string 1))))
13745 (goto-char start)
13746 (delete-region start end)
13747 (condition-case error
13748 (insert-file-contents filename)
13749 (error (insert (format "%%![Couldn't insert %s: %s]"
13750 filename error))))))
13751 ;; %() embedded elisp
13752 (goto-char (point-min))
13753 (while (re-search-forward "%\\((.+)\\)" nil t)
13754 (goto-char (match-beginning 0))
13755 (let ((template-start (point)))
13756 (forward-char 1)
13757 (let ((result
13758 (condition-case error
13759 (eval (read (current-buffer)))
13760 (error (format "%%![Error: %s]" error)))))
13761 (delete-region template-start (point))
13762 (insert result))))
13764 ;; From the property list
13765 (when plist-p
13766 (goto-char (point-min))
13767 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13768 (and (setq x (or (plist-get org-store-link-plist
13769 (intern (match-string 1))) ""))
13770 (replace-match x t t))))
13772 ;; Turn on org-mode in the remember buffer, set local variables
13773 (org-mode)
13774 (org-set-local 'org-finish-function 'org-remember-finalize)
13775 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13776 (org-set-local 'org-default-notes-file file))
13777 (if (and headline (stringp headline) (string-match "\\S-" headline))
13778 (org-set-local 'org-remember-default-headline headline))
13779 ;; Interactive template entries
13780 (goto-char (point-min))
13781 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13782 (setq char (if (match-end 3) (match-string 3))
13783 prompt (if (match-end 2) (match-string 2)))
13784 (goto-char (match-beginning 0))
13785 (replace-match "")
13786 (setq completions nil default nil)
13787 (when prompt
13788 (setq completions (org-split-string prompt "|")
13789 prompt (pop completions)
13790 default (car completions)
13791 histvar (intern (concat
13792 "org-remember-template-prompt-history::"
13793 (or prompt "")))
13794 completions (mapcar 'list completions)))
13795 (cond
13796 ((member char '("G" "g"))
13797 (let* ((org-last-tags-completion-table
13798 (org-global-tags-completion-table
13799 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13800 (org-add-colon-after-tag-completion t)
13801 (ins (completing-read
13802 (if prompt (concat prompt ": ") "Tags: ")
13803 'org-tags-completion-function nil nil nil
13804 'org-tags-history)))
13805 (setq ins (mapconcat 'identity
13806 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13807 ":"))
13808 (when (string-match "\\S-" ins)
13809 (or (equal (char-before) ?:) (insert ":"))
13810 (insert ins)
13811 (or (equal (char-after) ?:) (insert ":")))))
13812 (char
13813 (setq org-time-was-given (equal (upcase char) char))
13814 (setq time (org-read-date (equal (upcase char) "U") t nil
13815 prompt))
13816 (org-insert-time-stamp time org-time-was-given
13817 (member char '("u" "U"))
13818 nil nil (list org-end-time-was-given)))
13820 (insert (org-completing-read
13821 (concat (if prompt prompt "Enter string")
13822 (if default (concat " [" default "]"))
13823 ": ")
13824 completions nil nil nil histvar default)))))
13825 (goto-char (point-min))
13826 (if (re-search-forward "%\\?" nil t)
13827 (replace-match "")
13828 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13829 (org-mode)
13830 (org-set-local 'org-finish-function 'org-remember-finalize))
13831 (when (save-excursion
13832 (goto-char (point-min))
13833 (re-search-forward "%!" nil t))
13834 (replace-match "")
13835 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13837 (defun org-remember-finish-immediately ()
13838 "File remember note immediately.
13839 This should be run in `post-command-hook' and will remove itself
13840 from that hook."
13841 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13842 (when org-finish-function
13843 (funcall org-finish-function)))
13845 (defvar org-clock-marker) ; Defined below
13846 (defun org-remember-finalize ()
13847 "Finalize the remember process."
13848 (unless (fboundp 'remember-finalize)
13849 (defalias 'remember-finalize 'remember-buffer))
13850 (when (and org-clock-marker
13851 (equal (marker-buffer org-clock-marker) (current-buffer)))
13852 ;; FIXME: test this, this is w/o notetaking!
13853 (let (org-log-note-clock-out) (org-clock-out)))
13854 (when buffer-file-name
13855 (save-buffer)
13856 (setq buffer-file-name nil))
13857 (remember-finalize))
13859 ;;;###autoload
13860 (defun org-remember (&optional goto org-force-remember-template-char)
13861 "Call `remember'. If this is already a remember buffer, re-apply template.
13862 If there is an active region, make sure remember uses it as initial content
13863 of the remember buffer.
13865 When called interactively with a `C-u' prefix argument GOTO, don't remember
13866 anything, just go to the file/headline where the selected template usually
13867 stores its notes. With a double prefix arg `C-u C-u', go to the last
13868 note stored by remember.
13870 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13871 associated with a template in `org-remember-templates'."
13872 (interactive "P")
13873 (cond
13874 ((equal goto '(4)) (org-go-to-remember-target))
13875 ((equal goto '(16)) (org-remember-goto-last-stored))
13877 ;; set temporary variables that will be needed in
13878 ;; `org-select-remember-template'
13879 (setq org-select-template-temp-major-mode major-mode)
13880 (setq org-select-template-original-buffer (current-buffer))
13881 (if (memq org-finish-function '(remember-buffer remember-finalize))
13882 (progn
13883 (when (< (length org-remember-templates) 2)
13884 (error "No other template available"))
13885 (erase-buffer)
13886 (let ((annotation (plist-get org-store-link-plist :annotation))
13887 (initial (plist-get org-store-link-plist :initial)))
13888 (org-remember-apply-template))
13889 (message "Press C-c C-c to remember data"))
13890 (if (org-region-active-p)
13891 (remember (buffer-substring (point) (mark)))
13892 (call-interactively 'remember))))))
13894 (defun org-remember-goto-last-stored ()
13895 "Go to the location where the last remember note was stored."
13896 (interactive)
13897 (bookmark-jump "org-remember-last-stored")
13898 (message "This is the last note stored by remember"))
13900 (defun org-go-to-remember-target (&optional template-key)
13901 "Go to the target location of a remember template.
13902 The user is queried for the template."
13903 (interactive)
13904 (let* (org-select-template-temp-major-mode
13905 (entry (org-select-remember-template template-key))
13906 (file (nth 1 entry))
13907 (heading (nth 2 entry))
13908 visiting)
13909 (unless (and file (stringp file) (string-match "\\S-" file))
13910 (setq file org-default-notes-file))
13911 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13912 (setq heading org-remember-default-headline))
13913 (setq visiting (org-find-base-buffer-visiting file))
13914 (if (not visiting) (find-file-noselect file))
13915 (switch-to-buffer (or visiting (get-file-buffer file)))
13916 (widen)
13917 (goto-char (point-min))
13918 (if (re-search-forward
13919 (concat "^\\*+[ \t]+" (regexp-quote heading)
13920 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
13921 nil t)
13922 (goto-char (match-beginning 0))
13923 (error "Target headline not found: %s" heading))))
13925 (defvar org-note-abort nil) ; dynamically scoped
13927 ;;;###autoload
13928 (defun org-remember-handler ()
13929 "Store stuff from remember.el into an org file.
13930 First prompts for an org file. If the user just presses return, the value
13931 of `org-default-notes-file' is used.
13932 Then the command offers the headings tree of the selected file in order to
13933 file the text at a specific location.
13934 You can either immediately press RET to get the note appended to the
13935 file, or you can use vertical cursor motion and visibility cycling (TAB) to
13936 find a better place. Then press RET or <left> or <right> in insert the note.
13938 Key Cursor position Note gets inserted
13939 -----------------------------------------------------------------------------
13940 RET buffer-start as level 1 heading at end of file
13941 RET on headline as sublevel of the heading at cursor
13942 RET no heading at cursor position, level taken from context.
13943 Or use prefix arg to specify level manually.
13944 <left> on headline as same level, before current heading
13945 <right> on headline as same level, after current heading
13947 So the fastest way to store the note is to press RET RET to append it to
13948 the default file. This way your current train of thought is not
13949 interrupted, in accordance with the principles of remember.el.
13950 You can also get the fast execution without prompting by using
13951 C-u C-c C-c to exit the remember buffer. See also the variable
13952 `org-remember-store-without-prompt'.
13954 Before being stored away, the function ensures that the text has a
13955 headline, i.e. a first line that starts with a \"*\". If not, a headline
13956 is constructed from the current date and some additional data.
13958 If the variable `org-adapt-indentation' is non-nil, the entire text is
13959 also indented so that it starts in the same column as the headline
13960 \(i.e. after the stars).
13962 See also the variable `org-reverse-note-order'."
13963 (goto-char (point-min))
13964 (while (looking-at "^[ \t]*\n\\|^##.*\n")
13965 (replace-match ""))
13966 (goto-char (point-max))
13967 (beginning-of-line 1)
13968 (while (looking-at "[ \t]*$\\|##.*")
13969 (delete-region (1- (point)) (point-max))
13970 (beginning-of-line 1))
13971 (catch 'quit
13972 (if org-note-abort (throw 'quit nil))
13973 (let* ((txt (buffer-substring (point-min) (point-max)))
13974 (fastp (org-xor (equal current-prefix-arg '(4))
13975 org-remember-store-without-prompt))
13976 (file (cond
13977 (fastp org-default-notes-file)
13978 ((and (eq org-remember-interactive-interface 'refile)
13979 org-refile-targets)
13980 org-default-notes-file)
13981 ((not (and (equal current-prefix-arg '(16))
13982 org-remember-previous-location))
13983 (org-get-org-file))))
13984 (heading org-remember-default-headline)
13985 (visiting (and file (org-find-base-buffer-visiting file)))
13986 (org-startup-folded nil)
13987 (org-startup-align-all-tables nil)
13988 (org-goto-start-pos 1)
13989 spos exitcmd level indent reversed)
13990 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
13991 (setq file (car org-remember-previous-location)
13992 heading (cdr org-remember-previous-location)
13993 fastp t))
13994 (setq current-prefix-arg nil)
13995 (if (string-match "[ \t\n]+\\'" txt)
13996 (setq txt (replace-match "" t t txt)))
13997 ;; Modify text so that it becomes a nice subtree which can be inserted
13998 ;; into an org tree.
13999 (let* ((lines (split-string txt "\n"))
14000 first)
14001 (setq first (car lines) lines (cdr lines))
14002 (if (string-match "^\\*+ " first)
14003 ;; Is already a headline
14004 (setq indent nil)
14005 ;; We need to add a headline: Use time and first buffer line
14006 (setq lines (cons first lines)
14007 first (concat "* " (current-time-string)
14008 " (" (remember-buffer-desc) ")")
14009 indent " "))
14010 (if (and org-adapt-indentation indent)
14011 (setq lines (mapcar
14012 (lambda (x)
14013 (if (string-match "\\S-" x)
14014 (concat indent x) x))
14015 lines)))
14016 (setq txt (concat first "\n"
14017 (mapconcat 'identity lines "\n"))))
14018 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14019 (setq txt (replace-match "\n\n" t t txt))
14020 (if (string-match "[ \t\n]*\\'" txt)
14021 (setq txt (replace-match "\n" t t txt))))
14022 ;; Put the modified text back into the remember buffer, for refile.
14023 (erase-buffer)
14024 (insert txt)
14025 (goto-char (point-min))
14026 (when (and (eq org-remember-interactive-interface 'refile)
14027 (not fastp))
14028 (org-refile nil (or visiting (find-file-noselect file)))
14029 (throw 'quit t))
14030 ;; Find the file
14031 (if (not visiting) (find-file-noselect file))
14032 (with-current-buffer (or visiting (get-file-buffer file))
14033 (unless (org-mode-p)
14034 (error "Target files for remember notes must be in Org-mode"))
14035 (save-excursion
14036 (save-restriction
14037 (widen)
14038 (and (goto-char (point-min))
14039 (not (re-search-forward "^\\* " nil t))
14040 (insert "\n* " (or heading "Notes") "\n"))
14041 (setq reversed (org-notes-order-reversed-p))
14043 ;; Find the default location
14044 (when (and heading (stringp heading) (string-match "\\S-" heading))
14045 (goto-char (point-min))
14046 (if (re-search-forward
14047 (concat "^\\*+[ \t]+" (regexp-quote heading)
14048 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14049 nil t)
14050 (setq org-goto-start-pos (match-beginning 0))
14051 (when fastp
14052 (goto-char (point-max))
14053 (unless (bolp) (newline))
14054 (insert "* " heading "\n")
14055 (setq org-goto-start-pos (point-at-bol 0)))))
14057 ;; Ask the User for a location, using the appropriate interface
14058 (cond
14059 (fastp (setq spos org-goto-start-pos
14060 exitcmd 'return))
14061 ((eq org-remember-interactive-interface 'outline)
14062 (setq spos (org-get-location (current-buffer)
14063 org-remember-help)
14064 exitcmd (cdr spos)
14065 spos (car spos)))
14066 ((eq org-remember-interactive-interface 'outline-path-completion)
14067 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14068 (org-refile-use-outline-path t))
14069 (setq spos (org-refile-get-location "Heading: ")
14070 exitcmd 'return
14071 spos (nth 3 spos))))
14072 (t (error "this should not hapen")))
14073 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14074 ; not handle this note
14075 (goto-char spos)
14076 (cond ((org-on-heading-p t)
14077 (org-back-to-heading t)
14078 (setq level (funcall outline-level))
14079 (cond
14080 ((eq exitcmd 'return)
14081 ;; sublevel of current
14082 (setq org-remember-previous-location
14083 (cons (abbreviate-file-name file)
14084 (org-get-heading 'notags)))
14085 (if reversed
14086 (outline-next-heading)
14087 (org-end-of-subtree t)
14088 (if (not (bolp))
14089 (if (looking-at "[ \t]*\n")
14090 (beginning-of-line 2)
14091 (end-of-line 1)
14092 (insert "\n"))))
14093 (bookmark-set "org-remember-last-stored")
14094 (org-paste-subtree (org-get-legal-level level 1) txt))
14095 ((eq exitcmd 'left)
14096 ;; before current
14097 (bookmark-set "org-remember-last-stored")
14098 (org-paste-subtree level txt))
14099 ((eq exitcmd 'right)
14100 ;; after current
14101 (org-end-of-subtree t)
14102 (bookmark-set "org-remember-last-stored")
14103 (org-paste-subtree level txt))
14104 (t (error "This should not happen"))))
14106 ((and (bobp) (not reversed))
14107 ;; Put it at the end, one level below level 1
14108 (save-restriction
14109 (widen)
14110 (goto-char (point-max))
14111 (if (not (bolp)) (newline))
14112 (bookmark-set "org-remember-last-stored")
14113 (org-paste-subtree (org-get-legal-level 1 1) txt)))
14115 ((and (bobp) reversed)
14116 ;; Put it at the start, as level 1
14117 (save-restriction
14118 (widen)
14119 (goto-char (point-min))
14120 (re-search-forward "^\\*+ " nil t)
14121 (beginning-of-line 1)
14122 (bookmark-set "org-remember-last-stored")
14123 (org-paste-subtree 1 txt)))
14125 ;; Put it right there, with automatic level determined by
14126 ;; org-paste-subtree or from prefix arg
14127 (bookmark-set "org-remember-last-stored")
14128 (org-paste-subtree
14129 (if (numberp current-prefix-arg) current-prefix-arg)
14130 txt)))
14131 (when remember-save-after-remembering
14132 (save-buffer)
14133 (if (not visiting) (kill-buffer (current-buffer)))))))))
14135 t) ;; return t to indicate that we took care of this note.
14137 (defun org-get-org-file ()
14138 "Read a filename, with default directory `org-directory'."
14139 (let ((default (or org-default-notes-file remember-data-file)))
14140 (read-file-name (format "File name [%s]: " default)
14141 (file-name-as-directory org-directory)
14142 default)))
14144 (defun org-notes-order-reversed-p ()
14145 "Check if the current file should receive notes in reversed order."
14146 (cond
14147 ((not org-reverse-note-order) nil)
14148 ((eq t org-reverse-note-order) t)
14149 ((not (listp org-reverse-note-order)) nil)
14150 (t (catch 'exit
14151 (let ((all org-reverse-note-order)
14152 entry)
14153 (while (setq entry (pop all))
14154 (if (string-match (car entry) buffer-file-name)
14155 (throw 'exit (cdr entry))))
14156 nil)))))
14158 ;;; Refiling
14160 (defvar org-refile-target-table nil
14161 "The list of refile targets, created by `org-refile'.")
14163 (defvar org-agenda-new-buffers nil
14164 "Buffers created to visit agenda files.")
14166 (defun org-get-refile-targets (&optional default-buffer)
14167 "Produce a table with refile targets."
14168 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14169 targets txt re files f desc descre)
14170 (with-current-buffer (or default-buffer (current-buffer))
14171 (while (setq entry (pop entries))
14172 (setq files (car entry) desc (cdr entry))
14173 (cond
14174 ((null files) (setq files (list (current-buffer))))
14175 ((eq files 'org-agenda-files)
14176 (setq files (org-agenda-files 'unrestricted)))
14177 ((and (symbolp files) (fboundp files))
14178 (setq files (funcall files)))
14179 ((and (symbolp files) (boundp files))
14180 (setq files (symbol-value files))))
14181 (if (stringp files) (setq files (list files)))
14182 (cond
14183 ((eq (car desc) :tag)
14184 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14185 ((eq (car desc) :todo)
14186 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14187 ((eq (car desc) :regexp)
14188 (setq descre (cdr desc)))
14189 ((eq (car desc) :level)
14190 (setq descre (concat "^\\*\\{" (number-to-string
14191 (if org-odd-levels-only
14192 (1- (* 2 (cdr desc)))
14193 (cdr desc)))
14194 "\\}[ \t]")))
14195 ((eq (car desc) :maxlevel)
14196 (setq descre (concat "^\\*\\{1," (number-to-string
14197 (if org-odd-levels-only
14198 (1- (* 2 (cdr desc)))
14199 (cdr desc)))
14200 "\\}[ \t]")))
14201 (t (error "Bad refiling target description %s" desc)))
14202 (while (setq f (pop files))
14203 (save-excursion
14204 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14205 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14206 (save-excursion
14207 (save-restriction
14208 (widen)
14209 (goto-char (point-min))
14210 (while (re-search-forward descre nil t)
14211 (goto-char (point-at-bol))
14212 (when (looking-at org-complex-heading-regexp)
14213 (setq txt (match-string 4)
14214 re (concat "^" (regexp-quote
14215 (buffer-substring (match-beginning 1)
14216 (match-end 4)))))
14217 (if (match-end 5) (setq re (concat re "[ \t]+"
14218 (regexp-quote
14219 (match-string 5)))))
14220 (setq re (concat re "[ \t]*$"))
14221 (when org-refile-use-outline-path
14222 (setq txt (mapconcat 'identity
14223 (append
14224 (if (eq org-refile-use-outline-path 'file)
14225 (list (file-name-nondirectory
14226 (buffer-file-name (buffer-base-buffer))))
14227 (if (eq org-refile-use-outline-path 'full-file-path)
14228 (list (buffer-file-name (buffer-base-buffer)))))
14229 (org-get-outline-path)
14230 (list txt))
14231 "/")))
14232 (push (list txt f re (point)) targets))
14233 (goto-char (point-at-eol))))))))
14234 (nreverse targets))))
14236 (defun org-get-outline-path ()
14237 "Return the outline path to the current entry, as a list."
14238 (let (rtn)
14239 (save-excursion
14240 (while (org-up-heading-safe)
14241 (when (looking-at org-complex-heading-regexp)
14242 (push (org-match-string-no-properties 4) rtn)))
14243 rtn)))
14245 (defvar org-refile-history nil
14246 "History for refiling operations.")
14248 (defun org-refile (&optional goto default-buffer)
14249 "Move the entry at point to another heading.
14250 The list of target headings is compiled using the information in
14251 `org-refile-targets', which see. This list is created upon first use, and
14252 you can update it by calling this command with a double prefix (`C-u C-u').
14253 FIXME: Can we find a better way of updating?
14255 At the target location, the entry is filed as a subitem of the target heading.
14256 Depending on `org-reverse-note-order', the new subitem will either be the
14257 first of the last subitem.
14259 With prefix arg GOTO, the command will only visit the target location,
14260 not actually move anything.
14261 With a double prefix `C-c C-c', go to the location where the last refiling
14262 operation has put the subtree.
14264 With a double prefix argument, the command can be used to jump to any
14265 heading in the current buffer."
14266 (interactive "P")
14267 (let* ((cbuf (current-buffer))
14268 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14269 pos it nbuf file re level reversed)
14270 (if (equal goto '(16))
14271 (org-refile-goto-last-stored)
14272 (when (setq it (org-refile-get-location
14273 (if goto "Goto: " "Refile to: ") default-buffer))
14274 (setq file (nth 1 it)
14275 re (nth 2 it)
14276 pos (nth 3 it))
14277 (setq nbuf (or (find-buffer-visiting file)
14278 (find-file-noselect file)))
14279 (if goto
14280 (progn
14281 (switch-to-buffer nbuf)
14282 (goto-char pos)
14283 (org-show-context 'org-goto))
14284 (org-copy-special)
14285 (save-excursion
14286 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14287 (find-file-noselect file))))
14288 (setq reversed (org-notes-order-reversed-p))
14289 (save-excursion
14290 (save-restriction
14291 (widen)
14292 (goto-char pos)
14293 (looking-at outline-regexp)
14294 (setq level (org-get-legal-level (funcall outline-level) 1))
14295 (goto-char
14296 (if reversed
14297 (outline-next-heading)
14298 (or (save-excursion (outline-get-next-sibling))
14299 (org-end-of-subtree t t)
14300 (point-max))))
14301 (bookmark-set "org-refile-last-stored")
14302 (org-paste-subtree level))))
14303 (org-cut-special)
14304 (message "Entry refiled to \"%s\"" (car it)))))))
14306 (defun org-refile-goto-last-stored ()
14307 "Go to the location where the last refile was stored."
14308 (interactive)
14309 (bookmark-jump "org-refile-last-stored")
14310 (message "This is the location of the last refile"))
14312 (defun org-refile-get-location (&optional prompt default-buffer)
14313 "Prompt the user for a refile location, using PROMPT."
14314 (let ((org-refile-targets org-refile-targets)
14315 (org-refile-use-outline-path org-refile-use-outline-path))
14316 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14317 (unless org-refile-target-table
14318 (error "No refile targets"))
14319 (let* ((cbuf (current-buffer))
14320 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14321 (fname (and filename (file-truename filename)))
14322 (tbl (mapcar
14323 (lambda (x)
14324 (if (not (equal fname (file-truename (nth 1 x))))
14325 (cons (concat (car x) " (" (file-name-nondirectory
14326 (nth 1 x)) ")")
14327 (cdr x))
14329 org-refile-target-table))
14330 (completion-ignore-case t))
14331 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14332 tbl)))
14334 ;;;; Dynamic blocks
14336 (defun org-find-dblock (name)
14337 "Find the first dynamic block with name NAME in the buffer.
14338 If not found, stay at current position and return nil."
14339 (let (pos)
14340 (save-excursion
14341 (goto-char (point-min))
14342 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14343 nil t)
14344 (match-beginning 0))))
14345 (if pos (goto-char pos))
14346 pos))
14348 (defconst org-dblock-start-re
14349 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14350 "Matches the startline of a dynamic block, with parameters.")
14352 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14353 "Matches the end of a dyhamic block.")
14355 (defun org-create-dblock (plist)
14356 "Create a dynamic block section, with parameters taken from PLIST.
14357 PLIST must containe a :name entry which is used as name of the block."
14358 (unless (bolp) (newline))
14359 (let ((name (plist-get plist :name)))
14360 (insert "#+BEGIN: " name)
14361 (while plist
14362 (if (eq (car plist) :name)
14363 (setq plist (cddr plist))
14364 (insert " " (prin1-to-string (pop plist)))))
14365 (insert "\n\n#+END:\n")
14366 (beginning-of-line -2)))
14368 (defun org-prepare-dblock ()
14369 "Prepare dynamic block for refresh.
14370 This empties the block, puts the cursor at the insert position and returns
14371 the property list including an extra property :name with the block name."
14372 (unless (looking-at org-dblock-start-re)
14373 (error "Not at a dynamic block"))
14374 (let* ((begdel (1+ (match-end 0)))
14375 (name (org-no-properties (match-string 1)))
14376 (params (append (list :name name)
14377 (read (concat "(" (match-string 3) ")")))))
14378 (unless (re-search-forward org-dblock-end-re nil t)
14379 (error "Dynamic block not terminated"))
14380 (delete-region begdel (match-beginning 0))
14381 (goto-char begdel)
14382 (open-line 1)
14383 params))
14385 (defun org-map-dblocks (&optional command)
14386 "Apply COMMAND to all dynamic blocks in the current buffer.
14387 If COMMAND is not given, use `org-update-dblock'."
14388 (let ((cmd (or command 'org-update-dblock))
14389 pos)
14390 (save-excursion
14391 (goto-char (point-min))
14392 (while (re-search-forward org-dblock-start-re nil t)
14393 (goto-char (setq pos (match-beginning 0)))
14394 (condition-case nil
14395 (funcall cmd)
14396 (error (message "Error during update of dynamic block")))
14397 (goto-char pos)
14398 (unless (re-search-forward org-dblock-end-re nil t)
14399 (error "Dynamic block not terminated"))))))
14401 (defun org-dblock-update (&optional arg)
14402 "User command for updating dynamic blocks.
14403 Update the dynamic block at point. With prefix ARG, update all dynamic
14404 blocks in the buffer."
14405 (interactive "P")
14406 (if arg
14407 (org-update-all-dblocks)
14408 (or (looking-at org-dblock-start-re)
14409 (org-beginning-of-dblock))
14410 (org-update-dblock)))
14412 (defun org-update-dblock ()
14413 "Update the dynamic block at point
14414 This means to empty the block, parse for parameters and then call
14415 the correct writing function."
14416 (save-window-excursion
14417 (let* ((pos (point))
14418 (line (org-current-line))
14419 (params (org-prepare-dblock))
14420 (name (plist-get params :name))
14421 (cmd (intern (concat "org-dblock-write:" name))))
14422 (message "Updating dynamic block `%s' at line %d..." name line)
14423 (funcall cmd params)
14424 (message "Updating dynamic block `%s' at line %d...done" name line)
14425 (goto-char pos))))
14427 (defun org-beginning-of-dblock ()
14428 "Find the beginning of the dynamic block at point.
14429 Error if there is no scuh block at point."
14430 (let ((pos (point))
14431 beg)
14432 (end-of-line 1)
14433 (if (and (re-search-backward org-dblock-start-re nil t)
14434 (setq beg (match-beginning 0))
14435 (re-search-forward org-dblock-end-re nil t)
14436 (> (match-end 0) pos))
14437 (goto-char beg)
14438 (goto-char pos)
14439 (error "Not in a dynamic block"))))
14441 (defun org-update-all-dblocks ()
14442 "Update all dynamic blocks in the buffer.
14443 This function can be used in a hook."
14444 (when (org-mode-p)
14445 (org-map-dblocks 'org-update-dblock)))
14448 ;;;; Completion
14450 (defconst org-additional-option-like-keywords
14451 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14452 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14453 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14455 (defun org-complete (&optional arg)
14456 "Perform completion on word at point.
14457 At the beginning of a headline, this completes TODO keywords as given in
14458 `org-todo-keywords'.
14459 If the current word is preceded by a backslash, completes the TeX symbols
14460 that are supported for HTML support.
14461 If the current word is preceded by \"#+\", completes special words for
14462 setting file options.
14463 In the line after \"#+STARTUP:, complete valid keywords.\"
14464 At all other locations, this simply calls the value of
14465 `org-completion-fallback-command'."
14466 (interactive "P")
14467 (org-without-partial-completion
14468 (catch 'exit
14469 (let* ((end (point))
14470 (beg1 (save-excursion
14471 (skip-chars-backward (org-re "[:alnum:]_@"))
14472 (point)))
14473 (beg (save-excursion
14474 (skip-chars-backward "a-zA-Z0-9_:$")
14475 (point)))
14476 (confirm (lambda (x) (stringp (car x))))
14477 (searchhead (equal (char-before beg) ?*))
14478 (tag (and (equal (char-before beg1) ?:)
14479 (equal (char-after (point-at-bol)) ?*)))
14480 (prop (and (equal (char-before beg1) ?:)
14481 (not (equal (char-after (point-at-bol)) ?*))))
14482 (texp (equal (char-before beg) ?\\))
14483 (link (equal (char-before beg) ?\[))
14484 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14485 beg)
14486 "#+"))
14487 (startup (string-match "^#\\+STARTUP:.*"
14488 (buffer-substring (point-at-bol) (point))))
14489 (completion-ignore-case opt)
14490 (type nil)
14491 (tbl nil)
14492 (table (cond
14493 (opt
14494 (setq type :opt)
14495 (append
14496 (mapcar
14497 (lambda (x)
14498 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14499 (cons (match-string 2 x) (match-string 1 x)))
14500 (org-split-string (org-get-current-options) "\n"))
14501 (mapcar 'list org-additional-option-like-keywords)))
14502 (startup
14503 (setq type :startup)
14504 org-startup-options)
14505 (link (append org-link-abbrev-alist-local
14506 org-link-abbrev-alist))
14507 (texp
14508 (setq type :tex)
14509 org-html-entities)
14510 ((string-match "\\`\\*+[ \t]+\\'"
14511 (buffer-substring (point-at-bol) beg))
14512 (setq type :todo)
14513 (mapcar 'list org-todo-keywords-1))
14514 (searchhead
14515 (setq type :searchhead)
14516 (save-excursion
14517 (goto-char (point-min))
14518 (while (re-search-forward org-todo-line-regexp nil t)
14519 (push (list
14520 (org-make-org-heading-search-string
14521 (match-string 3) t))
14522 tbl)))
14523 tbl)
14524 (tag (setq type :tag beg beg1)
14525 (or org-tag-alist (org-get-buffer-tags)))
14526 (prop (setq type :prop beg beg1)
14527 (mapcar 'list (org-buffer-property-keys nil t t)))
14528 (t (progn
14529 (call-interactively org-completion-fallback-command)
14530 (throw 'exit nil)))))
14531 (pattern (buffer-substring-no-properties beg end))
14532 (completion (try-completion pattern table confirm)))
14533 (cond ((eq completion t)
14534 (if (not (assoc (upcase pattern) table))
14535 (message "Already complete")
14536 (if (equal type :opt)
14537 (insert (substring (cdr (assoc (upcase pattern) table))
14538 (length pattern)))
14539 (if (memq type '(:tag :prop)) (insert ":")))))
14540 ((null completion)
14541 (message "Can't find completion for \"%s\"" pattern)
14542 (ding))
14543 ((not (string= pattern completion))
14544 (delete-region beg end)
14545 (if (string-match " +$" completion)
14546 (setq completion (replace-match "" t t completion)))
14547 (insert completion)
14548 (if (get-buffer-window "*Completions*")
14549 (delete-window (get-buffer-window "*Completions*")))
14550 (if (assoc completion table)
14551 (if (eq type :todo) (insert " ")
14552 (if (memq type '(:tag :prop)) (insert ":"))))
14553 (if (and (equal type :opt) (assoc completion table))
14554 (message "%s" (substitute-command-keys
14555 "Press \\[org-complete] again to insert example settings"))))
14557 (message "Making completion list...")
14558 (let ((list (sort (all-completions pattern table confirm)
14559 'string<)))
14560 (with-output-to-temp-buffer "*Completions*"
14561 (condition-case nil
14562 ;; Protection needed for XEmacs and emacs 21
14563 (display-completion-list list pattern)
14564 (error (display-completion-list list)))))
14565 (message "Making completion list...%s" "done")))))))
14567 ;;;; TODO, DEADLINE, Comments
14569 (defun org-toggle-comment ()
14570 "Change the COMMENT state of an entry."
14571 (interactive)
14572 (save-excursion
14573 (org-back-to-heading)
14574 (let (case-fold-search)
14575 (if (looking-at (concat outline-regexp
14576 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14577 (replace-match "" t t nil 1)
14578 (if (looking-at outline-regexp)
14579 (progn
14580 (goto-char (match-end 0))
14581 (insert org-comment-string " ")))))))
14583 (defvar org-last-todo-state-is-todo nil
14584 "This is non-nil when the last TODO state change led to a TODO state.
14585 If the last change removed the TODO tag or switched to DONE, then
14586 this is nil.")
14588 (defvar org-setting-tags nil) ; dynamically skiped
14590 ;; FIXME: better place
14591 (defun org-property-or-variable-value (var &optional inherit)
14592 "Check if there is a property fixing the value of VAR.
14593 If yes, return this value. If not, return the current value of the variable."
14594 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14595 (if (and prop (stringp prop) (string-match "\\S-" prop))
14596 (read prop)
14597 (symbol-value var))))
14599 (defun org-parse-local-options (string var)
14600 "Parse STRING for startup setting relevant for variable VAR."
14601 (let ((rtn (symbol-value var))
14602 e opts)
14603 (save-match-data
14604 (if (or (not string) (not (string-match "\\S-" string)))
14606 (setq opts (delq nil (mapcar (lambda (x)
14607 (setq e (assoc x org-startup-options))
14608 (if (eq (nth 1 e) var) e nil))
14609 (org-split-string string "[ \t]+"))))
14610 (if (not opts)
14612 (setq rtn nil)
14613 (while (setq e (pop opts))
14614 (if (not (nth 3 e))
14615 (setq rtn (nth 2 e))
14616 (if (not (listp rtn)) (setq rtn nil))
14617 (push (nth 2 e) rtn)))
14618 rtn)))))
14620 (defvar org-blocker-hook nil
14621 "Hook for functions that are allowed to block a state change.
14623 Each function gets as its single argument a property list, see
14624 `org-trigger-hook' for more information about this list.
14626 If any of the functions in this hook returns nil, the state change
14627 is blocked.")
14629 (defvar org-trigger-hook nil
14630 "Hook for functions that are triggered by a state change.
14632 Each function gets as its single argument a property list with at least
14633 the following elements:
14635 (:type type-of-change :position pos-at-entry-start
14636 :from old-state :to new-state)
14638 Depending on the type, more properties may be present.
14640 This mechanism is currently implemented for:
14642 TODO state changes
14643 ------------------
14644 :type todo-state-change
14645 :from previous state (keyword as a string), or nil
14646 :to new state (keyword as a string), or nil")
14649 (defun org-todo (&optional arg)
14650 "Change the TODO state of an item.
14651 The state of an item is given by a keyword at the start of the heading,
14652 like
14653 *** TODO Write paper
14654 *** DONE Call mom
14656 The different keywords are specified in the variable `org-todo-keywords'.
14657 By default the available states are \"TODO\" and \"DONE\".
14658 So for this example: when the item starts with TODO, it is changed to DONE.
14659 When it starts with DONE, the DONE is removed. And when neither TODO nor
14660 DONE are present, add TODO at the beginning of the heading.
14662 With C-u prefix arg, use completion to determine the new state.
14663 With numeric prefix arg, switch to that state.
14665 For calling through lisp, arg is also interpreted in the following way:
14666 'none -> empty state
14667 \"\"(empty string) -> switch to empty state
14668 'done -> switch to DONE
14669 'nextset -> switch to the next set of keywords
14670 'previousset -> switch to the previous set of keywords
14671 \"WAITING\" -> switch to the specified keyword, but only if it
14672 really is a member of `org-todo-keywords'."
14673 (interactive "P")
14674 (save-excursion
14675 (catch 'exit
14676 (org-back-to-heading)
14677 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14678 (or (looking-at (concat " +" org-todo-regexp " *"))
14679 (looking-at " *"))
14680 (let* ((match-data (match-data))
14681 (startpos (point-at-bol))
14682 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14683 (org-log-done org-log-done)
14684 (org-log-repeat org-log-repeat)
14685 (org-todo-log-states org-todo-log-states)
14686 (this (match-string 1))
14687 (hl-pos (match-beginning 0))
14688 (head (org-get-todo-sequence-head this))
14689 (ass (assoc head org-todo-kwd-alist))
14690 (interpret (nth 1 ass))
14691 (done-word (nth 3 ass))
14692 (final-done-word (nth 4 ass))
14693 (last-state (or this ""))
14694 (completion-ignore-case t)
14695 (member (member this org-todo-keywords-1))
14696 (tail (cdr member))
14697 (state (cond
14698 ((and org-todo-key-trigger
14699 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14700 (and (not arg) org-use-fast-todo-selection
14701 (not (eq org-use-fast-todo-selection 'prefix)))))
14702 ;; Use fast selection
14703 (org-fast-todo-selection))
14704 ((and (equal arg '(4))
14705 (or (not org-use-fast-todo-selection)
14706 (not org-todo-key-trigger)))
14707 ;; Read a state with completion
14708 (completing-read "State: " (mapcar (lambda(x) (list x))
14709 org-todo-keywords-1)
14710 nil t))
14711 ((eq arg 'right)
14712 (if this
14713 (if tail (car tail) nil)
14714 (car org-todo-keywords-1)))
14715 ((eq arg 'left)
14716 (if (equal member org-todo-keywords-1)
14718 (if this
14719 (nth (- (length org-todo-keywords-1) (length tail) 2)
14720 org-todo-keywords-1)
14721 (org-last org-todo-keywords-1))))
14722 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14723 (setq arg nil))) ; hack to fall back to cycling
14724 (arg
14725 ;; user or caller requests a specific state
14726 (cond
14727 ((equal arg "") nil)
14728 ((eq arg 'none) nil)
14729 ((eq arg 'done) (or done-word (car org-done-keywords)))
14730 ((eq arg 'nextset)
14731 (or (car (cdr (member head org-todo-heads)))
14732 (car org-todo-heads)))
14733 ((eq arg 'previousset)
14734 (let ((org-todo-heads (reverse org-todo-heads)))
14735 (or (car (cdr (member head org-todo-heads)))
14736 (car org-todo-heads))))
14737 ((car (member arg org-todo-keywords-1)))
14738 ((nth (1- (prefix-numeric-value arg))
14739 org-todo-keywords-1))))
14740 ((null member) (or head (car org-todo-keywords-1)))
14741 ((equal this final-done-word) nil) ;; -> make empty
14742 ((null tail) nil) ;; -> first entry
14743 ((eq interpret 'sequence)
14744 (car tail))
14745 ((memq interpret '(type priority))
14746 (if (eq this-command last-command)
14747 (car tail)
14748 (if (> (length tail) 0)
14749 (or done-word (car org-done-keywords))
14750 nil)))
14751 (t nil)))
14752 (next (if state (concat " " state " ") " "))
14753 (change-plist (list :type 'todo-state-change :from this :to state
14754 :position startpos))
14755 dolog now-done-p)
14756 (when org-blocker-hook
14757 (unless (save-excursion
14758 (save-match-data
14759 (run-hook-with-args-until-failure
14760 'org-blocker-hook change-plist)))
14761 (if (interactive-p)
14762 (error "TODO state change from %s to %s blocked" this state)
14763 ;; fail silently
14764 (message "TODO state change from %s to %s blocked" this state)
14765 (throw 'exit nil))))
14766 (store-match-data match-data)
14767 (replace-match next t t)
14768 (unless (pos-visible-in-window-p hl-pos)
14769 (message "TODO state changed to %s" (org-trim next)))
14770 (unless head
14771 (setq head (org-get-todo-sequence-head state)
14772 ass (assoc head org-todo-kwd-alist)
14773 interpret (nth 1 ass)
14774 done-word (nth 3 ass)
14775 final-done-word (nth 4 ass)))
14776 (when (memq arg '(nextset previousset))
14777 (message "Keyword-Set %d/%d: %s"
14778 (- (length org-todo-sets) -1
14779 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14780 (length org-todo-sets)
14781 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14782 (setq org-last-todo-state-is-todo
14783 (not (member state org-done-keywords)))
14784 (setq now-done-p (and (member state org-done-keywords)
14785 (not (member this org-done-keywords))))
14786 (and logging (org-local-logging logging))
14787 (when (and (or org-todo-log-states org-log-done)
14788 (not (memq arg '(nextset previousset))))
14789 ;; we need to look at recording a time and note
14790 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14791 (nth 2 (assoc this org-todo-log-states))))
14792 (when (and state
14793 (member state org-not-done-keywords)
14794 (not (member this org-not-done-keywords)))
14795 ;; This is now a todo state and was not one before
14796 ;; If there was a CLOSED time stamp, get rid of it.
14797 (org-add-planning-info nil nil 'closed))
14798 (when (and now-done-p org-log-done)
14799 ;; It is now done, and it was not done before
14800 (org-add-planning-info 'closed (org-current-time))
14801 (if (and (not dolog) (eq 'note org-log-done))
14802 (org-add-log-maybe 'done state 'findpos 'note)))
14803 (when (and state dolog)
14804 ;; This is a non-nil state, and we need to log it
14805 (org-add-log-maybe 'state state 'findpos dolog)))
14806 ;; Fixup tag positioning
14807 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14808 (run-hooks 'org-after-todo-state-change-hook)
14809 (if (and arg (not (member state org-done-keywords)))
14810 (setq head (org-get-todo-sequence-head state)))
14811 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14812 ;; Do we need to trigger a repeat?
14813 (when now-done-p (org-auto-repeat-maybe state))
14814 ;; Fixup cursor location if close to the keyword
14815 (if (and (outline-on-heading-p)
14816 (not (bolp))
14817 (save-excursion (beginning-of-line 1)
14818 (looking-at org-todo-line-regexp))
14819 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14820 (progn
14821 (goto-char (or (match-end 2) (match-end 1)))
14822 (just-one-space)))
14823 (when org-trigger-hook
14824 (save-excursion
14825 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14827 (defun org-local-logging (value)
14828 "Get logging settings from a property VALUE."
14829 (let* (words w a)
14830 ;; directly set the variables, they are already local.
14831 (setq org-log-done nil
14832 org-log-repeat nil
14833 org-todo-log-states nil)
14834 (setq words (org-split-string value))
14835 (while (setq w (pop words))
14836 (cond
14837 ((setq a (assoc w org-startup-options))
14838 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14839 (set (nth 1 a) (nth 2 a))))
14840 ((setq a (org-extract-log-state-settings w))
14841 (and (member (car a) org-todo-keywords-1)
14842 (push a org-todo-log-states)))))))
14844 (defun org-get-todo-sequence-head (kwd)
14845 "Return the head of the TODO sequence to which KWD belongs.
14846 If KWD is not set, check if there is a text property remembering the
14847 right sequence."
14848 (let (p)
14849 (cond
14850 ((not kwd)
14851 (or (get-text-property (point-at-bol) 'org-todo-head)
14852 (progn
14853 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14854 nil (point-at-eol)))
14855 (get-text-property p 'org-todo-head))))
14856 ((not (member kwd org-todo-keywords-1))
14857 (car org-todo-keywords-1))
14858 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14860 (defun org-fast-todo-selection ()
14861 "Fast TODO keyword selection with single keys.
14862 Returns the new TODO keyword, or nil if no state change should occur."
14863 (let* ((fulltable org-todo-key-alist)
14864 (done-keywords org-done-keywords) ;; needed for the faces.
14865 (maxlen (apply 'max (mapcar
14866 (lambda (x)
14867 (if (stringp (car x)) (string-width (car x)) 0))
14868 fulltable)))
14869 (expert nil)
14870 (fwidth (+ maxlen 3 1 3))
14871 (ncol (/ (- (window-width) 4) fwidth))
14872 tg cnt e c tbl
14873 groups ingroup)
14874 (save-window-excursion
14875 (if expert
14876 (set-buffer (get-buffer-create " *Org todo*"))
14877 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14878 (erase-buffer)
14879 (org-set-local 'org-done-keywords done-keywords)
14880 (setq tbl fulltable cnt 0)
14881 (while (setq e (pop tbl))
14882 (cond
14883 ((equal e '(:startgroup))
14884 (push '() groups) (setq ingroup t)
14885 (when (not (= cnt 0))
14886 (setq cnt 0)
14887 (insert "\n"))
14888 (insert "{ "))
14889 ((equal e '(:endgroup))
14890 (setq ingroup nil cnt 0)
14891 (insert "}\n"))
14893 (setq tg (car e) c (cdr e))
14894 (if ingroup (push tg (car groups)))
14895 (setq tg (org-add-props tg nil 'face
14896 (org-get-todo-face tg)))
14897 (if (and (= cnt 0) (not ingroup)) (insert " "))
14898 (insert "[" c "] " tg (make-string
14899 (- fwidth 4 (length tg)) ?\ ))
14900 (when (= (setq cnt (1+ cnt)) ncol)
14901 (insert "\n")
14902 (if ingroup (insert " "))
14903 (setq cnt 0)))))
14904 (insert "\n")
14905 (goto-char (point-min))
14906 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14907 (fit-window-to-buffer))
14908 (message "[a-z..]:Set [SPC]:clear")
14909 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14910 (cond
14911 ((or (= c ?\C-g)
14912 (and (= c ?q) (not (rassoc c fulltable))))
14913 (setq quit-flag t))
14914 ((= c ?\ ) nil)
14915 ((setq e (rassoc c fulltable) tg (car e))
14917 (t (setq quit-flag t))))))
14919 (defun org-get-repeat ()
14920 "Check if tere is a deadline/schedule with repeater in this entry."
14921 (save-match-data
14922 (save-excursion
14923 (org-back-to-heading t)
14924 (if (re-search-forward
14925 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
14926 (match-string 1)))))
14928 (defvar org-last-changed-timestamp)
14929 (defvar org-log-post-message)
14930 (defvar org-log-note-purpose)
14931 (defun org-auto-repeat-maybe (done-word)
14932 "Check if the current headline contains a repeated deadline/schedule.
14933 If yes, set TODO state back to what it was and change the base date
14934 of repeating deadline/scheduled time stamps to new date.
14935 This function is run automatically after each state change to a DONE state."
14936 ;; last-state is dynamically scoped into this function
14937 (let* ((repeat (org-get-repeat))
14938 (aa (assoc last-state org-todo-kwd-alist))
14939 (interpret (nth 1 aa))
14940 (head (nth 2 aa))
14941 (whata '(("d" . day) ("m" . month) ("y" . year)))
14942 (msg "Entry repeats: ")
14943 (org-log-done nil)
14944 (org-todo-log-states nil)
14945 re type n what ts)
14946 (when repeat
14947 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
14948 (org-todo (if (eq interpret 'type) last-state head))
14949 (when (and org-log-repeat
14950 (or (not (memq 'org-add-log-note
14951 (default-value 'post-command-hook)))
14952 (eq org-log-note-purpose 'done)))
14953 ;; Make sure a note is taken;
14954 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
14955 'findpos org-log-repeat))
14956 (org-back-to-heading t)
14957 (org-add-planning-info nil nil 'closed)
14958 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
14959 org-deadline-time-regexp "\\)\\|\\("
14960 org-ts-regexp "\\)"))
14961 (while (re-search-forward
14962 re (save-excursion (outline-next-heading) (point)) t)
14963 (setq type (if (match-end 1) org-scheduled-string
14964 (if (match-end 3) org-deadline-string "Plain:"))
14965 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
14966 (when (string-match "\\([-+]?[0-9]+\\)\\([dwmy]\\)" ts)
14967 (setq n (string-to-number (match-string 1 ts))
14968 what (match-string 2 ts))
14969 (if (equal what "w") (setq n (* n 7) what "d"))
14970 (org-timestamp-change n (cdr (assoc what whata)))
14971 (setq msg (concat msg type org-last-changed-timestamp " "))))
14972 (setq org-log-post-message msg)
14973 (message "%s" msg))))
14975 (defun org-show-todo-tree (arg)
14976 "Make a compact tree which shows all headlines marked with TODO.
14977 The tree will show the lines where the regexp matches, and all higher
14978 headlines above the match.
14979 With a \\[universal-argument] prefix, also show the DONE entries.
14980 With a numeric prefix N, construct a sparse tree for the Nth element
14981 of `org-todo-keywords-1'."
14982 (interactive "P")
14983 (let ((case-fold-search nil)
14984 (kwd-re
14985 (cond ((null arg) org-not-done-regexp)
14986 ((equal arg '(4))
14987 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
14988 (mapcar 'list org-todo-keywords-1))))
14989 (concat "\\("
14990 (mapconcat 'identity (org-split-string kwd "|") "\\|")
14991 "\\)\\>")))
14992 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
14993 (regexp-quote (nth (1- (prefix-numeric-value arg))
14994 org-todo-keywords-1)))
14995 (t (error "Invalid prefix argument: %s" arg)))))
14996 (message "%d TODO entries found"
14997 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
14999 (defun org-deadline (&optional remove)
15000 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15001 With argument REMOVE, remove any deadline from the item."
15002 (interactive "P")
15003 (if remove
15004 (progn
15005 (org-remove-timestamp-with-keyword org-deadline-string)
15006 (message "Item no longer has a deadline."))
15007 (org-add-planning-info 'deadline nil 'closed)))
15009 (defun org-schedule (&optional remove)
15010 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15011 With argument REMOVE, remove any scheduling date from the item."
15012 (interactive "P")
15013 (if remove
15014 (progn
15015 (org-remove-timestamp-with-keyword org-scheduled-string)
15016 (message "Item is no longer scheduled."))
15017 (org-add-planning-info 'scheduled nil 'closed)))
15019 (defun org-remove-timestamp-with-keyword (keyword)
15020 "Remove all time stamps with KEYWORD in the current entry."
15021 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15022 beg)
15023 (save-excursion
15024 (org-back-to-heading t)
15025 (setq beg (point))
15026 (org-end-of-subtree t t)
15027 (while (re-search-backward re beg t)
15028 (replace-match "")
15029 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15030 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15032 (defun org-add-planning-info (what &optional time &rest remove)
15033 "Insert new timestamp with keyword in the line directly after the headline.
15034 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15035 If non is given, the user is prompted for a date.
15036 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15037 be removed."
15038 (interactive)
15039 (let (org-time-was-given org-end-time-was-given)
15040 (when what (setq time (or time (org-read-date nil 'to-time))))
15041 (when (and org-insert-labeled-timestamps-at-point
15042 (member what '(scheduled deadline)))
15043 (insert
15044 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15045 (org-insert-time-stamp time org-time-was-given
15046 nil nil nil (list org-end-time-was-given))
15047 (setq what nil))
15048 (save-excursion
15049 (save-restriction
15050 (let (col list elt ts buffer-invisibility-spec)
15051 (org-back-to-heading t)
15052 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15053 (goto-char (match-end 1))
15054 (setq col (current-column))
15055 (goto-char (match-end 0))
15056 (if (eobp) (insert "\n") (forward-char 1))
15057 (if (and (not (looking-at outline-regexp))
15058 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15059 "[^\r\n]*"))
15060 (not (equal (match-string 1) org-clock-string)))
15061 (narrow-to-region (match-beginning 0) (match-end 0))
15062 (insert-before-markers "\n")
15063 (backward-char 1)
15064 (narrow-to-region (point) (point))
15065 (indent-to-column col))
15066 ;; Check if we have to remove something.
15067 (setq list (cons what remove))
15068 (while list
15069 (setq elt (pop list))
15070 (goto-char (point-min))
15071 (when (or (and (eq elt 'scheduled)
15072 (re-search-forward org-scheduled-time-regexp nil t))
15073 (and (eq elt 'deadline)
15074 (re-search-forward org-deadline-time-regexp nil t))
15075 (and (eq elt 'closed)
15076 (re-search-forward org-closed-time-regexp nil t)))
15077 (replace-match "")
15078 (if (looking-at "--+<[^>]+>") (replace-match ""))
15079 (if (looking-at " +") (replace-match ""))))
15080 (goto-char (point-max))
15081 (when what
15082 (insert
15083 (if (not (equal (char-before) ?\ )) " " "")
15084 (cond ((eq what 'scheduled) org-scheduled-string)
15085 ((eq what 'deadline) org-deadline-string)
15086 ((eq what 'closed) org-closed-string))
15087 " ")
15088 (setq ts (org-insert-time-stamp
15089 time
15090 (or org-time-was-given
15091 (and (eq what 'closed) org-log-done-with-time))
15092 (eq what 'closed)
15093 nil nil (list org-end-time-was-given)))
15094 (end-of-line 1))
15095 (goto-char (point-min))
15096 (widen)
15097 (if (looking-at "[ \t]+\r?\n")
15098 (replace-match ""))
15099 ts)))))
15101 (defvar org-log-note-marker (make-marker))
15102 (defvar org-log-note-purpose nil)
15103 (defvar org-log-note-state nil)
15104 (defvar org-log-note-how nil)
15105 (defvar org-log-note-window-configuration nil)
15106 (defvar org-log-note-return-to (make-marker))
15107 (defvar org-log-post-message nil
15108 "Message to be displayed after a log note has been stored.
15109 The auto-repeater uses this.")
15111 (defun org-add-log-maybe (&optional purpose state findpos how)
15112 "Set up the post command hook to take a note.
15113 If this is about to TODO state change, the new state is expected in STATE.
15114 When FINDPOS is non-nil, find the correct position for the note in
15115 the current entry. If not, assume that it can be inserted at point."
15116 (save-excursion
15117 (when findpos
15118 (org-back-to-heading t)
15119 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15120 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15121 "[^\r\n]*\\)?"))
15122 (goto-char (match-end 0))
15123 (unless org-log-states-order-reversed
15124 (and (= (char-after) ?\n) (forward-char 1))
15125 (org-skip-over-state-notes)
15126 (skip-chars-backward " \t\n\r")))
15127 (move-marker org-log-note-marker (point))
15128 (setq org-log-note-purpose purpose
15129 org-log-note-state state
15130 org-log-note-how how)
15131 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15133 (defun org-skip-over-state-notes ()
15134 "Skip past the list of State notes in an entry."
15135 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15136 (while (looking-at "[ \t]*- State")
15137 (condition-case nil
15138 (org-next-item)
15139 (error (org-end-of-item)))))
15141 (defun org-add-log-note (&optional purpose)
15142 "Pop up a window for taking a note, and add this note later at point."
15143 (remove-hook 'post-command-hook 'org-add-log-note)
15144 (setq org-log-note-window-configuration (current-window-configuration))
15145 (delete-other-windows)
15146 (move-marker org-log-note-return-to (point))
15147 (switch-to-buffer (marker-buffer org-log-note-marker))
15148 (goto-char org-log-note-marker)
15149 (org-switch-to-buffer-other-window "*Org Note*")
15150 (erase-buffer)
15151 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15152 (org-store-log-note)
15153 (let ((org-inhibit-startup t)) (org-mode))
15154 (insert (format "# Insert note for %s.
15155 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15156 (cond
15157 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15158 ((eq org-log-note-purpose 'done) "closed todo item")
15159 ((eq org-log-note-purpose 'state)
15160 (format "state change to \"%s\"" org-log-note-state))
15161 (t (error "This should not happen")))))
15162 (org-set-local 'org-finish-function 'org-store-log-note)))
15164 (defun org-store-log-note ()
15165 "Finish taking a log note, and insert it to where it belongs."
15166 (let ((txt (buffer-string))
15167 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15168 lines ind)
15169 (kill-buffer (current-buffer))
15170 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15171 (setq txt (replace-match "" t t txt)))
15172 (if (string-match "\\s-+\\'" txt)
15173 (setq txt (replace-match "" t t txt)))
15174 (setq lines (org-split-string txt "\n"))
15175 (when (and note (string-match "\\S-" note))
15176 (setq note
15177 (org-replace-escapes
15178 note
15179 (list (cons "%u" (user-login-name))
15180 (cons "%U" user-full-name)
15181 (cons "%t" (format-time-string
15182 (org-time-stamp-format 'long 'inactive)
15183 (current-time)))
15184 (cons "%s" (if org-log-note-state
15185 (concat "\"" org-log-note-state "\"")
15186 "")))))
15187 (if lines (setq note (concat note " \\\\")))
15188 (push note lines))
15189 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15190 (when lines
15191 (save-excursion
15192 (set-buffer (marker-buffer org-log-note-marker))
15193 (save-excursion
15194 (goto-char org-log-note-marker)
15195 (move-marker org-log-note-marker nil)
15196 (end-of-line 1)
15197 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15198 (indent-relative nil)
15199 (insert "- " (pop lines))
15200 (org-indent-line-function)
15201 (beginning-of-line 1)
15202 (looking-at "[ \t]*")
15203 (setq ind (concat (match-string 0) " "))
15204 (end-of-line 1)
15205 (while lines (insert "\n" ind (pop lines)))))))
15206 (set-window-configuration org-log-note-window-configuration)
15207 (with-current-buffer (marker-buffer org-log-note-return-to)
15208 (goto-char org-log-note-return-to))
15209 (move-marker org-log-note-return-to nil)
15210 (and org-log-post-message (message "%s" org-log-post-message)))
15212 ;; FIXME: what else would be useful?
15213 ;; - priority
15214 ;; - date
15216 (defun org-sparse-tree (&optional arg)
15217 "Create a sparse tree, prompt for the details.
15218 This command can create sparse trees. You first need to select the type
15219 of match used to create the tree:
15221 t Show entries with a specific TODO keyword.
15222 T Show entries selected by a tags match.
15223 p Enter a property name and its value (both with completion on existing
15224 names/values) and show entries with that property.
15225 r Show entries matching a regular expression
15226 d Show deadlines due within `org-deadline-warning-days'."
15227 (interactive "P")
15228 (let (ans kwd value)
15229 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15230 (setq ans (read-char-exclusive))
15231 (cond
15232 ((equal ans ?d)
15233 (call-interactively 'org-check-deadlines))
15234 ((equal ans ?b)
15235 (call-interactively 'org-check-before-date))
15236 ((equal ans ?t)
15237 (org-show-todo-tree '(4)))
15238 ((equal ans ?T)
15239 (call-interactively 'org-tags-sparse-tree))
15240 ((member ans '(?p ?P))
15241 (setq kwd (completing-read "Property: "
15242 (mapcar 'list (org-buffer-property-keys))))
15243 (setq value (completing-read "Value: "
15244 (mapcar 'list (org-property-values kwd))))
15245 (unless (string-match "\\`{.*}\\'" value)
15246 (setq value (concat "\"" value "\"")))
15247 (org-tags-sparse-tree arg (concat kwd "=" value)))
15248 ((member ans '(?r ?R ?/))
15249 (call-interactively 'org-occur))
15250 (t (error "No such sparse tree command \"%c\"" ans)))))
15252 (defvar org-occur-highlights nil)
15253 (make-variable-buffer-local 'org-occur-highlights)
15255 (defun org-occur (regexp &optional keep-previous callback)
15256 "Make a compact tree which shows all matches of REGEXP.
15257 The tree will show the lines where the regexp matches, and all higher
15258 headlines above the match. It will also show the heading after the match,
15259 to make sure editing the matching entry is easy.
15260 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15261 call to `org-occur' will be kept, to allow stacking of calls to this
15262 command.
15263 If CALLBACK is non-nil, it is a function which is called to confirm
15264 that the match should indeed be shown."
15265 (interactive "sRegexp: \nP")
15266 (unless keep-previous
15267 (org-remove-occur-highlights nil nil t))
15268 (let ((cnt 0))
15269 (save-excursion
15270 (goto-char (point-min))
15271 (if (or (not keep-previous) ; do not want to keep
15272 (not org-occur-highlights)) ; no previous matches
15273 ;; hide everything
15274 (org-overview))
15275 (while (re-search-forward regexp nil t)
15276 (when (or (not callback)
15277 (save-match-data (funcall callback)))
15278 (setq cnt (1+ cnt))
15279 (when org-highlight-sparse-tree-matches
15280 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15281 (org-show-context 'occur-tree))))
15282 (when org-remove-highlights-with-change
15283 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15284 nil 'local))
15285 (unless org-sparse-tree-open-archived-trees
15286 (org-hide-archived-subtrees (point-min) (point-max)))
15287 (run-hooks 'org-occur-hook)
15288 (if (interactive-p)
15289 (message "%d match(es) for regexp %s" cnt regexp))
15290 cnt))
15292 (defun org-show-context (&optional key)
15293 "Make sure point and context and visible.
15294 How much context is shown depends upon the variables
15295 `org-show-hierarchy-above', `org-show-following-heading'. and
15296 `org-show-siblings'."
15297 (let ((heading-p (org-on-heading-p t))
15298 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15299 (following-p (org-get-alist-option org-show-following-heading key))
15300 (entry-p (org-get-alist-option org-show-entry-below key))
15301 (siblings-p (org-get-alist-option org-show-siblings key)))
15302 (catch 'exit
15303 ;; Show heading or entry text
15304 (if (and heading-p (not entry-p))
15305 (org-flag-heading nil) ; only show the heading
15306 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15307 (org-show-hidden-entry))) ; show entire entry
15308 (when following-p
15309 ;; Show next sibling, or heading below text
15310 (save-excursion
15311 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15312 (org-flag-heading nil))))
15313 (when siblings-p (org-show-siblings))
15314 (when hierarchy-p
15315 ;; show all higher headings, possibly with siblings
15316 (save-excursion
15317 (while (and (condition-case nil
15318 (progn (org-up-heading-all 1) t)
15319 (error nil))
15320 (not (bobp)))
15321 (org-flag-heading nil)
15322 (when siblings-p (org-show-siblings))))))))
15324 (defun org-reveal (&optional siblings)
15325 "Show current entry, hierarchy above it, and the following headline.
15326 This can be used to show a consistent set of context around locations
15327 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15328 not t for the search context.
15330 With optional argument SIBLINGS, on each level of the hierarchy all
15331 siblings are shown. This repairs the tree structure to what it would
15332 look like when opened with hierarchical calls to `org-cycle'."
15333 (interactive "P")
15334 (let ((org-show-hierarchy-above t)
15335 (org-show-following-heading t)
15336 (org-show-siblings (if siblings t org-show-siblings)))
15337 (org-show-context nil)))
15339 (defun org-highlight-new-match (beg end)
15340 "Highlight from BEG to END and mark the highlight is an occur headline."
15341 (let ((ov (org-make-overlay beg end)))
15342 (org-overlay-put ov 'face 'secondary-selection)
15343 (push ov org-occur-highlights)))
15345 (defun org-remove-occur-highlights (&optional beg end noremove)
15346 "Remove the occur highlights from the buffer.
15347 BEG and END are ignored. If NOREMOVE is nil, remove this function
15348 from the `before-change-functions' in the current buffer."
15349 (interactive)
15350 (unless org-inhibit-highlight-removal
15351 (mapc 'org-delete-overlay org-occur-highlights)
15352 (setq org-occur-highlights nil)
15353 (unless noremove
15354 (remove-hook 'before-change-functions
15355 'org-remove-occur-highlights 'local))))
15357 ;;;; Priorities
15359 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15360 "Regular expression matching the priority indicator.")
15362 (defvar org-remove-priority-next-time nil)
15364 (defun org-priority-up ()
15365 "Increase the priority of the current item."
15366 (interactive)
15367 (org-priority 'up))
15369 (defun org-priority-down ()
15370 "Decrease the priority of the current item."
15371 (interactive)
15372 (org-priority 'down))
15374 (defun org-priority (&optional action)
15375 "Change the priority of an item by ARG.
15376 ACTION can be `set', `up', `down', or a character."
15377 (interactive)
15378 (setq action (or action 'set))
15379 (let (current new news have remove)
15380 (save-excursion
15381 (org-back-to-heading)
15382 (if (looking-at org-priority-regexp)
15383 (setq current (string-to-char (match-string 2))
15384 have t)
15385 (setq current org-default-priority))
15386 (cond
15387 ((or (eq action 'set) (integerp action))
15388 (if (integerp action)
15389 (setq new action)
15390 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15391 (setq new (read-char-exclusive)))
15392 (if (and (= (upcase org-highest-priority) org-highest-priority)
15393 (= (upcase org-lowest-priority) org-lowest-priority))
15394 (setq new (upcase new)))
15395 (cond ((equal new ?\ ) (setq remove t))
15396 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15397 (error "Priority must be between `%c' and `%c'"
15398 org-highest-priority org-lowest-priority))))
15399 ((eq action 'up)
15400 (if (and (not have) (eq last-command this-command))
15401 (setq new org-lowest-priority)
15402 (setq new (if (and org-priority-start-cycle-with-default (not have))
15403 org-default-priority (1- current)))))
15404 ((eq action 'down)
15405 (if (and (not have) (eq last-command this-command))
15406 (setq new org-highest-priority)
15407 (setq new (if (and org-priority-start-cycle-with-default (not have))
15408 org-default-priority (1+ current)))))
15409 (t (error "Invalid action")))
15410 (if (or (< (upcase new) org-highest-priority)
15411 (> (upcase new) org-lowest-priority))
15412 (setq remove t))
15413 (setq news (format "%c" new))
15414 (if have
15415 (if remove
15416 (replace-match "" t t nil 1)
15417 (replace-match news t t nil 2))
15418 (if remove
15419 (error "No priority cookie found in line")
15420 (looking-at org-todo-line-regexp)
15421 (if (match-end 2)
15422 (progn
15423 (goto-char (match-end 2))
15424 (insert " [#" news "]"))
15425 (goto-char (match-beginning 3))
15426 (insert "[#" news "] ")))))
15427 (org-preserve-lc (org-set-tags nil 'align))
15428 (if remove
15429 (message "Priority removed")
15430 (message "Priority of current item set to %s" news))))
15433 (defun org-get-priority (s)
15434 "Find priority cookie and return priority."
15435 (save-match-data
15436 (if (not (string-match org-priority-regexp s))
15437 (* 1000 (- org-lowest-priority org-default-priority))
15438 (* 1000 (- org-lowest-priority
15439 (string-to-char (match-string 2 s)))))))
15441 ;;;; Tags
15443 (defun org-scan-tags (action matcher &optional todo-only)
15444 "Scan headline tags with inheritance and produce output ACTION.
15445 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15446 evaluated, testing if a given set of tags qualifies a headline for
15447 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15448 are included in the output."
15449 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15450 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15451 (org-re
15452 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15453 (props (list 'face nil
15454 'done-face 'org-done
15455 'undone-face nil
15456 'mouse-face 'highlight
15457 'org-not-done-regexp org-not-done-regexp
15458 'org-todo-regexp org-todo-regexp
15459 'keymap org-agenda-keymap
15460 'help-echo
15461 (format "mouse-2 or RET jump to org file %s"
15462 (abbreviate-file-name
15463 (or (buffer-file-name (buffer-base-buffer))
15464 (buffer-name (buffer-base-buffer)))))))
15465 (case-fold-search nil)
15466 lspos
15467 tags tags-list tags-alist (llast 0) rtn level category i txt
15468 todo marker entry priority)
15469 (save-excursion
15470 (goto-char (point-min))
15471 (when (eq action 'sparse-tree)
15472 (org-overview)
15473 (org-remove-occur-highlights))
15474 (while (re-search-forward re nil t)
15475 (catch :skip
15476 (setq todo (if (match-end 1) (match-string 2))
15477 tags (if (match-end 4) (match-string 4)))
15478 (goto-char (setq lspos (1+ (match-beginning 0))))
15479 (setq level (org-reduced-level (funcall outline-level))
15480 category (org-get-category))
15481 (setq i llast llast level)
15482 ;; remove tag lists from same and sublevels
15483 (while (>= i level)
15484 (when (setq entry (assoc i tags-alist))
15485 (setq tags-alist (delete entry tags-alist)))
15486 (setq i (1- i)))
15487 ;; add the nex tags
15488 (when tags
15489 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15490 tags-alist
15491 (cons (cons level tags) tags-alist)))
15492 ;; compile tags for current headline
15493 (setq tags-list
15494 (if org-use-tag-inheritance
15495 (apply 'append (mapcar 'cdr tags-alist))
15496 tags))
15497 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15498 (eval matcher)
15499 (or (not org-agenda-skip-archived-trees)
15500 (not (member org-archive-tag tags-list))))
15501 (and (eq action 'agenda) (org-agenda-skip))
15502 ;; list this headline
15504 (if (eq action 'sparse-tree)
15505 (progn
15506 (and org-highlight-sparse-tree-matches
15507 (org-get-heading) (match-end 0)
15508 (org-highlight-new-match
15509 (match-beginning 0) (match-beginning 1)))
15510 (org-show-context 'tags-tree))
15511 (setq txt (org-format-agenda-item
15513 (concat
15514 (if org-tags-match-list-sublevels
15515 (make-string (1- level) ?.) "")
15516 (org-get-heading))
15517 category tags-list)
15518 priority (org-get-priority txt))
15519 (goto-char lspos)
15520 (setq marker (org-agenda-new-marker))
15521 (org-add-props txt props
15522 'org-marker marker 'org-hd-marker marker 'org-category category
15523 'priority priority 'type "tagsmatch")
15524 (push txt rtn))
15525 ;; if we are to skip sublevels, jump to end of subtree
15526 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15527 (when (and (eq action 'sparse-tree)
15528 (not org-sparse-tree-open-archived-trees))
15529 (org-hide-archived-subtrees (point-min) (point-max)))
15530 (nreverse rtn)))
15532 (defvar todo-only) ;; dynamically scoped
15534 (defun org-tags-sparse-tree (&optional todo-only match)
15535 "Create a sparse tree according to tags string MATCH.
15536 MATCH can contain positive and negative selection of tags, like
15537 \"+WORK+URGENT-WITHBOSS\".
15538 If optional argument TODO_ONLY is non-nil, only select lines that are
15539 also TODO lines."
15540 (interactive "P")
15541 (org-prepare-agenda-buffers (list (current-buffer)))
15542 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15544 (defvar org-cached-props nil)
15545 (defun org-cached-entry-get (pom property)
15546 (if (or (eq t org-use-property-inheritance)
15547 (member property org-use-property-inheritance))
15548 ;; Caching is not possible, check it directly
15549 (org-entry-get pom property 'inherit)
15550 ;; Get all properties, so that we can do complicated checks easily
15551 (cdr (assoc property (or org-cached-props
15552 (setq org-cached-props
15553 (org-entry-properties pom)))))))
15555 (defun org-global-tags-completion-table (&optional files)
15556 "Return the list of all tags in all agenda buffer/files."
15557 (save-excursion
15558 (org-uniquify
15559 (delq nil
15560 (apply 'append
15561 (mapcar
15562 (lambda (file)
15563 (set-buffer (find-file-noselect file))
15564 (append (org-get-buffer-tags)
15565 (mapcar (lambda (x) (if (stringp (car-safe x))
15566 (list (car-safe x)) nil))
15567 org-tag-alist)))
15568 (if (and files (car files))
15569 files
15570 (org-agenda-files))))))))
15572 (defun org-make-tags-matcher (match)
15573 "Create the TAGS//TODO matcher form for the selection string MATCH."
15574 ;; todo-only is scoped dynamically into this function, and the function
15575 ;; may change it it the matcher asksk for it.
15576 (unless match
15577 ;; Get a new match request, with completion
15578 (let ((org-last-tags-completion-table
15579 (org-global-tags-completion-table)))
15580 (setq match (completing-read
15581 "Match: " 'org-tags-completion-function nil nil nil
15582 'org-tags-history))))
15584 ;; Parse the string and create a lisp form
15585 (let ((match0 match)
15586 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15587 minus tag mm
15588 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15589 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15590 (if (string-match "/+" match)
15591 ;; match contains also a todo-matching request
15592 (progn
15593 (setq tagsmatch (substring match 0 (match-beginning 0))
15594 todomatch (substring match (match-end 0)))
15595 (if (string-match "^!" todomatch)
15596 (setq todo-only t todomatch (substring todomatch 1)))
15597 (if (string-match "^\\s-*$" todomatch)
15598 (setq todomatch nil)))
15599 ;; only matching tags
15600 (setq tagsmatch match todomatch nil))
15602 ;; Make the tags matcher
15603 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15604 (setq tagsmatcher t)
15605 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15606 (while (setq term (pop orterms))
15607 (while (and (equal (substring term -1) "\\") orterms)
15608 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15609 (while (string-match re term)
15610 (setq minus (and (match-end 1)
15611 (equal (match-string 1 term) "-"))
15612 tag (match-string 2 term)
15613 re-p (equal (string-to-char tag) ?{)
15614 level-p (match-end 3)
15615 prop-p (match-end 4)
15616 mm (cond
15617 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15618 (level-p `(= level ,(string-to-number
15619 (match-string 3 term))))
15620 (prop-p
15621 (setq pn (match-string 4 term)
15622 pv (match-string 5 term)
15623 cat-p (equal pn "CATEGORY")
15624 re-p (equal (string-to-char pv) ?{)
15625 pv (substring pv 1 -1))
15626 (if (equal pn "CATEGORY")
15627 (setq gv '(get-text-property (point) 'org-category))
15628 (setq gv `(org-cached-entry-get nil ,pn)))
15629 (if re-p
15630 `(string-match ,pv (or ,gv ""))
15631 `(equal ,pv (or ,gv ""))))
15632 (t `(member ,(downcase tag) tags-list)))
15633 mm (if minus (list 'not mm) mm)
15634 term (substring term (match-end 0)))
15635 (push mm tagsmatcher))
15636 (push (if (> (length tagsmatcher) 1)
15637 (cons 'and tagsmatcher)
15638 (car tagsmatcher))
15639 orlist)
15640 (setq tagsmatcher nil))
15641 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15642 (setq tagsmatcher
15643 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15645 ;; Make the todo matcher
15646 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15647 (setq todomatcher t)
15648 (setq orterms (org-split-string todomatch "|") orlist nil)
15649 (while (setq term (pop orterms))
15650 (while (string-match re term)
15651 (setq minus (and (match-end 1)
15652 (equal (match-string 1 term) "-"))
15653 kwd (match-string 2 term)
15654 re-p (equal (string-to-char kwd) ?{)
15655 term (substring term (match-end 0))
15656 mm (if re-p
15657 `(string-match ,(substring kwd 1 -1) todo)
15658 (list 'equal 'todo kwd))
15659 mm (if minus (list 'not mm) mm))
15660 (push mm todomatcher))
15661 (push (if (> (length todomatcher) 1)
15662 (cons 'and todomatcher)
15663 (car todomatcher))
15664 orlist)
15665 (setq todomatcher nil))
15666 (setq todomatcher (if (> (length orlist) 1)
15667 (cons 'or orlist) (car orlist))))
15669 ;; Return the string and lisp forms of the matcher
15670 (setq matcher (if todomatcher
15671 (list 'and tagsmatcher todomatcher)
15672 tagsmatcher))
15673 (cons match0 matcher)))
15675 (defun org-match-any-p (re list)
15676 "Does re match any element of list?"
15677 (setq list (mapcar (lambda (x) (string-match re x)) list))
15678 (delq nil list))
15680 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15681 (defvar org-tags-overlay (org-make-overlay 1 1))
15682 (org-detach-overlay org-tags-overlay)
15684 (defun org-align-tags-here (to-col)
15685 ;; Assumes that this is a headline
15686 (let ((pos (point)) (col (current-column)) tags)
15687 (beginning-of-line 1)
15688 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15689 (< pos (match-beginning 2)))
15690 (progn
15691 (setq tags (match-string 2))
15692 (goto-char (match-beginning 1))
15693 (insert " ")
15694 (delete-region (point) (1+ (match-end 0)))
15695 (backward-char 1)
15696 (move-to-column
15697 (max (1+ (current-column))
15698 (1+ col)
15699 (if (> to-col 0)
15700 to-col
15701 (- (abs to-col) (length tags))))
15703 (insert tags)
15704 (move-to-column (min (current-column) col) t))
15705 (goto-char pos))))
15707 (defun org-set-tags (&optional arg just-align)
15708 "Set the tags for the current headline.
15709 With prefix ARG, realign all tags in headings in the current buffer."
15710 (interactive "P")
15711 (let* ((re (concat "^" outline-regexp))
15712 (current (org-get-tags-string))
15713 (col (current-column))
15714 (org-setting-tags t)
15715 table current-tags inherited-tags ; computed below when needed
15716 tags p0 c0 c1 rpl)
15717 (if arg
15718 (save-excursion
15719 (goto-char (point-min))
15720 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15721 (while (re-search-forward re nil t)
15722 (org-set-tags nil t)
15723 (end-of-line 1)))
15724 (message "All tags realigned to column %d" org-tags-column))
15725 (if just-align
15726 (setq tags current)
15727 ;; Get a new set of tags from the user
15728 (save-excursion
15729 (setq table (or org-tag-alist (org-get-buffer-tags))
15730 org-last-tags-completion-table table
15731 current-tags (org-split-string current ":")
15732 inherited-tags (nreverse
15733 (nthcdr (length current-tags)
15734 (nreverse (org-get-tags-at))))
15735 tags
15736 (if (or (eq t org-use-fast-tag-selection)
15737 (and org-use-fast-tag-selection
15738 (delq nil (mapcar 'cdr table))))
15739 (org-fast-tag-selection
15740 current-tags inherited-tags table
15741 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15742 (let ((org-add-colon-after-tag-completion t))
15743 (org-trim
15744 (org-without-partial-completion
15745 (completing-read "Tags: " 'org-tags-completion-function
15746 nil nil current 'org-tags-history)))))))
15747 (while (string-match "[-+&]+" tags)
15748 ;; No boolean logic, just a list
15749 (setq tags (replace-match ":" t t tags))))
15751 (if (string-match "\\`[\t ]*\\'" tags)
15752 (setq tags "")
15753 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15754 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15756 ;; Insert new tags at the correct column
15757 (beginning-of-line 1)
15758 (cond
15759 ((and (equal current "") (equal tags "")))
15760 ((re-search-forward
15761 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15762 (point-at-eol) t)
15763 (if (equal tags "")
15764 (setq rpl "")
15765 (goto-char (match-beginning 0))
15766 (setq c0 (current-column) p0 (point)
15767 c1 (max (1+ c0) (if (> org-tags-column 0)
15768 org-tags-column
15769 (- (- org-tags-column) (length tags))))
15770 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15771 (replace-match rpl t t)
15772 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15773 tags)
15774 (t (error "Tags alignment failed")))
15775 (move-to-column col)
15776 (unless just-align
15777 (run-hooks 'org-after-tags-change-hook)))))
15779 (defun org-change-tag-in-region (beg end tag off)
15780 "Add or remove TAG for each entry in the region.
15781 This works in the agenda, and also in an org-mode buffer."
15782 (interactive
15783 (list (region-beginning) (region-end)
15784 (let ((org-last-tags-completion-table
15785 (if (org-mode-p)
15786 (org-get-buffer-tags)
15787 (org-global-tags-completion-table))))
15788 (completing-read
15789 "Tag: " 'org-tags-completion-function nil nil nil
15790 'org-tags-history))
15791 (progn
15792 (message "[s]et or [r]emove? ")
15793 (equal (read-char-exclusive) ?r))))
15794 (if (fboundp 'deactivate-mark) (deactivate-mark))
15795 (let ((agendap (equal major-mode 'org-agenda-mode))
15796 l1 l2 m buf pos newhead (cnt 0))
15797 (goto-char end)
15798 (setq l2 (1- (org-current-line)))
15799 (goto-char beg)
15800 (setq l1 (org-current-line))
15801 (loop for l from l1 to l2 do
15802 (goto-line l)
15803 (setq m (get-text-property (point) 'org-hd-marker))
15804 (when (or (and (org-mode-p) (org-on-heading-p))
15805 (and agendap m))
15806 (setq buf (if agendap (marker-buffer m) (current-buffer))
15807 pos (if agendap m (point)))
15808 (with-current-buffer buf
15809 (save-excursion
15810 (save-restriction
15811 (goto-char pos)
15812 (setq cnt (1+ cnt))
15813 (org-toggle-tag tag (if off 'off 'on))
15814 (setq newhead (org-get-heading)))))
15815 (and agendap (org-agenda-change-all-lines newhead m))))
15816 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15818 (defun org-tags-completion-function (string predicate &optional flag)
15819 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15820 (confirm (lambda (x) (stringp (car x)))))
15821 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15822 (setq s1 (match-string 1 string)
15823 s2 (match-string 2 string))
15824 (setq s1 "" s2 string))
15825 (cond
15826 ((eq flag nil)
15827 ;; try completion
15828 (setq rtn (try-completion s2 ctable confirm))
15829 (if (stringp rtn)
15830 (setq rtn
15831 (concat s1 s2 (substring rtn (length s2))
15832 (if (and org-add-colon-after-tag-completion
15833 (assoc rtn ctable))
15834 ":" ""))))
15835 rtn)
15836 ((eq flag t)
15837 ;; all-completions
15838 (all-completions s2 ctable confirm)
15840 ((eq flag 'lambda)
15841 ;; exact match?
15842 (assoc s2 ctable)))
15845 (defun org-fast-tag-insert (kwd tags face &optional end)
15846 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15847 (insert (format "%-12s" (concat kwd ":"))
15848 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15849 (or end "")))
15851 (defun org-fast-tag-show-exit (flag)
15852 (save-excursion
15853 (goto-line 3)
15854 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15855 (replace-match ""))
15856 (when flag
15857 (end-of-line 1)
15858 (move-to-column (- (window-width) 19) t)
15859 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15861 (defun org-set-current-tags-overlay (current prefix)
15862 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15863 (if (featurep 'xemacs)
15864 (org-overlay-display org-tags-overlay (concat prefix s)
15865 'secondary-selection)
15866 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15867 (org-overlay-display org-tags-overlay (concat prefix s)))))
15869 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15870 "Fast tag selection with single keys.
15871 CURRENT is the current list of tags in the headline, INHERITED is the
15872 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15873 possibly with grouping information. TODO-TABLE is a similar table with
15874 TODO keywords, should these have keys assigned to them.
15875 If the keys are nil, a-z are automatically assigned.
15876 Returns the new tags string, or nil to not change the current settings."
15877 (let* ((fulltable (append table todo-table))
15878 (maxlen (apply 'max (mapcar
15879 (lambda (x)
15880 (if (stringp (car x)) (string-width (car x)) 0))
15881 fulltable)))
15882 (buf (current-buffer))
15883 (expert (eq org-fast-tag-selection-single-key 'expert))
15884 (buffer-tags nil)
15885 (fwidth (+ maxlen 3 1 3))
15886 (ncol (/ (- (window-width) 4) fwidth))
15887 (i-face 'org-done)
15888 (c-face 'org-todo)
15889 tg cnt e c char c1 c2 ntable tbl rtn
15890 ov-start ov-end ov-prefix
15891 (exit-after-next org-fast-tag-selection-single-key)
15892 (done-keywords org-done-keywords)
15893 groups ingroup)
15894 (save-excursion
15895 (beginning-of-line 1)
15896 (if (looking-at
15897 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15898 (setq ov-start (match-beginning 1)
15899 ov-end (match-end 1)
15900 ov-prefix "")
15901 (setq ov-start (1- (point-at-eol))
15902 ov-end (1+ ov-start))
15903 (skip-chars-forward "^\n\r")
15904 (setq ov-prefix
15905 (concat
15906 (buffer-substring (1- (point)) (point))
15907 (if (> (current-column) org-tags-column)
15909 (make-string (- org-tags-column (current-column)) ?\ ))))))
15910 (org-move-overlay org-tags-overlay ov-start ov-end)
15911 (save-window-excursion
15912 (if expert
15913 (set-buffer (get-buffer-create " *Org tags*"))
15914 (delete-other-windows)
15915 (split-window-vertically)
15916 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
15917 (erase-buffer)
15918 (org-set-local 'org-done-keywords done-keywords)
15919 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15920 (org-fast-tag-insert "Current" current c-face "\n\n")
15921 (org-fast-tag-show-exit exit-after-next)
15922 (org-set-current-tags-overlay current ov-prefix)
15923 (setq tbl fulltable char ?a cnt 0)
15924 (while (setq e (pop tbl))
15925 (cond
15926 ((equal e '(:startgroup))
15927 (push '() groups) (setq ingroup t)
15928 (when (not (= cnt 0))
15929 (setq cnt 0)
15930 (insert "\n"))
15931 (insert "{ "))
15932 ((equal e '(:endgroup))
15933 (setq ingroup nil cnt 0)
15934 (insert "}\n"))
15936 (setq tg (car e) c2 nil)
15937 (if (cdr e)
15938 (setq c (cdr e))
15939 ;; automatically assign a character.
15940 (setq c1 (string-to-char
15941 (downcase (substring
15942 tg (if (= (string-to-char tg) ?@) 1 0)))))
15943 (if (or (rassoc c1 ntable) (rassoc c1 table))
15944 (while (or (rassoc char ntable) (rassoc char table))
15945 (setq char (1+ char)))
15946 (setq c2 c1))
15947 (setq c (or c2 char)))
15948 (if ingroup (push tg (car groups)))
15949 (setq tg (org-add-props tg nil 'face
15950 (cond
15951 ((not (assoc tg table))
15952 (org-get-todo-face tg))
15953 ((member tg current) c-face)
15954 ((member tg inherited) i-face)
15955 (t nil))))
15956 (if (and (= cnt 0) (not ingroup)) (insert " "))
15957 (insert "[" c "] " tg (make-string
15958 (- fwidth 4 (length tg)) ?\ ))
15959 (push (cons tg c) ntable)
15960 (when (= (setq cnt (1+ cnt)) ncol)
15961 (insert "\n")
15962 (if ingroup (insert " "))
15963 (setq cnt 0)))))
15964 (setq ntable (nreverse ntable))
15965 (insert "\n")
15966 (goto-char (point-min))
15967 (if (and (not expert) (fboundp 'fit-window-to-buffer))
15968 (fit-window-to-buffer))
15969 (setq rtn
15970 (catch 'exit
15971 (while t
15972 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
15973 (if groups " [!] no groups" " [!]groups")
15974 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15975 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15976 (cond
15977 ((= c ?\r) (throw 'exit t))
15978 ((= c ?!)
15979 (setq groups (not groups))
15980 (goto-char (point-min))
15981 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15982 ((= c ?\C-c)
15983 (if (not expert)
15984 (org-fast-tag-show-exit
15985 (setq exit-after-next (not exit-after-next)))
15986 (setq expert nil)
15987 (delete-other-windows)
15988 (split-window-vertically)
15989 (org-switch-to-buffer-other-window " *Org tags*")
15990 (and (fboundp 'fit-window-to-buffer)
15991 (fit-window-to-buffer))))
15992 ((or (= c ?\C-g)
15993 (and (= c ?q) (not (rassoc c ntable))))
15994 (org-detach-overlay org-tags-overlay)
15995 (setq quit-flag t))
15996 ((= c ?\ )
15997 (setq current nil)
15998 (if exit-after-next (setq exit-after-next 'now)))
15999 ((= c ?\t)
16000 (condition-case nil
16001 (setq tg (completing-read
16002 "Tag: "
16003 (or buffer-tags
16004 (with-current-buffer buf
16005 (org-get-buffer-tags)))))
16006 (quit (setq tg "")))
16007 (when (string-match "\\S-" tg)
16008 (add-to-list 'buffer-tags (list tg))
16009 (if (member tg current)
16010 (setq current (delete tg current))
16011 (push tg current)))
16012 (if exit-after-next (setq exit-after-next 'now)))
16013 ((setq e (rassoc c todo-table) tg (car e))
16014 (with-current-buffer buf
16015 (save-excursion (org-todo tg)))
16016 (if exit-after-next (setq exit-after-next 'now)))
16017 ((setq e (rassoc c ntable) tg (car e))
16018 (if (member tg current)
16019 (setq current (delete tg current))
16020 (loop for g in groups do
16021 (if (member tg g)
16022 (mapc (lambda (x)
16023 (setq current (delete x current)))
16024 g)))
16025 (push tg current))
16026 (if exit-after-next (setq exit-after-next 'now))))
16028 ;; Create a sorted list
16029 (setq current
16030 (sort current
16031 (lambda (a b)
16032 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16033 (if (eq exit-after-next 'now) (throw 'exit t))
16034 (goto-char (point-min))
16035 (beginning-of-line 2)
16036 (delete-region (point) (point-at-eol))
16037 (org-fast-tag-insert "Current" current c-face)
16038 (org-set-current-tags-overlay current ov-prefix)
16039 (while (re-search-forward
16040 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16041 (setq tg (match-string 1))
16042 (add-text-properties
16043 (match-beginning 1) (match-end 1)
16044 (list 'face
16045 (cond
16046 ((member tg current) c-face)
16047 ((member tg inherited) i-face)
16048 (t (get-text-property (match-beginning 1) 'face))))))
16049 (goto-char (point-min)))))
16050 (org-detach-overlay org-tags-overlay)
16051 (if rtn
16052 (mapconcat 'identity current ":")
16053 nil))))
16055 (defun org-get-tags-string ()
16056 "Get the TAGS string in the current headline."
16057 (unless (org-on-heading-p t)
16058 (error "Not on a heading"))
16059 (save-excursion
16060 (beginning-of-line 1)
16061 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16062 (org-match-string-no-properties 1)
16063 "")))
16065 (defun org-get-tags ()
16066 "Get the list of tags specified in the current headline."
16067 (org-split-string (org-get-tags-string) ":"))
16069 (defun org-get-buffer-tags ()
16070 "Get a table of all tags used in the buffer, for completion."
16071 (let (tags)
16072 (save-excursion
16073 (goto-char (point-min))
16074 (while (re-search-forward
16075 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16076 (when (equal (char-after (point-at-bol 0)) ?*)
16077 (mapc (lambda (x) (add-to-list 'tags x))
16078 (org-split-string (org-match-string-no-properties 1) ":")))))
16079 (mapcar 'list tags)))
16082 ;;;; Properties
16084 ;;; Setting and retrieving properties
16086 (defconst org-special-properties
16087 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16088 "TIMESTAMP" "TIMESTAMP_IA")
16089 "The special properties valid in Org-mode.
16091 These are properties that are not defined in the property drawer,
16092 but in some other way.")
16094 (defconst org-default-properties
16095 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16096 "LOCATION" "LOGGING" "COLUMNS")
16097 "Some properties that are used by Org-mode for various purposes.
16098 Being in this list makes sure that they are offered for completion.")
16100 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16101 "Regular expression matching the first line of a property drawer.")
16103 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16104 "Regular expression matching the first line of a property drawer.")
16106 (defun org-property-action ()
16107 "Do an action on properties."
16108 (interactive)
16109 (let (c)
16110 (org-at-property-p)
16111 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16112 (setq c (read-char-exclusive))
16113 (cond
16114 ((equal c ?s)
16115 (call-interactively 'org-set-property))
16116 ((equal c ?d)
16117 (call-interactively 'org-delete-property))
16118 ((equal c ?D)
16119 (call-interactively 'org-delete-property-globally))
16120 ((equal c ?c)
16121 (call-interactively 'org-compute-property-at-point))
16122 (t (error "No such property action %c" c)))))
16124 (defun org-at-property-p ()
16125 "Is the cursor in a property line?"
16126 ;; FIXME: Does not check if we are actually in the drawer.
16127 ;; FIXME: also returns true on any drawers.....
16128 ;; This is used by C-c C-c for property action.
16129 (save-excursion
16130 (beginning-of-line 1)
16131 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16133 (defmacro org-with-point-at (pom &rest body)
16134 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16135 (declare (indent 1) (debug t))
16136 `(save-excursion
16137 (if (markerp pom) (set-buffer (marker-buffer pom)))
16138 (save-excursion
16139 (goto-char (or pom (point)))
16140 ,@body)))
16142 (defun org-get-property-block (&optional beg end force)
16143 "Return the (beg . end) range of the body of the property drawer.
16144 BEG and END can be beginning and end of subtree, if not given
16145 they will be found.
16146 If the drawer does not exist and FORCE is non-nil, create the drawer."
16147 (catch 'exit
16148 (save-excursion
16149 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16150 (end (or end (progn (outline-next-heading) (point)))))
16151 (goto-char beg)
16152 (if (re-search-forward org-property-start-re end t)
16153 (setq beg (1+ (match-end 0)))
16154 (if force
16155 (save-excursion
16156 (org-insert-property-drawer)
16157 (setq end (progn (outline-next-heading) (point))))
16158 (throw 'exit nil))
16159 (goto-char beg)
16160 (if (re-search-forward org-property-start-re end t)
16161 (setq beg (1+ (match-end 0)))))
16162 (if (re-search-forward org-property-end-re end t)
16163 (setq end (match-beginning 0))
16164 (or force (throw 'exit nil))
16165 (goto-char beg)
16166 (setq end beg)
16167 (org-indent-line-function)
16168 (insert ":END:\n"))
16169 (cons beg end)))))
16171 (defun org-entry-properties (&optional pom which)
16172 "Get all properties of the entry at point-or-marker POM.
16173 This includes the TODO keyword, the tags, time strings for deadline,
16174 scheduled, and clocking, and any additional properties defined in the
16175 entry. The return value is an alist, keys may occur multiple times
16176 if the property key was used several times.
16177 POM may also be nil, in which case the current entry is used.
16178 If WHICH is nil or `all', get all properties. If WHICH is
16179 `special' or `standard', only get that subclass."
16180 (setq which (or which 'all))
16181 (org-with-point-at pom
16182 (let ((clockstr (substring org-clock-string 0 -1))
16183 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16184 beg end range props sum-props key value string clocksum)
16185 (save-excursion
16186 (when (condition-case nil (org-back-to-heading t) (error nil))
16187 (setq beg (point))
16188 (setq sum-props (get-text-property (point) 'org-summaries))
16189 (setq clocksum (get-text-property (point) :org-clock-minutes))
16190 (outline-next-heading)
16191 (setq end (point))
16192 (when (memq which '(all special))
16193 ;; Get the special properties, like TODO and tags
16194 (goto-char beg)
16195 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16196 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16197 (when (looking-at org-priority-regexp)
16198 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16199 (when (and (setq value (org-get-tags-string))
16200 (string-match "\\S-" value))
16201 (push (cons "TAGS" value) props))
16202 (when (setq value (org-get-tags-at))
16203 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16204 props))
16205 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16206 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16207 string (if (equal key clockstr)
16208 (org-no-properties
16209 (org-trim
16210 (buffer-substring
16211 (match-beginning 3) (goto-char (point-at-eol)))))
16212 (substring (org-match-string-no-properties 3) 1 -1)))
16213 (unless key
16214 (if (= (char-after (match-beginning 3)) ?\[)
16215 (setq key "TIMESTAMP_IA")
16216 (setq key "TIMESTAMP")))
16217 (when (or (equal key clockstr) (not (assoc key props)))
16218 (push (cons key string) props)))
16222 (when (memq which '(all standard))
16223 ;; Get the standard properties, like :PORP: ...
16224 (setq range (org-get-property-block beg end))
16225 (when range
16226 (goto-char (car range))
16227 (while (re-search-forward
16228 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16229 (cdr range) t)
16230 (setq key (org-match-string-no-properties 1)
16231 value (org-trim (or (org-match-string-no-properties 2) "")))
16232 (unless (member key excluded)
16233 (push (cons key (or value "")) props)))))
16234 (if clocksum
16235 (push (cons "CLOCKSUM"
16236 (org-column-number-to-string (/ (float clocksum) 60.)
16237 'add_times))
16238 props))
16239 (append sum-props (nreverse props)))))))
16241 (defun org-entry-get (pom property &optional inherit)
16242 "Get value of PROPERTY for entry at point-or-marker POM.
16243 If INHERIT is non-nil and the entry does not have the property,
16244 then also check higher levels of the hierarchy.
16245 If the property is present but empty, the return value is the empty string.
16246 If the property is not present at all, nil is returned."
16247 (org-with-point-at pom
16248 (if inherit
16249 (org-entry-get-with-inheritance property)
16250 (if (member property org-special-properties)
16251 ;; We need a special property. Use brute force, get all properties.
16252 (cdr (assoc property (org-entry-properties nil 'special)))
16253 (let ((range (org-get-property-block)))
16254 (if (and range
16255 (goto-char (car range))
16256 (re-search-forward
16257 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16258 (cdr range) t))
16259 ;; Found the property, return it.
16260 (if (match-end 1)
16261 (org-match-string-no-properties 1)
16262 "")))))))
16264 (defun org-entry-delete (pom property)
16265 "Delete the property PROPERTY from entry at point-or-marker POM."
16266 (org-with-point-at pom
16267 (if (member property org-special-properties)
16268 nil ; cannot delete these properties.
16269 (let ((range (org-get-property-block)))
16270 (if (and range
16271 (goto-char (car range))
16272 (re-search-forward
16273 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16274 (cdr range) t))
16275 (progn
16276 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16278 nil)))))
16280 ;; Multi-values properties are properties that contain multiple values
16281 ;; These values are assumed to be single words, separated by whitespace.
16282 (defun org-entry-add-to-multivalued-property (pom property value)
16283 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16284 (let* ((old (org-entry-get pom property))
16285 (values (and old (org-split-string old "[ \t]"))))
16286 (unless (member value values)
16287 (setq values (cons value values))
16288 (org-entry-put pom property
16289 (mapconcat 'identity values " ")))))
16291 (defun org-entry-remove-from-multivalued-property (pom property value)
16292 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16293 (let* ((old (org-entry-get pom property))
16294 (values (and old (org-split-string old "[ \t]"))))
16295 (when (member value values)
16296 (setq values (delete value values))
16297 (org-entry-put pom property
16298 (mapconcat 'identity values " ")))))
16300 (defun org-entry-member-in-multivalued-property (pom property value)
16301 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16302 (let* ((old (org-entry-get pom property))
16303 (values (and old (org-split-string old "[ \t]"))))
16304 (member value values)))
16306 (defvar org-entry-property-inherited-from (make-marker))
16308 (defun org-entry-get-with-inheritance (property)
16309 "Get entry property, and search higher levels if not present."
16310 (let (tmp)
16311 (save-excursion
16312 (save-restriction
16313 (widen)
16314 (catch 'ex
16315 (while t
16316 (when (setq tmp (org-entry-get nil property))
16317 (org-back-to-heading t)
16318 (move-marker org-entry-property-inherited-from (point))
16319 (throw 'ex tmp))
16320 (or (org-up-heading-safe) (throw 'ex nil)))))
16321 (or tmp (cdr (assoc property org-local-properties))
16322 (cdr (assoc property org-global-properties))))))
16324 (defun org-entry-put (pom property value)
16325 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16326 (org-with-point-at pom
16327 (org-back-to-heading t)
16328 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16329 range)
16330 (cond
16331 ((equal property "TODO")
16332 (when (and (stringp value) (string-match "\\S-" value)
16333 (not (member value org-todo-keywords-1)))
16334 (error "\"%s\" is not a valid TODO state" value))
16335 (if (or (not value)
16336 (not (string-match "\\S-" value)))
16337 (setq value 'none))
16338 (org-todo value)
16339 (org-set-tags nil 'align))
16340 ((equal property "PRIORITY")
16341 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16342 (string-to-char value) ?\ ))
16343 (org-set-tags nil 'align))
16344 ((equal property "SCHEDULED")
16345 (if (re-search-forward org-scheduled-time-regexp end t)
16346 (cond
16347 ((eq value 'earlier) (org-timestamp-change -1 'day))
16348 ((eq value 'later) (org-timestamp-change 1 'day))
16349 (t (call-interactively 'org-schedule)))
16350 (call-interactively 'org-schedule)))
16351 ((equal property "DEADLINE")
16352 (if (re-search-forward org-deadline-time-regexp end t)
16353 (cond
16354 ((eq value 'earlier) (org-timestamp-change -1 'day))
16355 ((eq value 'later) (org-timestamp-change 1 'day))
16356 (t (call-interactively 'org-deadline)))
16357 (call-interactively 'org-deadline)))
16358 ((member property org-special-properties)
16359 (error "The %s property can not yet be set with `org-entry-put'"
16360 property))
16361 (t ; a non-special property
16362 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16363 (setq range (org-get-property-block beg end 'force))
16364 (goto-char (car range))
16365 (if (re-search-forward
16366 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16367 (progn
16368 (delete-region (match-beginning 1) (match-end 1))
16369 (goto-char (match-beginning 1)))
16370 (goto-char (cdr range))
16371 (insert "\n")
16372 (backward-char 1)
16373 (org-indent-line-function)
16374 (insert ":" property ":"))
16375 (and value (insert " " value))
16376 (org-indent-line-function)))))))
16378 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16379 "Get all property keys in the current buffer.
16380 With INCLUDE-SPECIALS, also list the special properties that relect things
16381 like tags and TODO state.
16382 With INCLUDE-DEFAULTS, also include properties that has special meaning
16383 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16384 With INCLUDE-COLUMNS, also include property names given in COLUMN
16385 formats in the current buffer."
16386 (let (rtn range cfmt cols s p)
16387 (save-excursion
16388 (save-restriction
16389 (widen)
16390 (goto-char (point-min))
16391 (while (re-search-forward org-property-start-re nil t)
16392 (setq range (org-get-property-block))
16393 (goto-char (car range))
16394 (while (re-search-forward
16395 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16396 (cdr range) t)
16397 (add-to-list 'rtn (org-match-string-no-properties 1)))
16398 (outline-next-heading))))
16400 (when include-specials
16401 (setq rtn (append org-special-properties rtn)))
16403 (when include-defaults
16404 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16406 (when include-columns
16407 (save-excursion
16408 (save-restriction
16409 (widen)
16410 (goto-char (point-min))
16411 (while (re-search-forward
16412 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16413 nil t)
16414 (setq cfmt (match-string 2) s 0)
16415 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16416 cfmt s)
16417 (setq s (match-end 0)
16418 p (match-string 1 cfmt))
16419 (unless (or (equal p "ITEM")
16420 (member p org-special-properties))
16421 (add-to-list 'rtn (match-string 1 cfmt))))))))
16423 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16425 (defun org-property-values (key)
16426 "Return a list of all values of property KEY."
16427 (save-excursion
16428 (save-restriction
16429 (widen)
16430 (goto-char (point-min))
16431 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16432 values)
16433 (while (re-search-forward re nil t)
16434 (add-to-list 'values (org-trim (match-string 1))))
16435 (delete "" values)))))
16437 (defun org-insert-property-drawer ()
16438 "Insert a property drawer into the current entry."
16439 (interactive)
16440 (org-back-to-heading t)
16441 (looking-at outline-regexp)
16442 (let ((indent (- (match-end 0)(match-beginning 0)))
16443 (beg (point))
16444 (re (concat "^[ \t]*" org-keyword-time-regexp))
16445 end hiddenp)
16446 (outline-next-heading)
16447 (setq end (point))
16448 (goto-char beg)
16449 (while (re-search-forward re end t))
16450 (setq hiddenp (org-invisible-p))
16451 (end-of-line 1)
16452 (and (equal (char-after) ?\n) (forward-char 1))
16453 (org-skip-over-state-notes)
16454 (skip-chars-backward " \t\n\r")
16455 (if (eq (char-before) ?*) (forward-char 1))
16456 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16457 (beginning-of-line 0)
16458 (indent-to-column indent)
16459 (beginning-of-line 2)
16460 (indent-to-column indent)
16461 (beginning-of-line 0)
16462 (if hiddenp
16463 (save-excursion
16464 (org-back-to-heading t)
16465 (hide-entry))
16466 (org-flag-drawer t))))
16468 (defun org-set-property (property value)
16469 "In the current entry, set PROPERTY to VALUE.
16470 When called interactively, this will prompt for a property name, offering
16471 completion on existing and default properties. And then it will prompt
16472 for a value, offering competion either on allowed values (via an inherited
16473 xxx_ALL property) or on existing values in other instances of this property
16474 in the current file."
16475 (interactive
16476 (let* ((prop (completing-read
16477 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16478 (cur (org-entry-get nil prop))
16479 (allowed (org-property-get-allowed-values nil prop 'table))
16480 (existing (mapcar 'list (org-property-values prop)))
16481 (val (if allowed
16482 (completing-read "Value: " allowed nil 'req-match)
16483 (completing-read
16484 (concat "Value" (if (and cur (string-match "\\S-" cur))
16485 (concat "[" cur "]") "")
16486 ": ")
16487 existing nil nil "" nil cur))))
16488 (list prop (if (equal val "") cur val))))
16489 (unless (equal (org-entry-get nil property) value)
16490 (org-entry-put nil property value)))
16492 (defun org-delete-property (property)
16493 "In the current entry, delete PROPERTY."
16494 (interactive
16495 (let* ((prop (completing-read
16496 "Property: " (org-entry-properties nil 'standard))))
16497 (list prop)))
16498 (message "Property %s %s" property
16499 (if (org-entry-delete nil property)
16500 "deleted"
16501 "was not present in the entry")))
16503 (defun org-delete-property-globally (property)
16504 "Remove PROPERTY globally, from all entries."
16505 (interactive
16506 (let* ((prop (completing-read
16507 "Globally remove property: "
16508 (mapcar 'list (org-buffer-property-keys)))))
16509 (list prop)))
16510 (save-excursion
16511 (save-restriction
16512 (widen)
16513 (goto-char (point-min))
16514 (let ((cnt 0))
16515 (while (re-search-forward
16516 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16517 nil t)
16518 (setq cnt (1+ cnt))
16519 (replace-match ""))
16520 (message "Property \"%s\" removed from %d entries" property cnt)))))
16522 (defvar org-columns-current-fmt-compiled) ; defined below
16524 (defun org-compute-property-at-point ()
16525 "Compute the property at point.
16526 This looks for an enclosing column format, extracts the operator and
16527 then applies it to the proerty in the column format's scope."
16528 (interactive)
16529 (unless (org-at-property-p)
16530 (error "Not at a property"))
16531 (let ((prop (org-match-string-no-properties 2)))
16532 (org-columns-get-format-and-top-level)
16533 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16534 (error "No operator defined for property %s" prop))
16535 (org-columns-compute prop)))
16537 (defun org-property-get-allowed-values (pom property &optional table)
16538 "Get allowed values for the property PROPERTY.
16539 When TABLE is non-nil, return an alist that can directly be used for
16540 completion."
16541 (let (vals)
16542 (cond
16543 ((equal property "TODO")
16544 (setq vals (org-with-point-at pom
16545 (append org-todo-keywords-1 '("")))))
16546 ((equal property "PRIORITY")
16547 (let ((n org-lowest-priority))
16548 (while (>= n org-highest-priority)
16549 (push (char-to-string n) vals)
16550 (setq n (1- n)))))
16551 ((member property org-special-properties))
16553 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16555 (when (and vals (string-match "\\S-" vals))
16556 (setq vals (car (read-from-string (concat "(" vals ")"))))
16557 (setq vals (mapcar (lambda (x)
16558 (cond ((stringp x) x)
16559 ((numberp x) (number-to-string x))
16560 ((symbolp x) (symbol-name x))
16561 (t "???")))
16562 vals)))))
16563 (if table (mapcar 'list vals) vals)))
16565 (defun org-property-previous-allowed-value (&optional previous)
16566 "Switch to the next allowed value for this property."
16567 (interactive)
16568 (org-property-next-allowed-value t))
16570 (defun org-property-next-allowed-value (&optional previous)
16571 "Switch to the next allowed value for this property."
16572 (interactive)
16573 (unless (org-at-property-p)
16574 (error "Not at a property"))
16575 (let* ((key (match-string 2))
16576 (value (match-string 3))
16577 (allowed (or (org-property-get-allowed-values (point) key)
16578 (and (member value '("[ ]" "[-]" "[X]"))
16579 '("[ ]" "[X]"))))
16580 nval)
16581 (unless allowed
16582 (error "Allowed values for this property have not been defined"))
16583 (if previous (setq allowed (reverse allowed)))
16584 (if (member value allowed)
16585 (setq nval (car (cdr (member value allowed)))))
16586 (setq nval (or nval (car allowed)))
16587 (if (equal nval value)
16588 (error "Only one allowed value for this property"))
16589 (org-at-property-p)
16590 (replace-match (concat " :" key ": " nval) t t)
16591 (org-indent-line-function)
16592 (beginning-of-line 1)
16593 (skip-chars-forward " \t")))
16595 (defun org-find-entry-with-id (ident)
16596 "Locate the entry that contains the ID property with exact value IDENT.
16597 IDENT can be a string, a symbol or a number, this function will search for
16598 the string representation of it.
16599 Return the position where this entry starts, or nil if there is no such entry."
16600 (let ((id (cond
16601 ((stringp ident) ident)
16602 ((symbol-name ident) (symbol-name ident))
16603 ((numberp ident) (number-to-string ident))
16604 (t (error "IDENT %s must be a string, symbol or number" ident))))
16605 (case-fold-search nil))
16606 (save-excursion
16607 (save-restriction
16608 (widen)
16609 (goto-char (point-min))
16610 (when (re-search-forward
16611 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16612 nil t)
16613 (org-back-to-heading)
16614 (point))))))
16616 ;;; Column View
16618 (defvar org-columns-overlays nil
16619 "Holds the list of current column overlays.")
16621 (defvar org-columns-current-fmt nil
16622 "Local variable, holds the currently active column format.")
16623 (defvar org-columns-current-fmt-compiled nil
16624 "Local variable, holds the currently active column format.
16625 This is the compiled version of the format.")
16626 (defvar org-columns-current-widths nil
16627 "Loval variable, holds the currently widths of fields.")
16628 (defvar org-columns-current-maxwidths nil
16629 "Loval variable, holds the currently active maximum column widths.")
16630 (defvar org-columns-begin-marker (make-marker)
16631 "Points to the position where last a column creation command was called.")
16632 (defvar org-columns-top-level-marker (make-marker)
16633 "Points to the position where current columns region starts.")
16635 (defvar org-columns-map (make-sparse-keymap)
16636 "The keymap valid in column display.")
16638 (defun org-columns-content ()
16639 "Switch to contents view while in columns view."
16640 (interactive)
16641 (org-overview)
16642 (org-content))
16644 (org-defkey org-columns-map "c" 'org-columns-content)
16645 (org-defkey org-columns-map "o" 'org-overview)
16646 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16647 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16648 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16649 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16650 (org-defkey org-columns-map "v" 'org-columns-show-value)
16651 (org-defkey org-columns-map "q" 'org-columns-quit)
16652 (org-defkey org-columns-map "r" 'org-columns-redo)
16653 (org-defkey org-columns-map "g" 'org-columns-redo)
16654 (org-defkey org-columns-map [left] 'backward-char)
16655 (org-defkey org-columns-map "\M-b" 'backward-char)
16656 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16657 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16658 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16659 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16660 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16661 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16662 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16663 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16664 (org-defkey org-columns-map "<" 'org-columns-narrow)
16665 (org-defkey org-columns-map ">" 'org-columns-widen)
16666 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16667 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16668 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16669 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16671 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16672 '("Column"
16673 ["Edit property" org-columns-edit-value t]
16674 ["Next allowed value" org-columns-next-allowed-value t]
16675 ["Previous allowed value" org-columns-previous-allowed-value t]
16676 ["Show full value" org-columns-show-value t]
16677 ["Edit allowed values" org-columns-edit-allowed t]
16678 "--"
16679 ["Edit column attributes" org-columns-edit-attributes t]
16680 ["Increase column width" org-columns-widen t]
16681 ["Decrease column width" org-columns-narrow t]
16682 "--"
16683 ["Move column right" org-columns-move-right t]
16684 ["Move column left" org-columns-move-left t]
16685 ["Add column" org-columns-new t]
16686 ["Delete column" org-columns-delete t]
16687 "--"
16688 ["CONTENTS" org-columns-content t]
16689 ["OVERVIEW" org-overview t]
16690 ["Refresh columns display" org-columns-redo t]
16691 "--"
16692 ["Open link" org-columns-open-link t]
16693 "--"
16694 ["Quit" org-columns-quit t]))
16696 (defun org-columns-new-overlay (beg end &optional string face)
16697 "Create a new column overlay and add it to the list."
16698 (let ((ov (org-make-overlay beg end)))
16699 (org-overlay-put ov 'face (or face 'secondary-selection))
16700 (org-overlay-display ov string face)
16701 (push ov org-columns-overlays)
16702 ov))
16704 (defun org-columns-display-here (&optional props)
16705 "Overlay the current line with column display."
16706 (interactive)
16707 (let* ((fmt org-columns-current-fmt-compiled)
16708 (beg (point-at-bol))
16709 (level-face (save-excursion
16710 (beginning-of-line 1)
16711 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16712 (org-get-level-face 2))))
16713 (color (list :foreground
16714 (face-attribute (or level-face 'default) :foreground)))
16715 props pom property ass width f string ov column val modval)
16716 ;; Check if the entry is in another buffer.
16717 (unless props
16718 (if (eq major-mode 'org-agenda-mode)
16719 (setq pom (or (get-text-property (point) 'org-hd-marker)
16720 (get-text-property (point) 'org-marker))
16721 props (if pom (org-entry-properties pom) nil))
16722 (setq props (org-entry-properties nil))))
16723 ;; Walk the format
16724 (while (setq column (pop fmt))
16725 (setq property (car column)
16726 ass (if (equal property "ITEM")
16727 (cons "ITEM"
16728 (save-match-data
16729 (org-no-properties
16730 (org-remove-tabs
16731 (buffer-substring-no-properties
16732 (point-at-bol) (point-at-eol))))))
16733 (assoc property props))
16734 width (or (cdr (assoc property org-columns-current-maxwidths))
16735 (nth 2 column)
16736 (length property))
16737 f (format "%%-%d.%ds | " width width)
16738 val (or (cdr ass) "")
16739 modval (if (equal property "ITEM")
16740 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16741 string (format f (or modval val)))
16742 ;; Create the overlay
16743 (org-unmodified
16744 (setq ov (org-columns-new-overlay
16745 beg (setq beg (1+ beg)) string
16746 (list color 'org-column)))
16747 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16748 (org-overlay-put ov 'keymap org-columns-map)
16749 (org-overlay-put ov 'org-columns-key property)
16750 (org-overlay-put ov 'org-columns-value (cdr ass))
16751 (org-overlay-put ov 'org-columns-value-modified modval)
16752 (org-overlay-put ov 'org-columns-pom pom)
16753 (org-overlay-put ov 'org-columns-format f))
16754 (if (or (not (char-after beg))
16755 (equal (char-after beg) ?\n))
16756 (let ((inhibit-read-only t))
16757 (save-excursion
16758 (goto-char beg)
16759 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16760 ;; Make the rest of the line disappear.
16761 (org-unmodified
16762 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16763 (org-overlay-put ov 'invisible t)
16764 (org-overlay-put ov 'keymap org-columns-map)
16765 (org-overlay-put ov 'intangible t)
16766 (push ov org-columns-overlays)
16767 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16768 (org-overlay-put ov 'keymap org-columns-map)
16769 (push ov org-columns-overlays)
16770 (let ((inhibit-read-only t))
16771 (put-text-property (max (point-min) (1- (point-at-bol)))
16772 (min (point-max) (1+ (point-at-eol)))
16773 'read-only "Type `e' to edit property")))))
16775 (defvar org-previous-header-line-format nil
16776 "The header line format before column view was turned on.")
16777 (defvar org-columns-inhibit-recalculation nil
16778 "Inhibit recomputing of columns on column view startup.")
16781 (defvar header-line-format)
16782 (defun org-columns-display-here-title ()
16783 "Overlay the newline before the current line with the table title."
16784 (interactive)
16785 (let ((fmt org-columns-current-fmt-compiled)
16786 string (title "")
16787 property width f column str widths)
16788 (while (setq column (pop fmt))
16789 (setq property (car column)
16790 str (or (nth 1 column) property)
16791 width (or (cdr (assoc property org-columns-current-maxwidths))
16792 (nth 2 column)
16793 (length str))
16794 widths (push width widths)
16795 f (format "%%-%d.%ds | " width width)
16796 string (format f str)
16797 title (concat title string)))
16798 (setq title (concat
16799 (org-add-props " " nil 'display '(space :align-to 0))
16800 (org-add-props title nil 'face '(:weight bold :underline t))))
16801 (org-set-local 'org-previous-header-line-format header-line-format)
16802 (org-set-local 'org-columns-current-widths (nreverse widths))
16803 (setq header-line-format title)))
16805 (defun org-columns-remove-overlays ()
16806 "Remove all currently active column overlays."
16807 (interactive)
16808 (when (marker-buffer org-columns-begin-marker)
16809 (with-current-buffer (marker-buffer org-columns-begin-marker)
16810 (when (local-variable-p 'org-previous-header-line-format)
16811 (setq header-line-format org-previous-header-line-format)
16812 (kill-local-variable 'org-previous-header-line-format))
16813 (move-marker org-columns-begin-marker nil)
16814 (move-marker org-columns-top-level-marker nil)
16815 (org-unmodified
16816 (mapc 'org-delete-overlay org-columns-overlays)
16817 (setq org-columns-overlays nil)
16818 (let ((inhibit-read-only t))
16819 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16821 (defun org-columns-cleanup-item (item fmt)
16822 "Remove from ITEM what is a column in the format FMT."
16823 (if (not org-complex-heading-regexp)
16824 item
16825 (when (string-match org-complex-heading-regexp item)
16826 (concat
16827 (org-add-props (concat (match-string 1 item) " ") nil
16828 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16829 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16830 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16831 " " (match-string 4 item)
16832 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16834 (defun org-columns-show-value ()
16835 "Show the full value of the property."
16836 (interactive)
16837 (let ((value (get-char-property (point) 'org-columns-value)))
16838 (message "Value is: %s" (or value ""))))
16840 (defun org-columns-quit ()
16841 "Remove the column overlays and in this way exit column editing."
16842 (interactive)
16843 (org-unmodified
16844 (org-columns-remove-overlays)
16845 (let ((inhibit-read-only t))
16846 (remove-text-properties (point-min) (point-max) '(read-only t))))
16847 (when (eq major-mode 'org-agenda-mode)
16848 (message
16849 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16851 (defun org-columns-check-computed ()
16852 "Check if this column value is computed.
16853 If yes, throw an error indicating that changing it does not make sense."
16854 (let ((val (get-char-property (point) 'org-columns-value)))
16855 (when (and (stringp val)
16856 (get-char-property 0 'org-computed val))
16857 (error "This value is computed from the entry's children"))))
16859 (defun org-columns-todo (&optional arg)
16860 "Change the TODO state during column view."
16861 (interactive "P")
16862 (org-columns-edit-value "TODO"))
16864 (defun org-columns-set-tags-or-toggle (&optional arg)
16865 "Toggle checkbox at point, or set tags for current headline."
16866 (interactive "P")
16867 (if (string-match "\\`\\[[ xX-]\\]\\'"
16868 (get-char-property (point) 'org-columns-value))
16869 (org-columns-next-allowed-value)
16870 (org-columns-edit-value "TAGS")))
16872 (defun org-columns-edit-value (&optional key)
16873 "Edit the value of the property at point in column view.
16874 Where possible, use the standard interface for changing this line."
16875 (interactive)
16876 (org-columns-check-computed)
16877 (let* ((external-key key)
16878 (col (current-column))
16879 (key (or key (get-char-property (point) 'org-columns-key)))
16880 (value (get-char-property (point) 'org-columns-value))
16881 (bol (point-at-bol)) (eol (point-at-eol))
16882 (pom (or (get-text-property bol 'org-hd-marker)
16883 (point))) ; keep despite of compiler waring
16884 (line-overlays
16885 (delq nil (mapcar (lambda (x)
16886 (and (eq (overlay-buffer x) (current-buffer))
16887 (>= (overlay-start x) bol)
16888 (<= (overlay-start x) eol)
16890 org-columns-overlays)))
16891 nval eval allowed)
16892 (cond
16893 ((equal key "CLOCKSUM")
16894 (error "This special column cannot be edited"))
16895 ((equal key "ITEM")
16896 (setq eval '(org-with-point-at pom
16897 (org-edit-headline))))
16898 ((equal key "TODO")
16899 (setq eval '(org-with-point-at pom
16900 (let ((current-prefix-arg
16901 (if external-key current-prefix-arg '(4))))
16902 (call-interactively 'org-todo)))))
16903 ((equal key "PRIORITY")
16904 (setq eval '(org-with-point-at pom
16905 (call-interactively 'org-priority))))
16906 ((equal key "TAGS")
16907 (setq eval '(org-with-point-at pom
16908 (let ((org-fast-tag-selection-single-key
16909 (if (eq org-fast-tag-selection-single-key 'expert)
16910 t org-fast-tag-selection-single-key)))
16911 (call-interactively 'org-set-tags)))))
16912 ((equal key "DEADLINE")
16913 (setq eval '(org-with-point-at pom
16914 (call-interactively 'org-deadline))))
16915 ((equal key "SCHEDULED")
16916 (setq eval '(org-with-point-at pom
16917 (call-interactively 'org-schedule))))
16919 (setq allowed (org-property-get-allowed-values pom key 'table))
16920 (if allowed
16921 (setq nval (completing-read "Value: " allowed nil t))
16922 (setq nval (read-string "Edit: " value)))
16923 (setq nval (org-trim nval))
16924 (when (not (equal nval value))
16925 (setq eval '(org-entry-put pom key nval)))))
16926 (when eval
16927 (let ((inhibit-read-only t))
16928 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
16929 (unwind-protect
16930 (progn
16931 (setq org-columns-overlays
16932 (org-delete-all line-overlays org-columns-overlays))
16933 (mapc 'org-delete-overlay line-overlays)
16934 (org-columns-eval eval))
16935 (org-columns-display-here))))
16936 (move-to-column col)
16937 (if (and (org-mode-p)
16938 (nth 3 (assoc key org-columns-current-fmt-compiled)))
16939 (org-columns-update key))))
16941 (defun org-edit-headline () ; FIXME: this is not columns specific
16942 "Edit the current headline, the part without TODO keyword, TAGS."
16943 (org-back-to-heading)
16944 (when (looking-at org-todo-line-regexp)
16945 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
16946 (txt (match-string 3))
16947 (post "")
16948 txt2)
16949 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
16950 (setq post (match-string 0 txt)
16951 txt (substring txt 0 (match-beginning 0))))
16952 (setq txt2 (read-string "Edit: " txt))
16953 (when (not (equal txt txt2))
16954 (beginning-of-line 1)
16955 (insert pre txt2 post)
16956 (delete-region (point) (point-at-eol))
16957 (org-set-tags nil t)))))
16959 (defun org-columns-edit-allowed ()
16960 "Edit the list of allowed values for the current property."
16961 (interactive)
16962 (let* ((key (get-char-property (point) 'org-columns-key))
16963 (key1 (concat key "_ALL"))
16964 (allowed (org-entry-get (point) key1 t))
16965 nval)
16966 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
16967 (setq nval (read-string "Allowed: " allowed))
16968 (org-entry-put
16969 (cond ((marker-position org-entry-property-inherited-from)
16970 org-entry-property-inherited-from)
16971 ((marker-position org-columns-top-level-marker)
16972 org-columns-top-level-marker))
16973 key1 nval)))
16975 (defmacro org-no-warnings (&rest body)
16976 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
16978 (defun org-columns-eval (form)
16979 (let (hidep)
16980 (save-excursion
16981 (beginning-of-line 1)
16982 ;; `next-line' is needed here, because it skips invisible line.
16983 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
16984 (setq hidep (org-on-heading-p 1)))
16985 (eval form)
16986 (and hidep (hide-entry))))
16988 (defun org-columns-previous-allowed-value ()
16989 "Switch to the previous allowed value for this column."
16990 (interactive)
16991 (org-columns-next-allowed-value t))
16993 (defun org-columns-next-allowed-value (&optional previous)
16994 "Switch to the next allowed value for this column."
16995 (interactive)
16996 (org-columns-check-computed)
16997 (let* ((col (current-column))
16998 (key (get-char-property (point) 'org-columns-key))
16999 (value (get-char-property (point) 'org-columns-value))
17000 (bol (point-at-bol)) (eol (point-at-eol))
17001 (pom (or (get-text-property bol 'org-hd-marker)
17002 (point))) ; keep despite of compiler waring
17003 (line-overlays
17004 (delq nil (mapcar (lambda (x)
17005 (and (eq (overlay-buffer x) (current-buffer))
17006 (>= (overlay-start x) bol)
17007 (<= (overlay-start x) eol)
17009 org-columns-overlays)))
17010 (allowed (or (org-property-get-allowed-values pom key)
17011 (and (memq
17012 (nth 4 (assoc key org-columns-current-fmt-compiled))
17013 '(checkbox checkbox-n-of-m checkbox-percent))
17014 '("[ ]" "[X]"))))
17015 nval)
17016 (when (equal key "ITEM")
17017 (error "Cannot edit item headline from here"))
17018 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17019 (error "Allowed values for this property have not been defined"))
17020 (if (member key '("SCHEDULED" "DEADLINE"))
17021 (setq nval (if previous 'earlier 'later))
17022 (if previous (setq allowed (reverse allowed)))
17023 (if (member value allowed)
17024 (setq nval (car (cdr (member value allowed)))))
17025 (setq nval (or nval (car allowed)))
17026 (if (equal nval value)
17027 (error "Only one allowed value for this property")))
17028 (let ((inhibit-read-only t))
17029 (remove-text-properties (1- bol) eol '(read-only t))
17030 (unwind-protect
17031 (progn
17032 (setq org-columns-overlays
17033 (org-delete-all line-overlays org-columns-overlays))
17034 (mapc 'org-delete-overlay line-overlays)
17035 (org-columns-eval '(org-entry-put pom key nval)))
17036 (org-columns-display-here)))
17037 (move-to-column col)
17038 (if (and (org-mode-p)
17039 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17040 (org-columns-update key))))
17042 (defun org-verify-version (task)
17043 (cond
17044 ((eq task 'columns)
17045 (if (or (featurep 'xemacs)
17046 (< emacs-major-version 22))
17047 (error "Emacs 22 is required for the columns feature")))))
17049 (defun org-columns-open-link (&optional arg)
17050 (interactive "P")
17051 (let ((value (get-char-property (point) 'org-columns-value)))
17052 (org-open-link-from-string value arg)))
17054 (defun org-open-link-from-string (s &optional arg)
17055 "Open a link in the string S, as if it was in Org-mode."
17056 (interactive)
17057 (with-temp-buffer
17058 (let ((org-inhibit-startup t))
17059 (org-mode)
17060 (insert s)
17061 (goto-char (point-min))
17062 (org-open-at-point arg))))
17064 (defun org-columns-get-format-and-top-level ()
17065 (let (fmt)
17066 (when (condition-case nil (org-back-to-heading) (error nil))
17067 (move-marker org-entry-property-inherited-from nil)
17068 (setq fmt (org-entry-get nil "COLUMNS" t)))
17069 (setq fmt (or fmt org-columns-default-format))
17070 (org-set-local 'org-columns-current-fmt fmt)
17071 (org-columns-compile-format fmt)
17072 (if (marker-position org-entry-property-inherited-from)
17073 (move-marker org-columns-top-level-marker
17074 org-entry-property-inherited-from)
17075 (move-marker org-columns-top-level-marker (point)))
17076 fmt))
17078 (defun org-columns ()
17079 "Turn on column view on an org-mode file."
17080 (interactive)
17081 (org-verify-version 'columns)
17082 (org-columns-remove-overlays)
17083 (move-marker org-columns-begin-marker (point))
17084 (let (beg end fmt cache maxwidths)
17085 (setq fmt (org-columns-get-format-and-top-level))
17086 (save-excursion
17087 (goto-char org-columns-top-level-marker)
17088 (setq beg (point))
17089 (unless org-columns-inhibit-recalculation
17090 (org-columns-compute-all))
17091 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17092 (point-max)))
17093 ;; Get and cache the properties
17094 (goto-char beg)
17095 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17096 (save-excursion
17097 (save-restriction
17098 (narrow-to-region beg end)
17099 (org-clock-sum))))
17100 (while (re-search-forward (concat "^" outline-regexp) end t)
17101 (push (cons (org-current-line) (org-entry-properties)) cache))
17102 (when cache
17103 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17104 (org-set-local 'org-columns-current-maxwidths maxwidths)
17105 (org-columns-display-here-title)
17106 (mapc (lambda (x)
17107 (goto-line (car x))
17108 (org-columns-display-here (cdr x)))
17109 cache)))))
17111 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17112 "Insert a new column, to the leeft o the current column."
17113 (interactive)
17114 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17115 cell)
17116 (setq prop (completing-read
17117 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17118 nil nil prop))
17119 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17120 (setq width (read-string "Column width: " (if width (number-to-string width))))
17121 (if (string-match "\\S-" width)
17122 (setq width (string-to-number width))
17123 (setq width nil))
17124 (setq fmt (completing-read "Summary [none]: "
17125 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17126 nil t))
17127 (if (string-match "\\S-" fmt)
17128 (setq fmt (intern fmt))
17129 (setq fmt nil))
17130 (if (eq fmt 'none) (setq fmt nil))
17131 (if editp
17132 (progn
17133 (setcar editp prop)
17134 (setcdr editp (list title width nil fmt)))
17135 (setq cell (nthcdr (1- (current-column))
17136 org-columns-current-fmt-compiled))
17137 (setcdr cell (cons (list prop title width nil fmt)
17138 (cdr cell))))
17139 (org-columns-store-format)
17140 (org-columns-redo)))
17142 (defun org-columns-delete ()
17143 "Delete the column at point from columns view."
17144 (interactive)
17145 (let* ((n (current-column))
17146 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17147 (when (y-or-n-p
17148 (format "Are you sure you want to remove column \"%s\"? " title))
17149 (setq org-columns-current-fmt-compiled
17150 (delq (nth n org-columns-current-fmt-compiled)
17151 org-columns-current-fmt-compiled))
17152 (org-columns-store-format)
17153 (org-columns-redo)
17154 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17155 (backward-char 1)))))
17157 (defun org-columns-edit-attributes ()
17158 "Edit the attributes of the current column."
17159 (interactive)
17160 (let* ((n (current-column))
17161 (info (nth n org-columns-current-fmt-compiled)))
17162 (apply 'org-columns-new info)))
17164 (defun org-columns-widen (arg)
17165 "Make the column wider by ARG characters."
17166 (interactive "p")
17167 (let* ((n (current-column))
17168 (entry (nth n org-columns-current-fmt-compiled))
17169 (width (or (nth 2 entry)
17170 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17171 (setq width (max 1 (+ width arg)))
17172 (setcar (nthcdr 2 entry) width)
17173 (org-columns-store-format)
17174 (org-columns-redo)))
17176 (defun org-columns-narrow (arg)
17177 "Make the column nrrower by ARG characters."
17178 (interactive "p")
17179 (org-columns-widen (- arg)))
17181 (defun org-columns-move-right ()
17182 "Swap this column with the one to the right."
17183 (interactive)
17184 (let* ((n (current-column))
17185 (cell (nthcdr n org-columns-current-fmt-compiled))
17187 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17188 (error "Cannot shift this column further to the right"))
17189 (setq e (car cell))
17190 (setcar cell (car (cdr cell)))
17191 (setcdr cell (cons e (cdr (cdr cell))))
17192 (org-columns-store-format)
17193 (org-columns-redo)
17194 (forward-char 1)))
17196 (defun org-columns-move-left ()
17197 "Swap this column with the one to the left."
17198 (interactive)
17199 (let* ((n (current-column)))
17200 (when (= n 0)
17201 (error "Cannot shift this column further to the left"))
17202 (backward-char 1)
17203 (org-columns-move-right)
17204 (backward-char 1)))
17206 (defun org-columns-store-format ()
17207 "Store the text version of the current columns format in appropriate place.
17208 This is either in the COLUMNS property of the node starting the current column
17209 display, or in the #+COLUMNS line of the current buffer."
17210 (let (fmt (cnt 0))
17211 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17212 (org-set-local 'org-columns-current-fmt fmt)
17213 (if (marker-position org-columns-top-level-marker)
17214 (save-excursion
17215 (goto-char org-columns-top-level-marker)
17216 (if (and (org-at-heading-p)
17217 (org-entry-get nil "COLUMNS"))
17218 (org-entry-put nil "COLUMNS" fmt)
17219 (goto-char (point-min))
17220 ;; Overwrite all #+COLUMNS lines....
17221 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17222 (setq cnt (1+ cnt))
17223 (replace-match (concat "#+COLUMNS: " fmt) t t))
17224 (unless (> cnt 0)
17225 (goto-char (point-min))
17226 (or (org-on-heading-p t) (outline-next-heading))
17227 (let ((inhibit-read-only t))
17228 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17229 (org-set-local 'org-columns-default-format fmt))))))
17231 (defvar org-overriding-columns-format nil
17232 "When set, overrides any other definition.")
17233 (defvar org-agenda-view-columns-initially nil
17234 "When set, switch to columns view immediately after creating the agenda.")
17236 (defun org-agenda-columns ()
17237 "Turn on column view in the agenda."
17238 (interactive)
17239 (org-verify-version 'columns)
17240 (org-columns-remove-overlays)
17241 (move-marker org-columns-begin-marker (point))
17242 (let (fmt cache maxwidths m)
17243 (cond
17244 ((and (local-variable-p 'org-overriding-columns-format)
17245 org-overriding-columns-format)
17246 (setq fmt org-overriding-columns-format))
17247 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17248 (setq fmt (org-entry-get m "COLUMNS" t)))
17249 ((and (boundp 'org-columns-current-fmt)
17250 (local-variable-p 'org-columns-current-fmt)
17251 org-columns-current-fmt)
17252 (setq fmt org-columns-current-fmt))
17253 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17254 (setq m (get-text-property m 'org-hd-marker))
17255 (setq fmt (org-entry-get m "COLUMNS" t))))
17256 (setq fmt (or fmt org-columns-default-format))
17257 (org-set-local 'org-columns-current-fmt fmt)
17258 (org-columns-compile-format fmt)
17259 (save-excursion
17260 ;; Get and cache the properties
17261 (goto-char (point-min))
17262 (while (not (eobp))
17263 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17264 (get-text-property (point) 'org-marker)))
17265 (push (cons (org-current-line) (org-entry-properties m)) cache))
17266 (beginning-of-line 2))
17267 (when cache
17268 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17269 (org-set-local 'org-columns-current-maxwidths maxwidths)
17270 (org-columns-display-here-title)
17271 (mapc (lambda (x)
17272 (goto-line (car x))
17273 (org-columns-display-here (cdr x)))
17274 cache)))))
17276 (defun org-columns-get-autowidth-alist (s cache)
17277 "Derive the maximum column widths from the format and the cache."
17278 (let ((start 0) rtn)
17279 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17280 (push (cons (match-string 1 s) 1) rtn)
17281 (setq start (match-end 0)))
17282 (mapc (lambda (x)
17283 (setcdr x (apply 'max
17284 (mapcar
17285 (lambda (y)
17286 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17287 cache))))
17288 rtn)
17289 rtn))
17291 (defun org-columns-compute-all ()
17292 "Compute all columns that have operators defined."
17293 (org-unmodified
17294 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17295 (let ((columns org-columns-current-fmt-compiled) col)
17296 (while (setq col (pop columns))
17297 (when (nth 3 col)
17298 (save-excursion
17299 (org-columns-compute (car col)))))))
17301 (defun org-columns-update (property)
17302 "Recompute PROPERTY, and update the columns display for it."
17303 (org-columns-compute property)
17304 (let (fmt val pos)
17305 (save-excursion
17306 (mapc (lambda (ov)
17307 (when (equal (org-overlay-get ov 'org-columns-key) property)
17308 (setq pos (org-overlay-start ov))
17309 (goto-char pos)
17310 (when (setq val (cdr (assoc property
17311 (get-text-property
17312 (point-at-bol) 'org-summaries))))
17313 (setq fmt (org-overlay-get ov 'org-columns-format))
17314 (org-overlay-put ov 'org-columns-value val)
17315 (org-overlay-put ov 'display (format fmt val)))))
17316 org-columns-overlays))))
17318 (defun org-columns-compute (property)
17319 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17320 (interactive)
17321 (let* ((re (concat "^" outline-regexp))
17322 (lmax 30) ; Does anyone use deeper levels???
17323 (lsum (make-vector lmax 0))
17324 (lflag (make-vector lmax nil))
17325 (level 0)
17326 (ass (assoc property org-columns-current-fmt-compiled))
17327 (format (nth 4 ass))
17328 (printf (nth 5 ass))
17329 (beg org-columns-top-level-marker)
17330 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17331 (save-excursion
17332 ;; Find the region to compute
17333 (goto-char beg)
17334 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17335 (goto-char end)
17336 ;; Walk the tree from the back and do the computations
17337 (while (re-search-backward re beg t)
17338 (setq sumpos (match-beginning 0)
17339 last-level level
17340 level (org-outline-level)
17341 val (org-entry-get nil property)
17342 valflag (and val (string-match "\\S-" val)))
17343 (cond
17344 ((< level last-level)
17345 ;; put the sum of lower levels here as a property
17346 (setq sum (aref lsum last-level) ; current sum
17347 flag (aref lflag last-level) ; any valid entries from children?
17348 str (org-column-number-to-string sum format printf)
17349 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17350 useval (if flag str1 (if valflag val ""))
17351 sum-alist (get-text-property sumpos 'org-summaries))
17352 (if (assoc property sum-alist)
17353 (setcdr (assoc property sum-alist) useval)
17354 (push (cons property useval) sum-alist)
17355 (org-unmodified
17356 (add-text-properties sumpos (1+ sumpos)
17357 (list 'org-summaries sum-alist))))
17358 (when val
17359 (org-entry-put nil property (if flag str val)))
17360 ;; add current to current level accumulator
17361 (when (or flag valflag)
17362 (aset lsum level (+ (aref lsum level)
17363 (if flag sum (org-column-string-to-number
17364 (if flag str val) format))))
17365 (aset lflag level t))
17366 ;; clear accumulators for deeper levels
17367 (loop for l from (1+ level) to (1- lmax) do
17368 (aset lsum l 0)
17369 (aset lflag l nil)))
17370 ((>= level last-level)
17371 ;; add what we have here to the accumulator for this level
17372 (aset lsum level (+ (aref lsum level)
17373 (org-column-string-to-number (or val "0") format)))
17374 (and valflag (aset lflag level t)))
17375 (t (error "This should not happen")))))))
17377 (defun org-columns-redo ()
17378 "Construct the column display again."
17379 (interactive)
17380 (message "Recomputing columns...")
17381 (save-excursion
17382 (if (marker-position org-columns-begin-marker)
17383 (goto-char org-columns-begin-marker))
17384 (org-columns-remove-overlays)
17385 (if (org-mode-p)
17386 (call-interactively 'org-columns)
17387 (call-interactively 'org-agenda-columns)))
17388 (message "Recomputing columns...done"))
17390 (defun org-columns-not-in-agenda ()
17391 (if (eq major-mode 'org-agenda-mode)
17392 (error "This command is only allowed in Org-mode buffers")))
17395 (defun org-string-to-number (s)
17396 "Convert string to number, and interpret hh:mm:ss."
17397 (if (not (string-match ":" s))
17398 (string-to-number s)
17399 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17400 (while l
17401 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17402 sum)))
17404 (defun org-column-number-to-string (n fmt &optional printf)
17405 "Convert a computed column number to a string value, according to FMT."
17406 (cond
17407 ((eq fmt 'add_times)
17408 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17409 (format "%d:%02d" h m)))
17410 ((eq fmt 'checkbox)
17411 (cond ((= n (floor n)) "[X]")
17412 ((> n 1.) "[-]")
17413 (t "[ ]")))
17414 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17415 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17416 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17417 (printf (format printf n))
17418 ((eq fmt 'currency)
17419 (format "%.2f" n))
17420 (t (number-to-string n))))
17422 (defun org-nofm-to-completion (n m &optional percent)
17423 (if (not percent)
17424 (format "[%d/%d]" n m)
17425 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17427 (defun org-column-string-to-number (s fmt)
17428 "Convert a column value to a number that can be used for column computing."
17429 (cond
17430 ((string-match ":" s)
17431 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17432 (while l
17433 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17434 sum))
17435 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17436 (if (equal s "[X]") 1. 0.000001))
17437 (t (string-to-number s))))
17439 (defun org-columns-uncompile-format (cfmt)
17440 "Turn the compiled columns format back into a string representation."
17441 (let ((rtn "") e s prop title op width fmt printf)
17442 (while (setq e (pop cfmt))
17443 (setq prop (car e)
17444 title (nth 1 e)
17445 width (nth 2 e)
17446 op (nth 3 e)
17447 fmt (nth 4 e)
17448 printf (nth 5 e))
17449 (cond
17450 ((eq fmt 'add_times) (setq op ":"))
17451 ((eq fmt 'checkbox) (setq op "X"))
17452 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17453 ((eq fmt 'checkbox-percent) (setq op "X%"))
17454 ((eq fmt 'add_numbers) (setq op "+"))
17455 ((eq fmt 'currency) (setq op "$")))
17456 (if (and op printf) (setq op (concat op ";" printf)))
17457 (if (equal title prop) (setq title nil))
17458 (setq s (concat "%" (if width (number-to-string width))
17459 prop
17460 (if title (concat "(" title ")"))
17461 (if op (concat "{" op "}"))))
17462 (setq rtn (concat rtn " " s)))
17463 (org-trim rtn)))
17465 (defun org-columns-compile-format (fmt)
17466 "Turn a column format string into an alist of specifications.
17467 The alist has one entry for each column in the format. The elements of
17468 that list are:
17469 property the property
17470 title the title field for the columns
17471 width the column width in characters, can be nil for automatic
17472 operator the operator if any
17473 format the output format for computed results, derived from operator
17474 printf a printf format for computed values"
17475 (let ((start 0) width prop title op f printf)
17476 (setq org-columns-current-fmt-compiled nil)
17477 (while (string-match
17478 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17479 fmt start)
17480 (setq start (match-end 0)
17481 width (match-string 1 fmt)
17482 prop (match-string 2 fmt)
17483 title (or (match-string 3 fmt) prop)
17484 op (match-string 4 fmt)
17485 f nil
17486 printf nil)
17487 (if width (setq width (string-to-number width)))
17488 (when (and op (string-match ";" op))
17489 (setq printf (substring op (match-end 0))
17490 op (substring op 0 (match-beginning 0))))
17491 (cond
17492 ((equal op "+") (setq f 'add_numbers))
17493 ((equal op "$") (setq f 'currency))
17494 ((equal op ":") (setq f 'add_times))
17495 ((equal op "X") (setq f 'checkbox))
17496 ((equal op "X/") (setq f 'checkbox-n-of-m))
17497 ((equal op "X%") (setq f 'checkbox-percent))
17499 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17500 (setq org-columns-current-fmt-compiled
17501 (nreverse org-columns-current-fmt-compiled))))
17504 ;;; Dynamic block for Column view
17506 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17507 "Get the column view of the current buffer or subtree.
17508 The first optional argument MAXLEVEL sets the level limit. A
17509 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17510 empty rows, an empty row being one where all the column view
17511 specifiers except ITEM are empty. This function returns a list
17512 containing the title row and all other rows. Each row is a list
17513 of fields."
17514 (save-excursion
17515 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17516 (n (length title)) row tbl)
17517 (goto-char (point-min))
17518 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17519 (or (null maxlevel)
17520 (>= maxlevel
17521 (if org-odd-levels-only
17522 (/ (1+ (length (match-string 1))) 2)
17523 (length (match-string 1))))))
17524 (when (get-char-property (match-beginning 0) 'org-columns-key)
17525 (setq row nil)
17526 (loop for i from 0 to (1- n) do
17527 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17528 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17530 row))
17531 (setq row (nreverse row))
17532 (unless (and skip-empty-rows
17533 (eq 1 (length (delete "" (delete-dups row)))))
17534 (push row tbl))))
17535 (append (list title 'hline) (nreverse tbl)))))
17537 (defun org-dblock-write:columnview (params)
17538 "Write the column view table.
17539 PARAMS is a property list of parameters:
17541 :width enforce same column widths with <N> specifiers.
17542 :id the :ID: property of the entry where the columns view
17543 should be built, as a string. When `local', call locally.
17544 When `global' call column view with the cursor at the beginning
17545 of the buffer (usually this means that the whole buffer switches
17546 to column view).
17547 :hlines When t, insert a hline before each item. When a number, insert
17548 a hline before each level <= that number.
17549 :vlines When t, make each column a colgroup to enforce vertical lines.
17550 :maxlevel When set to a number, don't capture headlines below this level.
17551 :skip-empty-rows
17552 When t, skip rows where all specifiers other than ITEM are empty."
17553 (let ((pos (move-marker (make-marker) (point)))
17554 (hlines (plist-get params :hlines))
17555 (vlines (plist-get params :vlines))
17556 (maxlevel (plist-get params :maxlevel))
17557 (skip-empty-rows (plist-get params :skip-empty-rows))
17558 tbl id idpos nfields tmp)
17559 (save-excursion
17560 (save-restriction
17561 (when (setq id (plist-get params :id))
17562 (cond ((not id) nil)
17563 ((eq id 'global) (goto-char (point-min)))
17564 ((eq id 'local) nil)
17565 ((setq idpos (org-find-entry-with-id id))
17566 (goto-char idpos))
17567 (t (error "Cannot find entry with :ID: %s" id))))
17568 (org-columns)
17569 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17570 (setq nfields (length (car tbl)))
17571 (org-columns-quit)))
17572 (goto-char pos)
17573 (move-marker pos nil)
17574 (when tbl
17575 (when (plist-get params :hlines)
17576 (setq tmp nil)
17577 (while tbl
17578 (if (eq (car tbl) 'hline)
17579 (push (pop tbl) tmp)
17580 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17581 (if (and (not (eq (car tmp) 'hline))
17582 (or (eq hlines t)
17583 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17584 (push 'hline tmp)))
17585 (push (pop tbl) tmp)))
17586 (setq tbl (nreverse tmp)))
17587 (when vlines
17588 (setq tbl (mapcar (lambda (x)
17589 (if (eq 'hline x) x (cons "" x)))
17590 tbl))
17591 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17592 (setq pos (point))
17593 (insert (org-listtable-to-string tbl))
17594 (when (plist-get params :width)
17595 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17596 org-columns-current-widths "|")))
17597 (goto-char pos)
17598 (org-table-align))))
17600 (defun org-listtable-to-string (tbl)
17601 "Convert a listtable TBL to a string that contains the Org-mode table.
17602 The table still need to be alligned. The resulting string has no leading
17603 and tailing newline characters."
17604 (mapconcat
17605 (lambda (x)
17606 (cond
17607 ((listp x)
17608 (concat "|" (mapconcat 'identity x "|") "|"))
17609 ((eq x 'hline) "|-|")
17610 (t (error "Garbage in listtable: %s" x))))
17611 tbl "\n"))
17613 (defun org-insert-columns-dblock ()
17614 "Create a dynamic block capturing a column view table."
17615 (interactive)
17616 (let ((defaults '(:name "columnview" :hlines 1))
17617 (id (completing-read
17618 "Capture columns (local, global, entry with :ID: property) [local]: "
17619 (append '(("global") ("local"))
17620 (mapcar 'list (org-property-values "ID"))))))
17621 (if (equal id "") (setq id 'local))
17622 (if (equal id "global") (setq id 'global))
17623 (setq defaults (append defaults (list :id id)))
17624 (org-create-dblock defaults)
17625 (org-update-dblock)))
17627 ;;;; Timestamps
17629 (defvar org-last-changed-timestamp nil)
17630 (defvar org-time-was-given) ; dynamically scoped parameter
17631 (defvar org-end-time-was-given) ; dynamically scoped parameter
17632 (defvar org-ts-what) ; dynamically scoped parameter
17634 (defun org-time-stamp (arg)
17635 "Prompt for a date/time and insert a time stamp.
17636 If the user specifies a time like HH:MM, or if this command is called
17637 with a prefix argument, the time stamp will contain date and time.
17638 Otherwise, only the date will be included. All parts of a date not
17639 specified by the user will be filled in from the current date/time.
17640 So if you press just return without typing anything, the time stamp
17641 will represent the current date/time. If there is already a timestamp
17642 at the cursor, it will be modified."
17643 (interactive "P")
17644 (let* ((ts nil)
17645 (default-time
17646 ;; Default time is either today, or, when entering a range,
17647 ;; the range start.
17648 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17649 (save-excursion
17650 (re-search-backward
17651 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17652 (- (point) 20) t)))
17653 (apply 'encode-time (org-parse-time-string (match-string 1)))
17654 (current-time)))
17655 (default-input (and ts (org-get-compact-tod ts)))
17656 org-time-was-given org-end-time-was-given time)
17657 (cond
17658 ((and (org-at-timestamp-p)
17659 (eq last-command 'org-time-stamp)
17660 (eq this-command 'org-time-stamp))
17661 (insert "--")
17662 (setq time (let ((this-command this-command))
17663 (org-read-date arg 'totime nil nil default-time default-input)))
17664 (org-insert-time-stamp time (or org-time-was-given arg)))
17665 ((org-at-timestamp-p)
17666 (setq time (let ((this-command this-command))
17667 (org-read-date arg 'totime nil nil default-time default-input)))
17668 (when (org-at-timestamp-p) ; just to get the match data
17669 (replace-match "")
17670 (setq org-last-changed-timestamp
17671 (org-insert-time-stamp
17672 time (or org-time-was-given arg)
17673 nil nil nil (list org-end-time-was-given))))
17674 (message "Timestamp updated"))
17676 (setq time (let ((this-command this-command))
17677 (org-read-date arg 'totime nil nil default-time default-input)))
17678 (org-insert-time-stamp time (or org-time-was-given arg)
17679 nil nil nil (list org-end-time-was-given))))))
17681 ;; FIXME: can we use this for something else????
17682 ;; like computing time differences?????
17683 (defun org-get-compact-tod (s)
17684 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17685 (let* ((t1 (match-string 1 s))
17686 (h1 (string-to-number (match-string 2 s)))
17687 (m1 (string-to-number (match-string 3 s)))
17688 (t2 (and (match-end 4) (match-string 5 s)))
17689 (h2 (and t2 (string-to-number (match-string 6 s))))
17690 (m2 (and t2 (string-to-number (match-string 7 s))))
17691 dh dm)
17692 (if (not t2)
17694 (setq dh (- h2 h1) dm (- m2 m1))
17695 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17696 (concat t1 "+" (number-to-string dh)
17697 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17699 (defun org-time-stamp-inactive (&optional arg)
17700 "Insert an inactive time stamp.
17701 An inactive time stamp is enclosed in square brackets instead of angle
17702 brackets. It is inactive in the sense that it does not trigger agenda entries,
17703 does not link to the calendar and cannot be changed with the S-cursor keys.
17704 So these are more for recording a certain time/date."
17705 (interactive "P")
17706 (let (org-time-was-given org-end-time-was-given time)
17707 (setq time (org-read-date arg 'totime))
17708 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17709 nil nil (list org-end-time-was-given))))
17711 (defvar org-date-ovl (org-make-overlay 1 1))
17712 (org-overlay-put org-date-ovl 'face 'org-warning)
17713 (org-detach-overlay org-date-ovl)
17715 (defvar org-ans1) ; dynamically scoped parameter
17716 (defvar org-ans2) ; dynamically scoped parameter
17718 (defvar org-plain-time-of-day-regexp) ; defined below
17720 (defvar org-read-date-overlay nil)
17721 (defvar org-dcst nil) ; dynamically scoped
17723 (defun org-read-date (&optional with-time to-time from-string prompt
17724 default-time default-input)
17725 "Read a date, possibly a time, and make things smooth for the user.
17726 The prompt will suggest to enter an ISO date, but you can also enter anything
17727 which will at least partially be understood by `parse-time-string'.
17728 Unrecognized parts of the date will default to the current day, month, year,
17729 hour and minute. If this command is called to replace a timestamp at point,
17730 of to enter the second timestamp of a range, the default time is taken from the
17731 existing stamp. For example,
17732 3-2-5 --> 2003-02-05
17733 feb 15 --> currentyear-02-15
17734 sep 12 9 --> 2009-09-12
17735 12:45 --> today 12:45
17736 22 sept 0:34 --> currentyear-09-22 0:34
17737 12 --> currentyear-currentmonth-12
17738 Fri --> nearest Friday (today or later)
17739 etc.
17741 Furthermore you can specify a relative date by giving, as the *first* thing
17742 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17743 change in days weeks, months, years.
17744 With a single plus or minus, the date is relative to today. With a double
17745 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17746 +4d --> four days from today
17747 +4 --> same as above
17748 +2w --> two weeks from today
17749 ++5 --> five days from default date
17751 The function understands only English month and weekday abbreviations,
17752 but this can be configured with the variables `parse-time-months' and
17753 `parse-time-weekdays'.
17755 While prompting, a calendar is popped up - you can also select the
17756 date with the mouse (button 1). The calendar shows a period of three
17757 months. To scroll it to other months, use the keys `>' and `<'.
17758 If you don't like the calendar, turn it off with
17759 \(setq org-read-date-popup-calendar nil)
17761 With optional argument TO-TIME, the date will immediately be converted
17762 to an internal time.
17763 With an optional argument WITH-TIME, the prompt will suggest to also
17764 insert a time. Note that when WITH-TIME is not set, you can still
17765 enter a time, and this function will inform the calling routine about
17766 this change. The calling routine may then choose to change the format
17767 used to insert the time stamp into the buffer to include the time.
17768 With optional argument FROM-STRING, read from this string instead from
17769 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17770 the time/date that is used for everything that is not specified by the
17771 user."
17772 (require 'parse-time)
17773 (let* ((org-time-stamp-rounding-minutes
17774 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17775 (org-dcst org-display-custom-times)
17776 (ct (org-current-time))
17777 (def (or default-time ct))
17778 (defdecode (decode-time def))
17779 (dummy (progn
17780 (when (< (nth 2 defdecode) org-extend-today-until)
17781 (setcar (nthcdr 2 defdecode) -1)
17782 (setcar (nthcdr 1 defdecode) 59)
17783 (setq def (apply 'encode-time defdecode)
17784 defdecode (decode-time def)))))
17785 (calendar-move-hook nil)
17786 (view-diary-entries-initially nil)
17787 (view-calendar-holidays-initially nil)
17788 (timestr (format-time-string
17789 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17790 (prompt (concat (if prompt (concat prompt " ") "")
17791 (format "Date+time [%s]: " timestr)))
17792 ans (org-ans0 "") org-ans1 org-ans2 final)
17794 (cond
17795 (from-string (setq ans from-string))
17796 (org-read-date-popup-calendar
17797 (save-excursion
17798 (save-window-excursion
17799 (calendar)
17800 (calendar-forward-day (- (time-to-days def)
17801 (calendar-absolute-from-gregorian
17802 (calendar-current-date))))
17803 (org-eval-in-calendar nil t)
17804 (let* ((old-map (current-local-map))
17805 (map (copy-keymap calendar-mode-map))
17806 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17807 (org-defkey map (kbd "RET") 'org-calendar-select)
17808 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17809 'org-calendar-select-mouse)
17810 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17811 'org-calendar-select-mouse)
17812 (org-defkey minibuffer-local-map [(meta shift left)]
17813 (lambda () (interactive)
17814 (org-eval-in-calendar '(calendar-backward-month 1))))
17815 (org-defkey minibuffer-local-map [(meta shift right)]
17816 (lambda () (interactive)
17817 (org-eval-in-calendar '(calendar-forward-month 1))))
17818 (org-defkey minibuffer-local-map [(meta shift up)]
17819 (lambda () (interactive)
17820 (org-eval-in-calendar '(calendar-backward-year 1))))
17821 (org-defkey minibuffer-local-map [(meta shift down)]
17822 (lambda () (interactive)
17823 (org-eval-in-calendar '(calendar-forward-year 1))))
17824 (org-defkey minibuffer-local-map [(shift up)]
17825 (lambda () (interactive)
17826 (org-eval-in-calendar '(calendar-backward-week 1))))
17827 (org-defkey minibuffer-local-map [(shift down)]
17828 (lambda () (interactive)
17829 (org-eval-in-calendar '(calendar-forward-week 1))))
17830 (org-defkey minibuffer-local-map [(shift left)]
17831 (lambda () (interactive)
17832 (org-eval-in-calendar '(calendar-backward-day 1))))
17833 (org-defkey minibuffer-local-map [(shift right)]
17834 (lambda () (interactive)
17835 (org-eval-in-calendar '(calendar-forward-day 1))))
17836 (org-defkey minibuffer-local-map ">"
17837 (lambda () (interactive)
17838 (org-eval-in-calendar '(scroll-calendar-left 1))))
17839 (org-defkey minibuffer-local-map "<"
17840 (lambda () (interactive)
17841 (org-eval-in-calendar '(scroll-calendar-right 1))))
17842 (unwind-protect
17843 (progn
17844 (use-local-map map)
17845 (add-hook 'post-command-hook 'org-read-date-display)
17846 (setq org-ans0 (read-string prompt default-input nil nil))
17847 ;; org-ans0: from prompt
17848 ;; org-ans1: from mouse click
17849 ;; org-ans2: from calendar motion
17850 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17851 (remove-hook 'post-command-hook 'org-read-date-display)
17852 (use-local-map old-map)
17853 (when org-read-date-overlay
17854 (org-delete-overlay org-read-date-overlay)
17855 (setq org-read-date-overlay nil)))))))
17857 (t ; Naked prompt only
17858 (unwind-protect
17859 (setq ans (read-string prompt default-input nil timestr))
17860 (when org-read-date-overlay
17861 (org-delete-overlay org-read-date-overlay)
17862 (setq org-read-date-overlay nil)))))
17864 (setq final (org-read-date-analyze ans def defdecode))
17866 (if to-time
17867 (apply 'encode-time final)
17868 (if (and (boundp 'org-time-was-given) org-time-was-given)
17869 (format "%04d-%02d-%02d %02d:%02d"
17870 (nth 5 final) (nth 4 final) (nth 3 final)
17871 (nth 2 final) (nth 1 final))
17872 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17873 (defvar def)
17874 (defvar defdecode)
17875 (defvar with-time)
17876 (defun org-read-date-display ()
17877 "Display the currrent date prompt interpretation in the minibuffer."
17878 (when org-read-date-display-live
17879 (when org-read-date-overlay
17880 (org-delete-overlay org-read-date-overlay))
17881 (let ((p (point)))
17882 (end-of-line 1)
17883 (while (not (equal (buffer-substring
17884 (max (point-min) (- (point) 4)) (point))
17885 " "))
17886 (insert " "))
17887 (goto-char p))
17888 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17889 " " (or org-ans1 org-ans2)))
17890 (org-end-time-was-given nil)
17891 (f (org-read-date-analyze ans def defdecode))
17892 (fmts (if org-dcst
17893 org-time-stamp-custom-formats
17894 org-time-stamp-formats))
17895 (fmt (if (or with-time
17896 (and (boundp 'org-time-was-given) org-time-was-given))
17897 (cdr fmts)
17898 (car fmts)))
17899 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
17900 (when (and org-end-time-was-given
17901 (string-match org-plain-time-of-day-regexp txt))
17902 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17903 org-end-time-was-given
17904 (substring txt (match-end 0)))))
17905 (setq org-read-date-overlay
17906 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17907 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
17909 (defun org-read-date-analyze (ans def defdecode)
17910 "Analyze the combined answer of the date prompt."
17911 ;; FIXME: cleanup and comment
17912 (let (delta deltan deltaw deltadef year month day
17913 hour minute second wday pm h2 m2 tl wday1)
17915 (when (setq delta (org-read-date-get-relative ans (current-time) def))
17916 (setq ans (replace-match "" t t ans)
17917 deltan (car delta)
17918 deltaw (nth 1 delta)
17919 deltadef (nth 2 delta)))
17921 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
17922 (when (string-match
17923 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17924 (setq year (if (match-end 2)
17925 (string-to-number (match-string 2 ans))
17926 (string-to-number (format-time-string "%Y")))
17927 month (string-to-number (match-string 3 ans))
17928 day (string-to-number (match-string 4 ans)))
17929 (if (< year 100) (setq year (+ 2000 year)))
17930 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17931 t nil ans)))
17932 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17933 ;; If there is a time with am/pm, and *no* time without it, we convert
17934 ;; so that matching will be successful.
17935 (loop for i from 1 to 2 do ; twice, for end time as well
17936 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17937 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17938 (setq hour (string-to-number (match-string 1 ans))
17939 minute (if (match-end 3)
17940 (string-to-number (match-string 3 ans))
17942 pm (equal ?p
17943 (string-to-char (downcase (match-string 4 ans)))))
17944 (if (and (= hour 12) (not pm))
17945 (setq hour 0)
17946 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
17947 (setq ans (replace-match (format "%02d:%02d" hour minute)
17948 t t ans))))
17950 ;; Check if a time range is given as a duration
17951 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17952 (setq hour (string-to-number (match-string 1 ans))
17953 h2 (+ hour (string-to-number (match-string 3 ans)))
17954 minute (string-to-number (match-string 2 ans))
17955 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
17956 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17957 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
17959 ;; Check if there is a time range
17960 (when (boundp 'org-end-time-was-given)
17961 (setq org-time-was-given nil)
17962 (when (and (string-match org-plain-time-of-day-regexp ans)
17963 (match-end 8))
17964 (setq org-end-time-was-given (match-string 8 ans))
17965 (setq ans (concat (substring ans 0 (match-beginning 7))
17966 (substring ans (match-end 7))))))
17968 (setq tl (parse-time-string ans)
17969 day (or (nth 3 tl) (nth 3 defdecode))
17970 month (or (nth 4 tl)
17971 (if (and org-read-date-prefer-future
17972 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
17973 (1+ (nth 4 defdecode))
17974 (nth 4 defdecode)))
17975 year (or (nth 5 tl)
17976 (if (and org-read-date-prefer-future
17977 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
17978 (1+ (nth 5 defdecode))
17979 (nth 5 defdecode)))
17980 hour (or (nth 2 tl) (nth 2 defdecode))
17981 minute (or (nth 1 tl) (nth 1 defdecode))
17982 second (or (nth 0 tl) 0)
17983 wday (nth 6 tl))
17984 (when deltan
17985 (unless deltadef
17986 (let ((now (decode-time (current-time))))
17987 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17988 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17989 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17990 ((equal deltaw "m") (setq month (+ month deltan)))
17991 ((equal deltaw "y") (setq year (+ year deltan)))))
17992 (when (and wday (not (nth 3 tl)))
17993 ;; Weekday was given, but no day, so pick that day in the week
17994 ;; on or after the derived date.
17995 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17996 (unless (equal wday wday1)
17997 (setq day (+ day (% (- wday wday1 -7) 7)))))
17998 (if (and (boundp 'org-time-was-given)
17999 (nth 2 tl))
18000 (setq org-time-was-given t))
18001 (if (< year 100) (setq year (+ 2000 year)))
18002 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18003 (list second minute hour day month year)))
18005 (defvar parse-time-weekdays)
18007 (defun org-read-date-get-relative (s today default)
18008 "Check string S for special relative date string.
18009 TODAY and DEFAULT are internal times, for today and for a default.
18010 Return shift list (N what def-flag)
18011 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18012 N is the number of WHATs to shift.
18013 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18014 the DEFAULT date rather than TODAY."
18015 (when (string-match
18016 (concat
18017 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18018 "\\([0-9]+\\)?"
18019 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18020 "\\([ \t]\\|$\\)") s)
18021 (let* ((dir (if (match-end 1)
18022 (string-to-char (substring (match-string 1 s) -1))
18023 ?+))
18024 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18025 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18026 (what (if (match-end 3) (match-string 3 s) "d"))
18027 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18028 (date (if rel default today))
18029 (wday (nth 6 (decode-time date)))
18030 delta)
18031 (if wday1
18032 (progn
18033 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18034 (if (= dir ?-) (setq delta (- delta 7)))
18035 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18036 (list delta "d" rel))
18037 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18039 (defun org-eval-in-calendar (form &optional keepdate)
18040 "Eval FORM in the calendar window and return to current window.
18041 Also, store the cursor date in variable org-ans2."
18042 (let ((sw (selected-window)))
18043 (select-window (get-buffer-window "*Calendar*"))
18044 (eval form)
18045 (when (and (not keepdate) (calendar-cursor-to-date))
18046 (let* ((date (calendar-cursor-to-date))
18047 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18048 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18049 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18050 (select-window sw)))
18052 ; ;; Update the prompt to show new default date
18053 ; (save-excursion
18054 ; (goto-char (point-min))
18055 ; (when (and org-ans2
18056 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18057 ; (get-text-property (match-end 0) 'field))
18058 ; (let ((inhibit-read-only t))
18059 ; (replace-match (concat "[" org-ans2 "]") t t)
18060 ; (add-text-properties (point-min) (1+ (match-end 0))
18061 ; (text-properties-at (1+ (point-min)))))))))
18063 (defun org-calendar-select ()
18064 "Return to `org-read-date' with the date currently selected.
18065 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18066 (interactive)
18067 (when (calendar-cursor-to-date)
18068 (let* ((date (calendar-cursor-to-date))
18069 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18070 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18071 (if (active-minibuffer-window) (exit-minibuffer))))
18073 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18074 "Insert a date stamp for the date given by the internal TIME.
18075 WITH-HM means, use the stamp format that includes the time of the day.
18076 INACTIVE means use square brackets instead of angular ones, so that the
18077 stamp will not contribute to the agenda.
18078 PRE and POST are optional strings to be inserted before and after the
18079 stamp.
18080 The command returns the inserted time stamp."
18081 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18082 stamp)
18083 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18084 (insert-before-markers (or pre ""))
18085 (insert-before-markers (setq stamp (format-time-string fmt time)))
18086 (when (listp extra)
18087 (setq extra (car extra))
18088 (if (and (stringp extra)
18089 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18090 (setq extra (format "-%02d:%02d"
18091 (string-to-number (match-string 1 extra))
18092 (string-to-number (match-string 2 extra))))
18093 (setq extra nil)))
18094 (when extra
18095 (backward-char 1)
18096 (insert-before-markers extra)
18097 (forward-char 1))
18098 (insert-before-markers (or post ""))
18099 stamp))
18101 (defun org-toggle-time-stamp-overlays ()
18102 "Toggle the use of custom time stamp formats."
18103 (interactive)
18104 (setq org-display-custom-times (not org-display-custom-times))
18105 (unless org-display-custom-times
18106 (let ((p (point-min)) (bmp (buffer-modified-p)))
18107 (while (setq p (next-single-property-change p 'display))
18108 (if (and (get-text-property p 'display)
18109 (eq (get-text-property p 'face) 'org-date))
18110 (remove-text-properties
18111 p (setq p (next-single-property-change p 'display))
18112 '(display t))))
18113 (set-buffer-modified-p bmp)))
18114 (if (featurep 'xemacs)
18115 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18116 (org-restart-font-lock)
18117 (setq org-table-may-need-update t)
18118 (if org-display-custom-times
18119 (message "Time stamps are overlayed with custom format")
18120 (message "Time stamp overlays removed")))
18122 (defun org-display-custom-time (beg end)
18123 "Overlay modified time stamp format over timestamp between BED and END."
18124 (let* ((ts (buffer-substring beg end))
18125 t1 w1 with-hm tf time str w2 (off 0))
18126 (save-match-data
18127 (setq t1 (org-parse-time-string ts t))
18128 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( \\+[0-9]+[dwmy]\\)?\\'" ts)
18129 (setq off (- (match-end 0) (match-beginning 0)))))
18130 (setq end (- end off))
18131 (setq w1 (- end beg)
18132 with-hm (and (nth 1 t1) (nth 2 t1))
18133 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18134 time (org-fix-decoded-time t1)
18135 str (org-add-props
18136 (format-time-string
18137 (substring tf 1 -1) (apply 'encode-time time))
18138 nil 'mouse-face 'highlight)
18139 w2 (length str))
18140 (if (not (= w2 w1))
18141 (add-text-properties (1+ beg) (+ 2 beg)
18142 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18143 (if (featurep 'xemacs)
18144 (progn
18145 (put-text-property beg end 'invisible t)
18146 (put-text-property beg end 'end-glyph (make-glyph str)))
18147 (put-text-property beg end 'display str))))
18149 (defun org-translate-time (string)
18150 "Translate all timestamps in STRING to custom format.
18151 But do this only if the variable `org-display-custom-times' is set."
18152 (when org-display-custom-times
18153 (save-match-data
18154 (let* ((start 0)
18155 (re org-ts-regexp-both)
18156 t1 with-hm inactive tf time str beg end)
18157 (while (setq start (string-match re string start))
18158 (setq beg (match-beginning 0)
18159 end (match-end 0)
18160 t1 (save-match-data
18161 (org-parse-time-string (substring string beg end) t))
18162 with-hm (and (nth 1 t1) (nth 2 t1))
18163 inactive (equal (substring string beg (1+ beg)) "[")
18164 tf (funcall (if with-hm 'cdr 'car)
18165 org-time-stamp-custom-formats)
18166 time (org-fix-decoded-time t1)
18167 str (format-time-string
18168 (concat
18169 (if inactive "[" "<") (substring tf 1 -1)
18170 (if inactive "]" ">"))
18171 (apply 'encode-time time))
18172 string (replace-match str t t string)
18173 start (+ start (length str)))))))
18174 string)
18176 (defun org-fix-decoded-time (time)
18177 "Set 0 instead of nil for the first 6 elements of time.
18178 Don't touch the rest."
18179 (let ((n 0))
18180 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18182 (defun org-days-to-time (timestamp-string)
18183 "Difference between TIMESTAMP-STRING and now in days."
18184 (- (time-to-days (org-time-string-to-time timestamp-string))
18185 (time-to-days (current-time))))
18187 (defun org-deadline-close (timestamp-string &optional ndays)
18188 "Is the time in TIMESTAMP-STRING close to the current date?"
18189 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18190 (and (< (org-days-to-time timestamp-string) ndays)
18191 (not (org-entry-is-done-p))))
18193 (defun org-get-wdays (ts)
18194 "Get the deadline lead time appropriate for timestring TS."
18195 (cond
18196 ((<= org-deadline-warning-days 0)
18197 ;; 0 or negative, enforce this value no matter what
18198 (- org-deadline-warning-days))
18199 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18200 ;; lead time is specified.
18201 (floor (* (string-to-number (match-string 1 ts))
18202 (cdr (assoc (match-string 2 ts)
18203 '(("d" . 1) ("w" . 7)
18204 ("m" . 30.4) ("y" . 365.25)))))))
18205 ;; go for the default.
18206 (t org-deadline-warning-days)))
18208 (defun org-calendar-select-mouse (ev)
18209 "Return to `org-read-date' with the date currently selected.
18210 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18211 (interactive "e")
18212 (mouse-set-point ev)
18213 (when (calendar-cursor-to-date)
18214 (let* ((date (calendar-cursor-to-date))
18215 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18216 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18217 (if (active-minibuffer-window) (exit-minibuffer))))
18219 (defun org-check-deadlines (ndays)
18220 "Check if there are any deadlines due or past due.
18221 A deadline is considered due if it happens within `org-deadline-warning-days'
18222 days from today's date. If the deadline appears in an entry marked DONE,
18223 it is not shown. The prefix arg NDAYS can be used to test that many
18224 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18225 (interactive "P")
18226 (let* ((org-warn-days
18227 (cond
18228 ((equal ndays '(4)) 100000)
18229 (ndays (prefix-numeric-value ndays))
18230 (t (abs org-deadline-warning-days))))
18231 (case-fold-search nil)
18232 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18233 (callback
18234 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18236 (message "%d deadlines past-due or due within %d days"
18237 (org-occur regexp nil callback)
18238 org-warn-days)))
18240 (defun org-check-before-date (date)
18241 "Check if there are deadlines or scheduled entries before DATE."
18242 (interactive (list (org-read-date)))
18243 (let ((case-fold-search nil)
18244 (regexp (concat "\\<\\(" org-deadline-string
18245 "\\|" org-scheduled-string
18246 "\\) *<\\([^>]+\\)>"))
18247 (callback
18248 (lambda () (time-less-p
18249 (org-time-string-to-time (match-string 2))
18250 (org-time-string-to-time date)))))
18251 (message "%d entries before %s"
18252 (org-occur regexp nil callback) date)))
18254 (defun org-evaluate-time-range (&optional to-buffer)
18255 "Evaluate a time range by computing the difference between start and end.
18256 Normally the result is just printed in the echo area, but with prefix arg
18257 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18258 If the time range is actually in a table, the result is inserted into the
18259 next column.
18260 For time difference computation, a year is assumed to be exactly 365
18261 days in order to avoid rounding problems."
18262 (interactive "P")
18264 (org-clock-update-time-maybe)
18265 (save-excursion
18266 (unless (org-at-date-range-p t)
18267 (goto-char (point-at-bol))
18268 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18269 (if (not (org-at-date-range-p t))
18270 (error "Not at a time-stamp range, and none found in current line")))
18271 (let* ((ts1 (match-string 1))
18272 (ts2 (match-string 2))
18273 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18274 (match-end (match-end 0))
18275 (time1 (org-time-string-to-time ts1))
18276 (time2 (org-time-string-to-time ts2))
18277 (t1 (time-to-seconds time1))
18278 (t2 (time-to-seconds time2))
18279 (diff (abs (- t2 t1)))
18280 (negative (< (- t2 t1) 0))
18281 ;; (ys (floor (* 365 24 60 60)))
18282 (ds (* 24 60 60))
18283 (hs (* 60 60))
18284 (fy "%dy %dd %02d:%02d")
18285 (fy1 "%dy %dd")
18286 (fd "%dd %02d:%02d")
18287 (fd1 "%dd")
18288 (fh "%02d:%02d")
18289 y d h m align)
18290 (if havetime
18291 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18293 d (floor (/ diff ds)) diff (mod diff ds)
18294 h (floor (/ diff hs)) diff (mod diff hs)
18295 m (floor (/ diff 60)))
18296 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18298 d (floor (+ (/ diff ds) 0.5))
18299 h 0 m 0))
18300 (if (not to-buffer)
18301 (message "%s" (org-make-tdiff-string y d h m))
18302 (if (org-at-table-p)
18303 (progn
18304 (goto-char match-end)
18305 (setq align t)
18306 (and (looking-at " *|") (goto-char (match-end 0))))
18307 (goto-char match-end))
18308 (if (looking-at
18309 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18310 (replace-match ""))
18311 (if negative (insert " -"))
18312 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18313 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18314 (insert " " (format fh h m))))
18315 (if align (org-table-align))
18316 (message "Time difference inserted")))))
18318 (defun org-make-tdiff-string (y d h m)
18319 (let ((fmt "")
18320 (l nil))
18321 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18322 l (push y l)))
18323 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18324 l (push d l)))
18325 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18326 l (push h l)))
18327 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18328 l (push m l)))
18329 (apply 'format fmt (nreverse l))))
18331 (defun org-time-string-to-time (s)
18332 (apply 'encode-time (org-parse-time-string s)))
18334 (defun org-time-string-to-absolute (s &optional daynr prefer)
18335 "Convert a time stamp to an absolute day number.
18336 If there is a specifyer for a cyclic time stamp, get the closest date to
18337 DAYNR."
18338 (cond
18339 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18340 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18341 daynr
18342 (+ daynr 1000)))
18343 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18344 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18345 (time-to-days (current-time))) (match-string 0 s)
18346 prefer))
18347 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18349 (defun org-time-from-absolute (d)
18350 "Return the time corresponding to date D.
18351 D may be an absolute day number, or a calendar-type list (month day year)."
18352 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18353 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18355 (defun org-calendar-holiday ()
18356 "List of holidays, for Diary display in Org-mode."
18357 (require 'holidays)
18358 (let ((hl (funcall
18359 (if (fboundp 'calendar-check-holidays)
18360 'calendar-check-holidays 'check-calendar-holidays) date)))
18361 (if hl (mapconcat 'identity hl "; "))))
18363 (defun org-diary-sexp-entry (sexp entry date)
18364 "Process a SEXP diary ENTRY for DATE."
18365 (require 'diary-lib)
18366 (let ((result (if calendar-debug-sexp
18367 (let ((stack-trace-on-error t))
18368 (eval (car (read-from-string sexp))))
18369 (condition-case nil
18370 (eval (car (read-from-string sexp)))
18371 (error
18372 (beep)
18373 (message "Bad sexp at line %d in %s: %s"
18374 (org-current-line)
18375 (buffer-file-name) sexp)
18376 (sleep-for 2))))))
18377 (cond ((stringp result) result)
18378 ((and (consp result)
18379 (stringp (cdr result))) (cdr result))
18380 (result entry)
18381 (t nil))))
18383 (defun org-diary-to-ical-string (frombuf)
18384 "Get iCalendar entries from diary entries in buffer FROMBUF.
18385 This uses the icalendar.el library."
18386 (let* ((tmpdir (if (featurep 'xemacs)
18387 (temp-directory)
18388 temporary-file-directory))
18389 (tmpfile (make-temp-name
18390 (expand-file-name "orgics" tmpdir)))
18391 buf rtn b e)
18392 (save-excursion
18393 (set-buffer frombuf)
18394 (icalendar-export-region (point-min) (point-max) tmpfile)
18395 (setq buf (find-buffer-visiting tmpfile))
18396 (set-buffer buf)
18397 (goto-char (point-min))
18398 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18399 (setq b (match-beginning 0)))
18400 (goto-char (point-max))
18401 (if (re-search-backward "^END:VEVENT" nil t)
18402 (setq e (match-end 0)))
18403 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18404 (kill-buffer buf)
18405 (kill-buffer frombuf)
18406 (delete-file tmpfile)
18407 rtn))
18409 (defun org-closest-date (start current change prefer)
18410 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18411 When PREFER is `past' return a date that is either CURRENT or past.
18412 When PREFER is `future', return a date that is either CURRENT or future."
18413 ;; Make the proper lists from the dates
18414 (catch 'exit
18415 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18416 dn dw sday cday n1 n2
18417 d m y y1 y2 date1 date2 nmonths nm ny m2)
18419 (setq start (org-date-to-gregorian start)
18420 current (org-date-to-gregorian
18421 (if org-agenda-repeating-timestamp-show-all
18422 current
18423 (time-to-days (current-time))))
18424 sday (calendar-absolute-from-gregorian start)
18425 cday (calendar-absolute-from-gregorian current))
18427 (if (<= cday sday) (throw 'exit sday))
18429 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18430 (setq dn (string-to-number (match-string 1 change))
18431 dw (cdr (assoc (match-string 2 change) a1)))
18432 (error "Invalid change specifyer: %s" change))
18433 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18434 (cond
18435 ((eq dw 'day)
18436 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18437 n2 (+ n1 dn)))
18438 ((eq dw 'year)
18439 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18440 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18441 (setq date1 (list m d y1)
18442 n1 (calendar-absolute-from-gregorian date1)
18443 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18444 n2 (calendar-absolute-from-gregorian date2)))
18445 ((eq dw 'month)
18446 ;; approx number of month between the tow dates
18447 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18448 ;; How often does dn fit in there?
18449 (setq d (nth 1 start) m (car start) y (nth 2 start)
18450 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18451 m (+ m nm)
18452 ny (floor (/ m 12))
18453 y (+ y ny)
18454 m (- m (* ny 12)))
18455 (while (> m 12) (setq m (- m 12) y (1+ y)))
18456 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18457 (setq m2 (+ m dn) y2 y)
18458 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18459 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18460 (while (< n2 cday)
18461 (setq n1 n2 m m2 y y2)
18462 (setq m2 (+ m dn) y2 y)
18463 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18464 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18466 (if org-agenda-repeating-timestamp-show-all
18467 (cond
18468 ((eq prefer 'past) n1)
18469 ((eq prefer 'future) (if (= cday n1) n1 n2))
18470 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18471 (cond
18472 ((eq prefer 'past) n1)
18473 ((eq prefer 'future) (if (= cday n1) n1 n2))
18474 (t (if (= cday n1) n1 n2)))))))
18476 (defun org-date-to-gregorian (date)
18477 "Turn any specification of DATE into a gregorian date for the calendar."
18478 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18479 ((and (listp date) (= (length date) 3)) date)
18480 ((stringp date)
18481 (setq date (org-parse-time-string date))
18482 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18483 ((listp date)
18484 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18486 (defun org-parse-time-string (s &optional nodefault)
18487 "Parse the standard Org-mode time string.
18488 This should be a lot faster than the normal `parse-time-string'.
18489 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18490 hour and minute fields will be nil if not given."
18491 (if (string-match org-ts-regexp0 s)
18492 (list 0
18493 (if (or (match-beginning 8) (not nodefault))
18494 (string-to-number (or (match-string 8 s) "0")))
18495 (if (or (match-beginning 7) (not nodefault))
18496 (string-to-number (or (match-string 7 s) "0")))
18497 (string-to-number (match-string 4 s))
18498 (string-to-number (match-string 3 s))
18499 (string-to-number (match-string 2 s))
18500 nil nil nil)
18501 (make-list 9 0)))
18503 (defun org-timestamp-up (&optional arg)
18504 "Increase the date item at the cursor by one.
18505 If the cursor is on the year, change the year. If it is on the month or
18506 the day, change that.
18507 With prefix ARG, change by that many units."
18508 (interactive "p")
18509 (org-timestamp-change (prefix-numeric-value arg)))
18511 (defun org-timestamp-down (&optional arg)
18512 "Decrease the date item at the cursor by one.
18513 If the cursor is on the year, change the year. If it is on the month or
18514 the day, change that.
18515 With prefix ARG, change by that many units."
18516 (interactive "p")
18517 (org-timestamp-change (- (prefix-numeric-value arg))))
18519 (defun org-timestamp-up-day (&optional arg)
18520 "Increase the date in the time stamp by one day.
18521 With prefix ARG, change that many days."
18522 (interactive "p")
18523 (if (and (not (org-at-timestamp-p t))
18524 (org-on-heading-p))
18525 (org-todo 'up)
18526 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18528 (defun org-timestamp-down-day (&optional arg)
18529 "Decrease the date in the time stamp by one day.
18530 With prefix ARG, change that many days."
18531 (interactive "p")
18532 (if (and (not (org-at-timestamp-p t))
18533 (org-on-heading-p))
18534 (org-todo 'down)
18535 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18537 (defsubst org-pos-in-match-range (pos n)
18538 (and (match-beginning n)
18539 (<= (match-beginning n) pos)
18540 (>= (match-end n) pos)))
18542 (defun org-at-timestamp-p (&optional inactive-ok)
18543 "Determine if the cursor is in or at a timestamp."
18544 (interactive)
18545 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18546 (pos (point))
18547 (ans (or (looking-at tsr)
18548 (save-excursion
18549 (skip-chars-backward "^[<\n\r\t")
18550 (if (> (point) (point-min)) (backward-char 1))
18551 (and (looking-at tsr)
18552 (> (- (match-end 0) pos) -1))))))
18553 (and ans
18554 (boundp 'org-ts-what)
18555 (setq org-ts-what
18556 (cond
18557 ((= pos (match-beginning 0)) 'bracket)
18558 ((= pos (1- (match-end 0))) 'bracket)
18559 ((org-pos-in-match-range pos 2) 'year)
18560 ((org-pos-in-match-range pos 3) 'month)
18561 ((org-pos-in-match-range pos 7) 'hour)
18562 ((org-pos-in-match-range pos 8) 'minute)
18563 ((or (org-pos-in-match-range pos 4)
18564 (org-pos-in-match-range pos 5)) 'day)
18565 ((and (> pos (or (match-end 8) (match-end 5)))
18566 (< pos (match-end 0)))
18567 (- pos (or (match-end 8) (match-end 5))))
18568 (t 'day))))
18569 ans))
18571 (defun org-toggle-timestamp-type ()
18572 "Toggle the type (<active> or [inactive]) of a time stamp."
18573 (interactive)
18574 (when (org-at-timestamp-p t)
18575 (save-excursion
18576 (goto-char (match-beginning 0))
18577 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18578 (goto-char (1- (match-end 0)))
18579 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18580 (message "Timestamp is now %sactive"
18581 (if (equal (char-before) ?>) "in" ""))))
18583 (defun org-timestamp-change (n &optional what)
18584 "Change the date in the time stamp at point.
18585 The date will be changed by N times WHAT. WHAT can be `day', `month',
18586 `year', `minute', `second'. If WHAT is not given, the cursor position
18587 in the timestamp determines what will be changed."
18588 (let ((pos (point))
18589 with-hm inactive
18590 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18591 org-ts-what
18592 extra rem
18593 ts time time0)
18594 (if (not (org-at-timestamp-p t))
18595 (error "Not at a timestamp"))
18596 (if (and (not what) (eq org-ts-what 'bracket))
18597 (org-toggle-timestamp-type)
18598 (if (and (not what) (not (eq org-ts-what 'day))
18599 org-display-custom-times
18600 (get-text-property (point) 'display)
18601 (not (get-text-property (1- (point)) 'display)))
18602 (setq org-ts-what 'day))
18603 (setq org-ts-what (or what org-ts-what)
18604 inactive (= (char-after (match-beginning 0)) ?\[)
18605 ts (match-string 0))
18606 (replace-match "")
18607 (if (string-match
18608 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( [-+][0-9]+[dwmy]\\)*\\)[]>]"
18610 (setq extra (match-string 1 ts)))
18611 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18612 (setq with-hm t))
18613 (setq time0 (org-parse-time-string ts))
18614 (when (and (eq org-ts-what 'minute)
18615 (eq current-prefix-arg nil))
18616 (setq n (* dm (org-no-warnings (signum n))))
18617 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18618 (setcar (cdr time0) (+ (nth 1 time0)
18619 (if (> n 0) (- rem) (- dm rem))))))
18620 (setq time
18621 (encode-time (or (car time0) 0)
18622 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18623 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18624 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18625 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18626 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18627 (nthcdr 6 time0)))
18628 (when (integerp org-ts-what)
18629 (setq extra (org-modify-ts-extra extra org-ts-what n)))
18630 (if (eq what 'calendar)
18631 (let ((cal-date (org-get-date-from-calendar)))
18632 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18633 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18634 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18635 (setcar time0 (or (car time0) 0))
18636 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18637 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18638 (setq time (apply 'encode-time time0))))
18639 (setq org-last-changed-timestamp
18640 (org-insert-time-stamp time with-hm inactive nil nil extra))
18641 (org-clock-update-time-maybe)
18642 (goto-char pos)
18643 ;; Try to recenter the calendar window, if any
18644 (if (and org-calendar-follow-timestamp-change
18645 (get-buffer-window "*Calendar*" t)
18646 (memq org-ts-what '(day month year)))
18647 (org-recenter-calendar (time-to-days time))))))
18649 ;; FIXME: does not yet work for lead times
18650 (defun org-modify-ts-extra (s pos n)
18651 "Change the different parts of the lead-time and repeat fields in timestamp."
18652 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18653 ng h m new)
18654 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( \\+\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18655 (cond
18656 ((or (org-pos-in-match-range pos 2)
18657 (org-pos-in-match-range pos 3))
18658 (setq m (string-to-number (match-string 3 s))
18659 h (string-to-number (match-string 2 s)))
18660 (if (org-pos-in-match-range pos 2)
18661 (setq h (+ h n))
18662 (setq m (+ m n)))
18663 (if (< m 0) (setq m (+ m 60) h (1- h)))
18664 (if (> m 59) (setq m (- m 60) h (1+ h)))
18665 (setq h (min 24 (max 0 h)))
18666 (setq ng 1 new (format "-%02d:%02d" h m)))
18667 ((org-pos-in-match-range pos 6)
18668 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18669 ((org-pos-in-match-range pos 5)
18670 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s))))))))
18672 (when ng
18673 (setq s (concat
18674 (substring s 0 (match-beginning ng))
18676 (substring s (match-end ng))))))
18679 (defun org-recenter-calendar (date)
18680 "If the calendar is visible, recenter it to DATE."
18681 (let* ((win (selected-window))
18682 (cwin (get-buffer-window "*Calendar*" t))
18683 (calendar-move-hook nil))
18684 (when cwin
18685 (select-window cwin)
18686 (calendar-goto-date (if (listp date) date
18687 (calendar-gregorian-from-absolute date)))
18688 (select-window win))))
18690 (defun org-goto-calendar (&optional arg)
18691 "Go to the Emacs calendar at the current date.
18692 If there is a time stamp in the current line, go to that date.
18693 A prefix ARG can be used to force the current date."
18694 (interactive "P")
18695 (let ((tsr org-ts-regexp) diff
18696 (calendar-move-hook nil)
18697 (view-calendar-holidays-initially nil)
18698 (view-diary-entries-initially nil))
18699 (if (or (org-at-timestamp-p)
18700 (save-excursion
18701 (beginning-of-line 1)
18702 (looking-at (concat ".*" tsr))))
18703 (let ((d1 (time-to-days (current-time)))
18704 (d2 (time-to-days
18705 (org-time-string-to-time (match-string 1)))))
18706 (setq diff (- d2 d1))))
18707 (calendar)
18708 (calendar-goto-today)
18709 (if (and diff (not arg)) (calendar-forward-day diff))))
18711 (defun org-get-date-from-calendar ()
18712 "Return a list (month day year) of date at point in calendar."
18713 (with-current-buffer "*Calendar*"
18714 (save-match-data
18715 (calendar-cursor-to-date))))
18717 (defun org-date-from-calendar ()
18718 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18719 If there is already a time stamp at the cursor position, update it."
18720 (interactive)
18721 (if (org-at-timestamp-p t)
18722 (org-timestamp-change 0 'calendar)
18723 (let ((cal-date (org-get-date-from-calendar)))
18724 (org-insert-time-stamp
18725 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18727 (defvar appt-time-msg-list)
18729 ;;;###autoload
18730 (defun org-agenda-to-appt (&optional refresh filter)
18731 "Activate appointments found in `org-agenda-files'.
18732 With a \\[universal-argument] prefix, refresh the list of
18733 appointements.
18735 If FILTER is t, interactively prompt the user for a regular
18736 expression, and filter out entries that don't match it.
18738 If FILTER is a string, use this string as a regular expression
18739 for filtering entries out.
18741 FILTER can also be an alist with the car of each cell being
18742 either 'headline or 'category. For example:
18744 '((headline \"IMPORTANT\")
18745 (category \"Work\"))
18747 will only add headlines containing IMPORTANT or headlines
18748 belonging to the \"Work\" category."
18749 (interactive "P")
18750 (require 'calendar)
18751 (if refresh (setq appt-time-msg-list nil))
18752 (if (eq filter t)
18753 (setq filter (read-from-minibuffer "Regexp filter: ")))
18754 (let* ((cnt 0) ; count added events
18755 (org-agenda-new-buffers nil)
18756 (org-deadline-warning-days 0)
18757 (today (org-date-to-gregorian
18758 (time-to-days (current-time))))
18759 (files (org-agenda-files)) entries file)
18760 ;; Get all entries which may contain an appt
18761 (while (setq file (pop files))
18762 (setq entries
18763 (append entries
18764 (org-agenda-get-day-entries
18765 file today :timestamp :scheduled :deadline))))
18766 (setq entries (delq nil entries))
18767 ;; Map thru entries and find if we should filter them out
18768 (mapc
18769 (lambda(x)
18770 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18771 (cat (get-text-property 1 'org-category x))
18772 (tod (get-text-property 1 'time-of-day x))
18773 (ok (or (null filter)
18774 (and (stringp filter) (string-match filter evt))
18775 (and (listp filter)
18776 (or (string-match
18777 (cadr (assoc 'category filter)) cat)
18778 (string-match
18779 (cadr (assoc 'headline filter)) evt))))))
18780 ;; FIXME: Shall we remove text-properties for the appt text?
18781 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18782 (when (and ok tod)
18783 (setq tod (number-to-string tod)
18784 tod (when (string-match
18785 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18786 (concat (match-string 1 tod) ":"
18787 (match-string 2 tod))))
18788 (appt-add tod evt)
18789 (setq cnt (1+ cnt))))) entries)
18790 (org-release-buffers org-agenda-new-buffers)
18791 (if (eq cnt 0)
18792 (message "No event to add")
18793 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18795 ;;; The clock for measuring work time.
18797 (defvar org-mode-line-string "")
18798 (put 'org-mode-line-string 'risky-local-variable t)
18800 (defvar org-mode-line-timer nil)
18801 (defvar org-clock-heading "")
18802 (defvar org-clock-start-time "")
18804 (defun org-update-mode-line ()
18805 (let* ((delta (- (time-to-seconds (current-time))
18806 (time-to-seconds org-clock-start-time)))
18807 (h (floor delta 3600))
18808 (m (floor (- delta (* 3600 h)) 60)))
18809 (setq org-mode-line-string
18810 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18811 'help-echo "Org-mode clock is running"))
18812 (force-mode-line-update)))
18814 (defvar org-clock-marker (make-marker)
18815 "Marker recording the last clock-in.")
18816 (defvar org-clock-mode-line-entry nil
18817 "Information for the modeline about the running clock.")
18819 (defun org-clock-in ()
18820 "Start the clock on the current item.
18821 If necessary, clock-out of the currently active clock."
18822 (interactive)
18823 (org-clock-out t)
18824 (let (ts)
18825 (save-excursion
18826 (org-back-to-heading t)
18827 (when (and org-clock-in-switch-to-state
18828 (not (looking-at (concat outline-regexp "[ \t]*"
18829 org-clock-in-switch-to-state
18830 "\\>"))))
18831 (org-todo org-clock-in-switch-to-state))
18832 (if (and org-clock-heading-function
18833 (functionp org-clock-heading-function))
18834 (setq org-clock-heading (funcall org-clock-heading-function))
18835 (if (looking-at org-complex-heading-regexp)
18836 (setq org-clock-heading (match-string 4))
18837 (setq org-clock-heading "???")))
18838 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18839 (org-clock-find-position)
18841 (insert "\n") (backward-char 1)
18842 (indent-relative)
18843 (insert org-clock-string " ")
18844 (setq org-clock-start-time (current-time))
18845 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18846 (move-marker org-clock-marker (point) (buffer-base-buffer))
18847 (or global-mode-string (setq global-mode-string '("")))
18848 (or (memq 'org-mode-line-string global-mode-string)
18849 (setq global-mode-string
18850 (append global-mode-string '(org-mode-line-string))))
18851 (org-update-mode-line)
18852 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18853 (message "Clock started at %s" ts))))
18855 (defun org-clock-find-position ()
18856 "Find the location where the next clock line should be inserted."
18857 (org-back-to-heading t)
18858 (catch 'exit
18859 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18860 (re (concat "^[ \t]*" org-clock-string))
18861 (cnt 0)
18862 first last)
18863 (goto-char beg)
18864 (when (eobp) (newline) (setq end (max (point) end)))
18865 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18866 ;; we seem to have a CLOCK drawer, so go there.
18867 (beginning-of-line 2)
18868 (throw 'exit t))
18869 ;; Lets count the CLOCK lines
18870 (goto-char beg)
18871 (while (re-search-forward re end t)
18872 (setq first (or first (match-beginning 0))
18873 last (match-beginning 0)
18874 cnt (1+ cnt)))
18875 (when (and (integerp org-clock-into-drawer)
18876 (>= (1+ cnt) org-clock-into-drawer))
18877 ;; Wrap current entries into a new drawer
18878 (goto-char last)
18879 (beginning-of-line 2)
18880 (if (org-at-item-p) (org-end-of-item))
18881 (insert ":END:\n")
18882 (beginning-of-line 0)
18883 (org-indent-line-function)
18884 (goto-char first)
18885 (insert ":CLOCK:\n")
18886 (beginning-of-line 0)
18887 (org-indent-line-function)
18888 (org-flag-drawer t)
18889 (beginning-of-line 2)
18890 (throw 'exit nil))
18892 (goto-char beg)
18893 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18894 (not (equal (match-string 1) org-clock-string)))
18895 ;; Planning info, skip to after it
18896 (beginning-of-line 2)
18897 (or (bolp) (newline)))
18898 (when (eq t org-clock-into-drawer)
18899 (insert ":CLOCK:\n:END:\n")
18900 (beginning-of-line -1)
18901 (org-indent-line-function)
18902 (org-flag-drawer t)
18903 (beginning-of-line 2)
18904 (org-indent-line-function)))))
18906 (defun org-clock-out (&optional fail-quietly)
18907 "Stop the currently running clock.
18908 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
18909 (interactive)
18910 (catch 'exit
18911 (if (not (marker-buffer org-clock-marker))
18912 (if fail-quietly (throw 'exit t) (error "No active clock")))
18913 (let (ts te s h m)
18914 (save-excursion
18915 (set-buffer (marker-buffer org-clock-marker))
18916 (goto-char org-clock-marker)
18917 (beginning-of-line 1)
18918 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
18919 (equal (match-string 1) org-clock-string))
18920 (setq ts (match-string 2))
18921 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
18922 (goto-char (match-end 0))
18923 (delete-region (point) (point-at-eol))
18924 (insert "--")
18925 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18926 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
18927 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
18928 h (floor (/ s 3600))
18929 s (- s (* 3600 h))
18930 m (floor (/ s 60))
18931 s (- s (* 60 s)))
18932 (insert " => " (format "%2d:%02d" h m))
18933 (move-marker org-clock-marker nil)
18934 (when org-log-note-clock-out
18935 (org-add-log-maybe 'clock-out))
18936 (when org-mode-line-timer
18937 (cancel-timer org-mode-line-timer)
18938 (setq org-mode-line-timer nil))
18939 (setq global-mode-string
18940 (delq 'org-mode-line-string global-mode-string))
18941 (force-mode-line-update)
18942 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
18944 (defun org-clock-cancel ()
18945 "Cancel the running clock be removing the start timestamp."
18946 (interactive)
18947 (if (not (marker-buffer org-clock-marker))
18948 (error "No active clock"))
18949 (save-excursion
18950 (set-buffer (marker-buffer org-clock-marker))
18951 (goto-char org-clock-marker)
18952 (delete-region (1- (point-at-bol)) (point-at-eol)))
18953 (setq global-mode-string
18954 (delq 'org-mode-line-string global-mode-string))
18955 (force-mode-line-update)
18956 (message "Clock canceled"))
18958 (defun org-clock-goto (&optional delete-windows)
18959 "Go to the currently clocked-in entry."
18960 (interactive "P")
18961 (if (not (marker-buffer org-clock-marker))
18962 (error "No active clock"))
18963 (switch-to-buffer-other-window
18964 (marker-buffer org-clock-marker))
18965 (if delete-windows (delete-other-windows))
18966 (goto-char org-clock-marker)
18967 (org-show-entry)
18968 (org-back-to-heading)
18969 (recenter))
18971 (defvar org-clock-file-total-minutes nil
18972 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
18973 (make-variable-buffer-local 'org-clock-file-total-minutes)
18975 (defun org-clock-sum (&optional tstart tend)
18976 "Sum the times for each subtree.
18977 Puts the resulting times in minutes as a text property on each headline."
18978 (interactive)
18979 (let* ((bmp (buffer-modified-p))
18980 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
18981 org-clock-string
18982 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
18983 (lmax 30)
18984 (ltimes (make-vector lmax 0))
18985 (t1 0)
18986 (level 0)
18987 ts te dt
18988 time)
18989 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
18990 (save-excursion
18991 (goto-char (point-max))
18992 (while (re-search-backward re nil t)
18993 (cond
18994 ((match-end 2)
18995 ;; Two time stamps
18996 (setq ts (match-string 2)
18997 te (match-string 3)
18998 ts (time-to-seconds
18999 (apply 'encode-time (org-parse-time-string ts)))
19000 te (time-to-seconds
19001 (apply 'encode-time (org-parse-time-string te)))
19002 ts (if tstart (max ts tstart) ts)
19003 te (if tend (min te tend) te)
19004 dt (- te ts)
19005 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19006 ((match-end 4)
19007 ;; A naket time
19008 (setq t1 (+ t1 (string-to-number (match-string 5))
19009 (* 60 (string-to-number (match-string 4))))))
19010 (t ;; A headline
19011 (setq level (- (match-end 1) (match-beginning 1)))
19012 (when (or (> t1 0) (> (aref ltimes level) 0))
19013 (loop for l from 0 to level do
19014 (aset ltimes l (+ (aref ltimes l) t1)))
19015 (setq t1 0 time (aref ltimes level))
19016 (loop for l from level to (1- lmax) do
19017 (aset ltimes l 0))
19018 (goto-char (match-beginning 0))
19019 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19020 (setq org-clock-file-total-minutes (aref ltimes 0)))
19021 (set-buffer-modified-p bmp)))
19023 (defun org-clock-display (&optional total-only)
19024 "Show subtree times in the entire buffer.
19025 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19026 in the echo area."
19027 (interactive)
19028 (org-remove-clock-overlays)
19029 (let (time h m p)
19030 (org-clock-sum)
19031 (unless total-only
19032 (save-excursion
19033 (goto-char (point-min))
19034 (while (or (and (equal (setq p (point)) (point-min))
19035 (get-text-property p :org-clock-minutes))
19036 (setq p (next-single-property-change
19037 (point) :org-clock-minutes)))
19038 (goto-char p)
19039 (when (setq time (get-text-property p :org-clock-minutes))
19040 (org-put-clock-overlay time (funcall outline-level))))
19041 (setq h (/ org-clock-file-total-minutes 60)
19042 m (- org-clock-file-total-minutes (* 60 h)))
19043 ;; Arrange to remove the overlays upon next change.
19044 (when org-remove-highlights-with-change
19045 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19046 nil 'local))))
19047 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19049 (defvar org-clock-overlays nil)
19050 (make-variable-buffer-local 'org-clock-overlays)
19052 (defun org-put-clock-overlay (time &optional level)
19053 "Put an overlays on the current line, displaying TIME.
19054 If LEVEL is given, prefix time with a corresponding number of stars.
19055 This creates a new overlay and stores it in `org-clock-overlays', so that it
19056 will be easy to remove."
19057 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19058 (l (if level (org-get-legal-level level 0) 0))
19059 (off 0)
19060 ov tx)
19061 (move-to-column c)
19062 (unless (eolp) (skip-chars-backward "^ \t"))
19063 (skip-chars-backward " \t")
19064 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19065 tx (concat (buffer-substring (1- (point)) (point))
19066 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19067 (org-add-props (format "%s %2d:%02d%s"
19068 (make-string l ?*) h m
19069 (make-string (- 16 l) ?\ ))
19070 '(face secondary-selection))
19071 ""))
19072 (if (not (featurep 'xemacs))
19073 (org-overlay-put ov 'display tx)
19074 (org-overlay-put ov 'invisible t)
19075 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19076 (push ov org-clock-overlays)))
19078 (defun org-remove-clock-overlays (&optional beg end noremove)
19079 "Remove the occur highlights from the buffer.
19080 BEG and END are ignored. If NOREMOVE is nil, remove this function
19081 from the `before-change-functions' in the current buffer."
19082 (interactive)
19083 (unless org-inhibit-highlight-removal
19084 (mapc 'org-delete-overlay org-clock-overlays)
19085 (setq org-clock-overlays nil)
19086 (unless noremove
19087 (remove-hook 'before-change-functions
19088 'org-remove-clock-overlays 'local))))
19090 (defun org-clock-out-if-current ()
19091 "Clock out if the current entry contains the running clock.
19092 This is used to stop the clock after a TODO entry is marked DONE,
19093 and is only done if the variable `org-clock-out-when-done' is not nil."
19094 (when (and org-clock-out-when-done
19095 (member state org-done-keywords)
19096 (equal (marker-buffer org-clock-marker) (current-buffer))
19097 (< (point) org-clock-marker)
19098 (> (save-excursion (outline-next-heading) (point))
19099 org-clock-marker))
19100 ;; Clock out, but don't accept a logging message for this.
19101 (let ((org-log-note-clock-out nil))
19102 (org-clock-out))))
19104 (add-hook 'org-after-todo-state-change-hook
19105 'org-clock-out-if-current)
19107 (defun org-check-running-clock ()
19108 "Check if the current buffer contains the running clock.
19109 If yes, offer to stop it and to save the buffer with the changes."
19110 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19111 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19112 (buffer-name))))
19113 (org-clock-out)
19114 (when (y-or-n-p "Save changed buffer?")
19115 (save-buffer))))
19117 (defun org-clock-report (&optional arg)
19118 "Create a table containing a report about clocked time.
19119 If the cursor is inside an existing clocktable block, then the table
19120 will be updated. If not, a new clocktable will be inserted.
19121 When called with a prefix argument, move to the first clock table in the
19122 buffer and update it."
19123 (interactive "P")
19124 (org-remove-clock-overlays)
19125 (when arg
19126 (org-find-dblock "clocktable")
19127 (org-show-entry))
19128 (if (org-in-clocktable-p)
19129 (goto-char (org-in-clocktable-p))
19130 (org-create-dblock (list :name "clocktable"
19131 :maxlevel 2 :scope 'file)))
19132 (org-update-dblock))
19134 (defun org-in-clocktable-p ()
19135 "Check if the cursor is in a clocktable."
19136 (let ((pos (point)) start)
19137 (save-excursion
19138 (end-of-line 1)
19139 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19140 (setq start (match-beginning 0))
19141 (re-search-forward "^#\\+END:.*" nil t)
19142 (>= (match-end 0) pos)
19143 start))))
19145 (defun org-clock-update-time-maybe ()
19146 "If this is a CLOCK line, update it and return t.
19147 Otherwise, return nil."
19148 (interactive)
19149 (save-excursion
19150 (beginning-of-line 1)
19151 (skip-chars-forward " \t")
19152 (when (looking-at org-clock-string)
19153 (let ((re (concat "[ \t]*" org-clock-string
19154 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19155 "\\([ \t]*=>.*\\)?"))
19156 ts te h m s)
19157 (if (not (looking-at re))
19159 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19160 (end-of-line 1)
19161 (setq ts (match-string 1)
19162 te (match-string 2))
19163 (setq s (- (time-to-seconds
19164 (apply 'encode-time (org-parse-time-string te)))
19165 (time-to-seconds
19166 (apply 'encode-time (org-parse-time-string ts))))
19167 h (floor (/ s 3600))
19168 s (- s (* 3600 h))
19169 m (floor (/ s 60))
19170 s (- s (* 60 s)))
19171 (insert " => " (format "%2d:%02d" h m))
19172 t)))))
19174 (defun org-clock-special-range (key &optional time as-strings)
19175 "Return two times bordering a special time range.
19176 Key is a symbol specifying the range and can be one of `today', `yesterday',
19177 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19178 A week starts Monday 0:00 and ends Sunday 24:00.
19179 The range is determined relative to TIME. TIME defaults to the current time.
19180 The return value is a cons cell with two internal times like the ones
19181 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19182 the returned times will be formatted strings."
19183 (let* ((tm (decode-time (or time (current-time))))
19184 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19185 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19186 (dow (nth 6 tm))
19187 s1 m1 h1 d1 month1 y1 diff ts te fm)
19188 (cond
19189 ((eq key 'today)
19190 (setq h 0 m 0 h1 24 m1 0))
19191 ((eq key 'yesterday)
19192 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19193 ((eq key 'thisweek)
19194 (setq diff (if (= dow 0) 6 (1- dow))
19195 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19196 ((eq key 'lastweek)
19197 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19198 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19199 ((eq key 'thismonth)
19200 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19201 ((eq key 'lastmonth)
19202 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19203 ((eq key 'thisyear)
19204 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19205 ((eq key 'lastyear)
19206 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19207 (t (error "No such time block %s" key)))
19208 (setq ts (encode-time s m h d month y)
19209 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19210 (or d1 d) (or month1 month) (or y1 y)))
19211 (setq fm (cdr org-time-stamp-formats))
19212 (if as-strings
19213 (cons (format-time-string fm ts) (format-time-string fm te))
19214 (cons ts te))))
19216 (defun org-dblock-write:clocktable (params)
19217 "Write the standard clocktable."
19218 (catch 'exit
19219 (let* ((hlchars '((1 . "*") (2 . "/")))
19220 (ins (make-marker))
19221 (total-time nil)
19222 (scope (plist-get params :scope))
19223 (tostring (plist-get params :tostring))
19224 (multifile (plist-get params :multifile))
19225 (header (plist-get params :header))
19226 (maxlevel (or (plist-get params :maxlevel) 3))
19227 (step (plist-get params :step))
19228 (emph (plist-get params :emphasize))
19229 (ts (plist-get params :tstart))
19230 (te (plist-get params :tend))
19231 (block (plist-get params :block))
19232 ipos time h m p level hlc hdl
19233 cc beg end pos tbl)
19234 (when step
19235 (org-clocktable-steps params)
19236 (throw 'exit nil))
19237 (when block
19238 (setq cc (org-clock-special-range block nil t)
19239 ts (car cc) te (cdr cc)))
19240 (if ts (setq ts (time-to-seconds
19241 (apply 'encode-time (org-parse-time-string ts)))))
19242 (if te (setq te (time-to-seconds
19243 (apply 'encode-time (org-parse-time-string te)))))
19244 (move-marker ins (point))
19245 (setq ipos (point))
19247 ;; Get the right scope
19248 (setq pos (point))
19249 (save-restriction
19250 (cond
19251 ((not scope))
19252 ((eq scope 'file) (widen))
19253 ((eq scope 'subtree) (org-narrow-to-subtree))
19254 ((eq scope 'tree)
19255 (while (org-up-heading-safe))
19256 (org-narrow-to-subtree))
19257 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19258 (symbol-name scope)))
19259 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19260 (catch 'exit
19261 (while (org-up-heading-safe)
19262 (looking-at outline-regexp)
19263 (if (<= (org-reduced-level (funcall outline-level)) level)
19264 (throw 'exit nil))))
19265 (org-narrow-to-subtree))
19266 ((or (listp scope) (eq scope 'agenda))
19267 (let* ((files (if (listp scope) scope (org-agenda-files)))
19268 (scope 'agenda)
19269 (p1 (copy-sequence params))
19270 file)
19271 (plist-put p1 :tostring t)
19272 (plist-put p1 :multifile t)
19273 (plist-put p1 :scope 'file)
19274 (org-prepare-agenda-buffers files)
19275 (while (setq file (pop files))
19276 (with-current-buffer (find-buffer-visiting file)
19277 (push (org-clocktable-add-file
19278 file (org-dblock-write:clocktable p1)) tbl)
19279 (setq total-time (+ (or total-time 0)
19280 org-clock-file-total-minutes)))))))
19281 (goto-char pos)
19283 (unless (eq scope 'agenda)
19284 (org-clock-sum ts te)
19285 (goto-char (point-min))
19286 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19287 (goto-char p)
19288 (when (setq time (get-text-property p :org-clock-minutes))
19289 (save-excursion
19290 (beginning-of-line 1)
19291 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19292 (setq level (org-reduced-level
19293 (- (match-end 1) (match-beginning 1))))
19294 (<= level maxlevel))
19295 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19296 hdl (match-string 2)
19297 h (/ time 60)
19298 m (- time (* 60 h)))
19299 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19300 (push (concat
19301 "| " (int-to-string level) "|" hlc hdl hlc " |"
19302 (make-string (1- level) ?|)
19303 hlc (format "%d:%02d" h m) hlc
19304 " |") tbl))))))
19305 (setq tbl (nreverse tbl))
19306 (if tostring
19307 (if tbl (mapconcat 'identity tbl "\n") nil)
19308 (goto-char ins)
19309 (insert-before-markers
19310 (or header
19311 (concat
19312 "Clock summary at ["
19313 (substring
19314 (format-time-string (cdr org-time-stamp-formats))
19315 1 -1)
19316 "]."
19317 (if block
19318 (format " Considered range is /%s/." block)
19320 "\n\n"))
19321 (if (eq scope 'agenda) "|File" "")
19322 "|L|Headline|Time|\n")
19323 (setq total-time (or total-time org-clock-file-total-minutes)
19324 h (/ total-time 60)
19325 m (- total-time (* 60 h)))
19326 (insert-before-markers
19327 "|-\n|"
19328 (if (eq scope 'agenda) "|" "")
19330 "*Total time*| "
19331 (format "*%d:%02d*" h m)
19332 "|\n|-\n")
19333 (setq tbl (delq nil tbl))
19334 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19335 (equal (substring (car tbl) 0 2) "|-"))
19336 (pop tbl))
19337 (insert-before-markers (mapconcat
19338 'identity (delq nil tbl)
19339 (if (eq scope 'agenda) "\n|-\n" "\n")))
19340 (backward-delete-char 1)
19341 (goto-char ipos)
19342 (skip-chars-forward "^|")
19343 (org-table-align))))))
19345 (defun org-clocktable-steps (params)
19346 (let* ((p1 (copy-sequence params))
19347 (ts (plist-get p1 :tstart))
19348 (te (plist-get p1 :tend))
19349 (step0 (plist-get p1 :step))
19350 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19351 (block (plist-get p1 :block))
19353 (when block
19354 (setq cc (org-clock-special-range block nil t)
19355 ts (car cc) te (cdr cc)))
19356 (if ts (setq ts (time-to-seconds
19357 (apply 'encode-time (org-parse-time-string ts)))))
19358 (if te (setq te (time-to-seconds
19359 (apply 'encode-time (org-parse-time-string te)))))
19360 (plist-put p1 :header "")
19361 (plist-put p1 :step nil)
19362 (plist-put p1 :block nil)
19363 (while (< ts te)
19364 (or (bolp) (insert "\n"))
19365 (plist-put p1 :tstart (format-time-string
19366 (car org-time-stamp-formats)
19367 (seconds-to-time ts)))
19368 (plist-put p1 :tend (format-time-string
19369 (car org-time-stamp-formats)
19370 (seconds-to-time (setq ts (+ ts step)))))
19371 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19372 (plist-get p1 :tstart) "\n")
19373 (org-dblock-write:clocktable p1)
19374 (re-search-forward "#\\+END:")
19375 (end-of-line 0))))
19378 (defun org-clocktable-add-file (file table)
19379 (if table
19380 (let ((lines (org-split-string table "\n"))
19381 (ff (file-name-nondirectory file)))
19382 (mapconcat 'identity
19383 (mapcar (lambda (x)
19384 (if (string-match org-table-dataline-regexp x)
19385 (concat "|" ff x)
19387 lines)
19388 "\n"))))
19390 ;; FIXME: I don't think anybody uses this, ask David
19391 (defun org-collect-clock-time-entries ()
19392 "Return an internal list with clocking information.
19393 This list has one entry for each CLOCK interval.
19394 FIXME: describe the elements."
19395 (interactive)
19396 (let ((re (concat "^[ \t]*" org-clock-string
19397 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19398 rtn beg end next cont level title total closedp leafp
19399 clockpos titlepos h m donep)
19400 (save-excursion
19401 (org-clock-sum)
19402 (goto-char (point-min))
19403 (while (re-search-forward re nil t)
19404 (setq clockpos (match-beginning 0)
19405 beg (match-string 1) end (match-string 2)
19406 cont (match-end 0))
19407 (setq beg (apply 'encode-time (org-parse-time-string beg))
19408 end (apply 'encode-time (org-parse-time-string end)))
19409 (org-back-to-heading t)
19410 (setq donep (org-entry-is-done-p))
19411 (setq titlepos (point)
19412 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19413 h (/ total 60) m (- total (* 60 h))
19414 total (cons h m))
19415 (looking-at "\\(\\*+\\) +\\(.*\\)")
19416 (setq level (- (match-end 1) (match-beginning 1))
19417 title (org-match-string-no-properties 2))
19418 (save-excursion (outline-next-heading) (setq next (point)))
19419 (setq closedp (re-search-forward org-closed-time-regexp next t))
19420 (goto-char next)
19421 (setq leafp (and (looking-at "^\\*+ ")
19422 (<= (- (match-end 0) (point)) level)))
19423 (push (list beg end clockpos closedp donep
19424 total title titlepos level leafp)
19425 rtn)
19426 (goto-char cont)))
19427 (nreverse rtn)))
19429 ;;;; Agenda, and Diary Integration
19431 ;;; Define the Org-agenda-mode
19433 (defvar org-agenda-mode-map (make-sparse-keymap)
19434 "Keymap for `org-agenda-mode'.")
19436 (defvar org-agenda-menu) ; defined later in this file.
19437 (defvar org-agenda-follow-mode nil)
19438 (defvar org-agenda-show-log nil)
19439 (defvar org-agenda-redo-command nil)
19440 (defvar org-agenda-query-string nil)
19441 (defvar org-agenda-mode-hook nil)
19442 (defvar org-agenda-type nil)
19443 (defvar org-agenda-force-single-file nil)
19445 (defun org-agenda-mode ()
19446 "Mode for time-sorted view on action items in Org-mode files.
19448 The following commands are available:
19450 \\{org-agenda-mode-map}"
19451 (interactive)
19452 (kill-all-local-variables)
19453 (setq org-agenda-undo-list nil
19454 org-agenda-pending-undo-list nil)
19455 (setq major-mode 'org-agenda-mode)
19456 ;; Keep global-font-lock-mode from turning on font-lock-mode
19457 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19458 (setq mode-name "Org-Agenda")
19459 (use-local-map org-agenda-mode-map)
19460 (easy-menu-add org-agenda-menu)
19461 (if org-startup-truncated (setq truncate-lines t))
19462 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19463 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19464 ;; Make sure properties are removed when copying text
19465 (when (boundp 'buffer-substring-filters)
19466 (org-set-local 'buffer-substring-filters
19467 (cons (lambda (x)
19468 (set-text-properties 0 (length x) nil x) x)
19469 buffer-substring-filters)))
19470 (unless org-agenda-keep-modes
19471 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19472 org-agenda-show-log nil))
19473 (easy-menu-change
19474 '("Agenda") "Agenda Files"
19475 (append
19476 (list
19477 (vector
19478 (if (get 'org-agenda-files 'org-restrict)
19479 "Restricted to single file"
19480 "Edit File List")
19481 '(org-edit-agenda-file-list)
19482 (not (get 'org-agenda-files 'org-restrict)))
19483 "--")
19484 (mapcar 'org-file-menu-entry (org-agenda-files))))
19485 (org-agenda-set-mode-name)
19486 (apply
19487 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19488 (list 'org-agenda-mode-hook)))
19490 (substitute-key-definition 'undo 'org-agenda-undo
19491 org-agenda-mode-map global-map)
19492 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19493 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19494 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19495 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19496 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19497 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19498 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19499 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19500 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19501 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19502 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19503 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19504 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19505 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19506 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19507 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19508 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19509 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19510 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19511 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19512 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19513 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19514 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19515 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19516 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19517 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19518 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19519 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19520 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19522 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19523 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19524 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19525 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19526 (while l (org-defkey org-agenda-mode-map
19527 (int-to-string (pop l)) 'digit-argument)))
19529 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19530 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19531 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19532 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19533 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19534 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19535 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19536 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19537 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19538 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19539 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19540 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19541 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19542 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19543 (org-defkey org-agenda-mode-map "n" 'next-line)
19544 (org-defkey org-agenda-mode-map "p" 'previous-line)
19545 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19546 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19547 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19548 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19549 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19550 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19551 (eval-after-load "calendar"
19552 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19553 'org-calendar-goto-agenda))
19554 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19555 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19556 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19557 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19558 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19559 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19560 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19561 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19562 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19563 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19564 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19565 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19566 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19567 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19568 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19569 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19570 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19571 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19572 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19573 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19574 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19575 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19577 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19578 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19579 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19580 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19582 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19583 "Local keymap for agenda entries from Org-mode.")
19585 (org-defkey org-agenda-keymap
19586 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19587 (org-defkey org-agenda-keymap
19588 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19589 (when org-agenda-mouse-1-follows-link
19590 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19591 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19592 '("Agenda"
19593 ("Agenda Files")
19594 "--"
19595 ["Show" org-agenda-show t]
19596 ["Go To (other window)" org-agenda-goto t]
19597 ["Go To (this window)" org-agenda-switch-to t]
19598 ["Follow Mode" org-agenda-follow-mode
19599 :style toggle :selected org-agenda-follow-mode :active t]
19600 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19601 "--"
19602 ["Cycle TODO" org-agenda-todo t]
19603 ["Archive subtree" org-agenda-archive t]
19604 ["Delete subtree" org-agenda-kill t]
19605 "--"
19606 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19607 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19608 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19609 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19610 "--"
19611 ("Tags and Properties"
19612 ["Show all Tags" org-agenda-show-tags t]
19613 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19614 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19615 "--"
19616 ["Column View" org-columns t])
19617 ("Date/Schedule"
19618 ["Schedule" org-agenda-schedule t]
19619 ["Set Deadline" org-agenda-deadline t]
19620 "--"
19621 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19622 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19623 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19624 ("Clock"
19625 ["Clock in" org-agenda-clock-in t]
19626 ["Clock out" org-agenda-clock-out t]
19627 ["Clock cancel" org-agenda-clock-cancel t]
19628 ["Goto running clock" org-clock-goto t])
19629 ("Priority"
19630 ["Set Priority" org-agenda-priority t]
19631 ["Increase Priority" org-agenda-priority-up t]
19632 ["Decrease Priority" org-agenda-priority-down t]
19633 ["Show Priority" org-agenda-show-priority t])
19634 ("Calendar/Diary"
19635 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19636 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19637 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19638 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19639 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19640 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19641 "--"
19642 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19643 "--"
19644 ("View"
19645 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19646 :style radio :selected (equal org-agenda-ndays 1)]
19647 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19648 :style radio :selected (equal org-agenda-ndays 7)]
19649 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19650 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19651 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19652 :style radio :selected (member org-agenda-ndays '(365 366))]
19653 "--"
19654 ["Show Logbook entries" org-agenda-log-mode
19655 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19656 ["Include Diary" org-agenda-toggle-diary
19657 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19658 ["Use Time Grid" org-agenda-toggle-time-grid
19659 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19660 ["Write view to file" org-write-agenda t]
19661 ["Rebuild buffer" org-agenda-redo t]
19662 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19663 "--"
19664 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19665 "--"
19666 ["Quit" org-agenda-quit t]
19667 ["Exit and Release Buffers" org-agenda-exit t]
19670 ;;; Agenda undo
19672 (defvar org-agenda-allow-remote-undo t
19673 "Non-nil means, allow remote undo from the agenda buffer.")
19674 (defvar org-agenda-undo-list nil
19675 "List of undoable operations in the agenda since last refresh.")
19676 (defvar org-agenda-undo-has-started-in nil
19677 "Buffers that have already seen `undo-start' in the current undo sequence.")
19678 (defvar org-agenda-pending-undo-list nil
19679 "In a series of undo commands, this is the list of remaning undo items.")
19681 (defmacro org-if-unprotected (&rest body)
19682 "Execute BODY if there is no `org-protected' text property at point."
19683 (declare (debug t))
19684 `(unless (get-text-property (point) 'org-protected)
19685 ,@body))
19687 (defmacro org-with-remote-undo (_buffer &rest _body)
19688 "Execute BODY while recording undo information in two buffers."
19689 (declare (indent 1) (debug t))
19690 `(let ((_cline (org-current-line))
19691 (_cmd this-command)
19692 (_buf1 (current-buffer))
19693 (_buf2 ,_buffer)
19694 (_undo1 buffer-undo-list)
19695 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19696 _c1 _c2)
19697 ,@_body
19698 (when org-agenda-allow-remote-undo
19699 (setq _c1 (org-verify-change-for-undo
19700 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19701 _c2 (org-verify-change-for-undo
19702 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19703 (when (or _c1 _c2)
19704 ;; make sure there are undo boundaries
19705 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19706 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19707 ;; remember which buffer to undo
19708 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19709 org-agenda-undo-list)))))
19711 (defun org-agenda-undo ()
19712 "Undo a remote editing step in the agenda.
19713 This undoes changes both in the agenda buffer and in the remote buffer
19714 that have been changed along."
19715 (interactive)
19716 (or org-agenda-allow-remote-undo
19717 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19718 (if (not (eq this-command last-command))
19719 (setq org-agenda-undo-has-started-in nil
19720 org-agenda-pending-undo-list org-agenda-undo-list))
19721 (if (not org-agenda-pending-undo-list)
19722 (error "No further undo information"))
19723 (let* ((entry (pop org-agenda-pending-undo-list))
19724 buf line cmd rembuf)
19725 (setq cmd (pop entry) line (pop entry))
19726 (setq rembuf (nth 2 entry))
19727 (org-with-remote-undo rembuf
19728 (while (bufferp (setq buf (pop entry)))
19729 (if (pop entry)
19730 (with-current-buffer buf
19731 (let ((last-undo-buffer buf)
19732 (inhibit-read-only t))
19733 (unless (memq buf org-agenda-undo-has-started-in)
19734 (push buf org-agenda-undo-has-started-in)
19735 (make-local-variable 'pending-undo-list)
19736 (undo-start))
19737 (while (and pending-undo-list
19738 (listp pending-undo-list)
19739 (not (car pending-undo-list)))
19740 (pop pending-undo-list))
19741 (undo-more 1))))))
19742 (goto-line line)
19743 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19745 (defun org-verify-change-for-undo (l1 l2)
19746 "Verify that a real change occurred between the undo lists L1 and L2."
19747 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19748 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19749 (not (eq l1 l2)))
19751 ;;; Agenda dispatch
19753 (defvar org-agenda-restrict nil)
19754 (defvar org-agenda-restrict-begin (make-marker))
19755 (defvar org-agenda-restrict-end (make-marker))
19756 (defvar org-agenda-last-dispatch-buffer nil)
19757 (defvar org-agenda-overriding-restriction nil)
19759 ;;;###autoload
19760 (defun org-agenda (arg &optional keys restriction)
19761 "Dispatch agenda commands to collect entries to the agenda buffer.
19762 Prompts for a command to execute. Any prefix arg will be passed
19763 on to the selected command. The default selections are:
19765 a Call `org-agenda-list' to display the agenda for current day or week.
19766 t Call `org-todo-list' to display the global todo list.
19767 T Call `org-todo-list' to display the global todo list, select only
19768 entries with a specific TODO keyword (the user gets a prompt).
19769 m Call `org-tags-view' to display headlines with tags matching
19770 a condition (the user is prompted for the condition).
19771 M Like `m', but select only TODO entries, no ordinary headlines.
19772 L Create a timeline for the current buffer.
19773 e Export views to associated files.
19775 More commands can be added by configuring the variable
19776 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19777 searches can be pre-defined in this way.
19779 If the current buffer is in Org-mode and visiting a file, you can also
19780 first press `<' once to indicate that the agenda should be temporarily
19781 \(until the next use of \\[org-agenda]) restricted to the current file.
19782 Pressing `<' twice means to restrict to the current subtree or region
19783 \(if active)."
19784 (interactive "P")
19785 (catch 'exit
19786 (let* ((prefix-descriptions nil)
19787 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19788 (org-agenda-custom-commands
19789 ;; normalize different versions
19790 (delq nil
19791 (mapcar
19792 (lambda (x)
19793 (cond ((stringp (cdr x))
19794 (push x prefix-descriptions)
19795 nil)
19796 ((stringp (nth 1 x)) x)
19797 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19798 (t (cons (car x) (cons "" (cdr x))))))
19799 org-agenda-custom-commands)))
19800 (buf (current-buffer))
19801 (bfn (buffer-file-name (buffer-base-buffer)))
19802 entry key type match lprops ans)
19803 ;; Turn off restriction unless there is an overriding one
19804 (unless org-agenda-overriding-restriction
19805 (put 'org-agenda-files 'org-restrict nil)
19806 (setq org-agenda-restrict nil)
19807 (move-marker org-agenda-restrict-begin nil)
19808 (move-marker org-agenda-restrict-end nil))
19809 ;; Delete old local properties
19810 (put 'org-agenda-redo-command 'org-lprops nil)
19811 ;; Remember where this call originated
19812 (setq org-agenda-last-dispatch-buffer (current-buffer))
19813 (unless keys
19814 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19815 keys (car ans)
19816 restriction (cdr ans)))
19817 ;; Estabish the restriction, if any
19818 (when (and (not org-agenda-overriding-restriction) restriction)
19819 (put 'org-agenda-files 'org-restrict (list bfn))
19820 (cond
19821 ((eq restriction 'region)
19822 (setq org-agenda-restrict t)
19823 (move-marker org-agenda-restrict-begin (region-beginning))
19824 (move-marker org-agenda-restrict-end (region-end)))
19825 ((eq restriction 'subtree)
19826 (save-excursion
19827 (setq org-agenda-restrict t)
19828 (org-back-to-heading t)
19829 (move-marker org-agenda-restrict-begin (point))
19830 (move-marker org-agenda-restrict-end
19831 (progn (org-end-of-subtree t)))))))
19833 (require 'calendar) ; FIXME: can we avoid this for some commands?
19834 ;; For example the todo list should not need it (but does...)
19835 (cond
19836 ((setq entry (assoc keys org-agenda-custom-commands))
19837 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19838 (progn
19839 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19840 (put 'org-agenda-redo-command 'org-lprops lprops)
19841 (cond
19842 ((eq type 'agenda)
19843 (org-let lprops '(org-agenda-list current-prefix-arg)))
19844 ((eq type 'alltodo)
19845 (org-let lprops '(org-todo-list current-prefix-arg)))
19846 ((eq type 'search)
19847 (org-let lprops '(org-search-view current-prefix-arg match)))
19848 ((eq type 'stuck)
19849 (org-let lprops '(org-agenda-list-stuck-projects
19850 current-prefix-arg)))
19851 ((eq type 'tags)
19852 (org-let lprops '(org-tags-view current-prefix-arg match)))
19853 ((eq type 'tags-todo)
19854 (org-let lprops '(org-tags-view '(4) match)))
19855 ((eq type 'todo)
19856 (org-let lprops '(org-todo-list match)))
19857 ((eq type 'tags-tree)
19858 (org-check-for-org-mode)
19859 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19860 ((eq type 'todo-tree)
19861 (org-check-for-org-mode)
19862 (org-let lprops
19863 '(org-occur (concat "^" outline-regexp "[ \t]*"
19864 (regexp-quote match) "\\>"))))
19865 ((eq type 'occur-tree)
19866 (org-check-for-org-mode)
19867 (org-let lprops '(org-occur match)))
19868 ((functionp type)
19869 (org-let lprops '(funcall type match)))
19870 ((fboundp type)
19871 (org-let lprops '(funcall type match)))
19872 (t (error "Invalid custom agenda command type %s" type))))
19873 (org-run-agenda-series (nth 1 entry) (cddr entry))))
19874 ((equal keys "C")
19875 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
19876 (customize-variable 'org-agenda-custom-commands))
19877 ((equal keys "a") (call-interactively 'org-agenda-list))
19878 ((equal keys "s") (call-interactively 'org-search-view))
19879 ((equal keys "t") (call-interactively 'org-todo-list))
19880 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
19881 ((equal keys "m") (call-interactively 'org-tags-view))
19882 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
19883 ((equal keys "e") (call-interactively 'org-store-agenda-views))
19884 ((equal keys "L")
19885 (unless (org-mode-p)
19886 (error "This is not an Org-mode file"))
19887 (unless restriction
19888 (put 'org-agenda-files 'org-restrict (list bfn))
19889 (org-call-with-arg 'org-timeline arg)))
19890 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
19891 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
19892 ((equal keys "!") (customize-variable 'org-stuck-projects))
19893 (t (error "Invalid agenda key"))))))
19895 (defun org-agenda-normalize-custom-commands (cmds)
19896 (delq nil
19897 (mapcar
19898 (lambda (x)
19899 (cond ((stringp (cdr x)) nil)
19900 ((stringp (nth 1 x)) x)
19901 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19902 (t (cons (car x) (cons "" (cdr x))))))
19903 cmds)))
19905 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
19906 "The user interface for selecting an agenda command."
19907 (catch 'exit
19908 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
19909 (restrict-ok (and bfn (org-mode-p)))
19910 (region-p (org-region-active-p))
19911 (custom org-agenda-custom-commands)
19912 (selstring "")
19913 restriction second-time
19914 c entry key type match prefixes rmheader header-end custom1 desc)
19915 (save-window-excursion
19916 (delete-other-windows)
19917 (org-switch-to-buffer-other-window " *Agenda Commands*")
19918 (erase-buffer)
19919 (insert (eval-when-compile
19920 (let ((header
19922 Press key for an agenda command: < Buffer,subtree/region restriction
19923 -------------------------------- > Remove restriction
19924 a Agenda for current week or day e Export agenda views
19925 t List of all TODO entries T Entries with special TODO kwd
19926 m Match a TAGS query M Like m, but only TODO entries
19927 L Timeline for current buffer # List stuck projects (!=configure)
19928 s Search for keywords C Configure custom agenda commands
19929 / Multi-occur
19931 (start 0))
19932 (while (string-match
19933 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
19934 header start)
19935 (setq start (match-end 0))
19936 (add-text-properties (match-beginning 2) (match-end 2)
19937 '(face bold) header))
19938 header)))
19939 (setq header-end (move-marker (make-marker) (point)))
19940 (while t
19941 (setq custom1 custom)
19942 (when (eq rmheader t)
19943 (goto-line 1)
19944 (re-search-forward ":" nil t)
19945 (delete-region (match-end 0) (point-at-eol))
19946 (forward-char 1)
19947 (looking-at "-+")
19948 (delete-region (match-end 0) (point-at-eol))
19949 (move-marker header-end (match-end 0)))
19950 (goto-char header-end)
19951 (delete-region (point) (point-max))
19952 (while (setq entry (pop custom1))
19953 (setq key (car entry) desc (nth 1 entry)
19954 type (nth 2 entry) match (nth 3 entry))
19955 (if (> (length key) 1)
19956 (add-to-list 'prefixes (string-to-char key))
19957 (insert
19958 (format
19959 "\n%-4s%-14s: %s"
19960 (org-add-props (copy-sequence key)
19961 '(face bold))
19962 (cond
19963 ((string-match "\\S-" desc) desc)
19964 ((eq type 'agenda) "Agenda for current week or day")
19965 ((eq type 'alltodo) "List of all TODO entries")
19966 ((eq type 'search) "Word search")
19967 ((eq type 'stuck) "List of stuck projects")
19968 ((eq type 'todo) "TODO keyword")
19969 ((eq type 'tags) "Tags query")
19970 ((eq type 'tags-todo) "Tags (TODO)")
19971 ((eq type 'tags-tree) "Tags tree")
19972 ((eq type 'todo-tree) "TODO kwd tree")
19973 ((eq type 'occur-tree) "Occur tree")
19974 ((functionp type) (if (symbolp type)
19975 (symbol-name type)
19976 "Lambda expression"))
19977 (t "???"))
19978 (cond
19979 ((stringp match)
19980 (org-add-props match nil 'face 'org-warning))
19981 (match
19982 (format "set of %d commands" (length match)))
19983 (t ""))))))
19984 (when prefixes
19985 (mapc (lambda (x)
19986 (insert
19987 (format "\n%s %s"
19988 (org-add-props (char-to-string x)
19989 nil 'face 'bold)
19990 (or (cdr (assoc (concat selstring (char-to-string x))
19991 prefix-descriptions))
19992 "Prefix key"))))
19993 prefixes))
19994 (goto-char (point-min))
19995 (when (fboundp 'fit-window-to-buffer)
19996 (if second-time
19997 (if (not (pos-visible-in-window-p (point-max)))
19998 (fit-window-to-buffer))
19999 (setq second-time t)
20000 (fit-window-to-buffer)))
20001 (message "Press key for agenda command%s:"
20002 (if (or restrict-ok org-agenda-overriding-restriction)
20003 (if org-agenda-overriding-restriction
20004 " (restriction lock active)"
20005 (if restriction
20006 (format " (restricted to %s)" restriction)
20007 " (unrestricted)"))
20008 ""))
20009 (setq c (read-char-exclusive))
20010 (message "")
20011 (cond
20012 ((assoc (char-to-string c) custom)
20013 (setq selstring (concat selstring (char-to-string c)))
20014 (throw 'exit (cons selstring restriction)))
20015 ((memq c prefixes)
20016 (setq selstring (concat selstring (char-to-string c))
20017 prefixes nil
20018 rmheader (or rmheader t)
20019 custom (delq nil (mapcar
20020 (lambda (x)
20021 (if (or (= (length (car x)) 1)
20022 (/= (string-to-char (car x)) c))
20024 (cons (substring (car x) 1) (cdr x))))
20025 custom))))
20026 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20027 (message "Restriction is only possible in Org-mode buffers")
20028 (ding) (sit-for 1))
20029 ((eq c ?1)
20030 (org-agenda-remove-restriction-lock 'noupdate)
20031 (setq restriction 'buffer))
20032 ((eq c ?0)
20033 (org-agenda-remove-restriction-lock 'noupdate)
20034 (setq restriction (if region-p 'region 'subtree)))
20035 ((eq c ?<)
20036 (org-agenda-remove-restriction-lock 'noupdate)
20037 (setq restriction
20038 (cond
20039 ((eq restriction 'buffer)
20040 (if region-p 'region 'subtree))
20041 ((memq restriction '(subtree region))
20042 nil)
20043 (t 'buffer))))
20044 ((eq c ?>)
20045 (org-agenda-remove-restriction-lock 'noupdate)
20046 (setq restriction nil))
20047 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20048 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20049 ((and (> (length selstring) 0) (eq c ?\d))
20050 (delete-window)
20051 (org-agenda-get-restriction-and-command prefix-descriptions))
20053 ((equal c ?q) (error "Abort"))
20054 (t (error "Invalid key %c" c))))))))
20056 (defun org-run-agenda-series (name series)
20057 (org-prepare-agenda name)
20058 (let* ((org-agenda-multi t)
20059 (redo (list 'org-run-agenda-series name (list 'quote series)))
20060 (cmds (car series))
20061 (gprops (nth 1 series))
20062 match ;; The byte compiler incorrectly complains about this. Keep it!
20063 cmd type lprops)
20064 (while (setq cmd (pop cmds))
20065 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20066 (cond
20067 ((eq type 'agenda)
20068 (org-let2 gprops lprops
20069 '(call-interactively 'org-agenda-list)))
20070 ((eq type 'alltodo)
20071 (org-let2 gprops lprops
20072 '(call-interactively 'org-todo-list)))
20073 ((eq type 'search)
20074 (org-let2 gprops lprops
20075 '(org-search-view current-prefix-arg match)))
20076 ((eq type 'stuck)
20077 (org-let2 gprops lprops
20078 '(call-interactively 'org-agenda-list-stuck-projects)))
20079 ((eq type 'tags)
20080 (org-let2 gprops lprops
20081 '(org-tags-view current-prefix-arg match)))
20082 ((eq type 'tags-todo)
20083 (org-let2 gprops lprops
20084 '(org-tags-view '(4) match)))
20085 ((eq type 'todo)
20086 (org-let2 gprops lprops
20087 '(org-todo-list match)))
20088 ((fboundp type)
20089 (org-let2 gprops lprops
20090 '(funcall type match)))
20091 (t (error "Invalid type in command series"))))
20092 (widen)
20093 (setq org-agenda-redo-command redo)
20094 (goto-char (point-min)))
20095 (org-finalize-agenda))
20097 ;;;###autoload
20098 (defmacro org-batch-agenda (cmd-key &rest parameters)
20099 "Run an agenda command in batch mode and send the result to STDOUT.
20100 If CMD-KEY is a string of length 1, it is used as a key in
20101 `org-agenda-custom-commands' and triggers this command. If it is a
20102 longer string it is used as a tags/todo match string.
20103 Paramters are alternating variable names and values that will be bound
20104 before running the agenda command."
20105 (let (pars)
20106 (while parameters
20107 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20108 (if (> (length cmd-key) 2)
20109 (eval (list 'let (nreverse pars)
20110 (list 'org-tags-view nil cmd-key)))
20111 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20112 (set-buffer org-agenda-buffer-name)
20113 (princ (org-encode-for-stdout (buffer-string)))))
20115 (defun org-encode-for-stdout (string)
20116 (if (fboundp 'encode-coding-string)
20117 (encode-coding-string string buffer-file-coding-system)
20118 string))
20120 (defvar org-agenda-info nil)
20122 ;;;###autoload
20123 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20124 "Run an agenda command in batch mode and send the result to STDOUT.
20125 If CMD-KEY is a string of length 1, it is used as a key in
20126 `org-agenda-custom-commands' and triggers this command. If it is a
20127 longer string it is used as a tags/todo match string.
20128 Paramters are alternating variable names and values that will be bound
20129 before running the agenda command.
20131 The output gives a line for each selected agenda item. Each
20132 item is a list of comma-separated values, like this:
20134 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20136 category The category of the item
20137 head The headline, without TODO kwd, TAGS and PRIORITY
20138 type The type of the agenda entry, can be
20139 todo selected in TODO match
20140 tagsmatch selected in tags match
20141 diary imported from diary
20142 deadline a deadline on given date
20143 scheduled scheduled on given date
20144 timestamp entry has timestamp on given date
20145 closed entry was closed on given date
20146 upcoming-deadline warning about deadline
20147 past-scheduled forwarded scheduled item
20148 block entry has date block including g. date
20149 todo The todo keyword, if any
20150 tags All tags including inherited ones, separated by colons
20151 date The relevant date, like 2007-2-14
20152 time The time, like 15:00-16:50
20153 extra Sting with extra planning info
20154 priority-l The priority letter if any was given
20155 priority-n The computed numerical priority
20156 agenda-day The day in the agenda where this is listed"
20158 (let (pars)
20159 (while parameters
20160 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20161 (push (list 'org-agenda-remove-tags t) pars)
20162 (if (> (length cmd-key) 2)
20163 (eval (list 'let (nreverse pars)
20164 (list 'org-tags-view nil cmd-key)))
20165 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20166 (set-buffer org-agenda-buffer-name)
20167 (let* ((lines (org-split-string (buffer-string) "\n"))
20168 line)
20169 (while (setq line (pop lines))
20170 (catch 'next
20171 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20172 (setq org-agenda-info
20173 (org-fix-agenda-info (text-properties-at 0 line)))
20174 (princ
20175 (org-encode-for-stdout
20176 (mapconcat 'org-agenda-export-csv-mapper
20177 '(org-category txt type todo tags date time-of-day extra
20178 priority-letter priority agenda-day)
20179 ",")))
20180 (princ "\n"))))))
20182 (defun org-fix-agenda-info (props)
20183 "Make sure all properties on an agenda item have a canonical form,
20184 so the export commands can easily use it."
20185 (let (tmp re)
20186 (when (setq tmp (plist-get props 'tags))
20187 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20188 (when (setq tmp (plist-get props 'date))
20189 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20190 (let ((calendar-date-display-form '(year "-" month "-" day)))
20191 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20193 (setq tmp (calendar-date-string tmp)))
20194 (setq props (plist-put props 'date tmp)))
20195 (when (setq tmp (plist-get props 'day))
20196 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20197 (let ((calendar-date-display-form '(year "-" month "-" day)))
20198 (setq tmp (calendar-date-string tmp)))
20199 (setq props (plist-put props 'day tmp))
20200 (setq props (plist-put props 'agenda-day tmp)))
20201 (when (setq tmp (plist-get props 'txt))
20202 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20203 (plist-put props 'priority-letter (match-string 1 tmp))
20204 (setq tmp (replace-match "" t t tmp)))
20205 (when (and (setq re (plist-get props 'org-todo-regexp))
20206 (setq re (concat "\\`\\.*" re " ?"))
20207 (string-match re tmp))
20208 (plist-put props 'todo (match-string 1 tmp))
20209 (setq tmp (replace-match "" t t tmp)))
20210 (plist-put props 'txt tmp)))
20211 props)
20213 (defun org-agenda-export-csv-mapper (prop)
20214 (let ((res (plist-get org-agenda-info prop)))
20215 (setq res
20216 (cond
20217 ((not res) "")
20218 ((stringp res) res)
20219 (t (prin1-to-string res))))
20220 (while (string-match "," res)
20221 (setq res (replace-match ";" t t res)))
20222 (org-trim res)))
20225 ;;;###autoload
20226 (defun org-store-agenda-views (&rest parameters)
20227 (interactive)
20228 (eval (list 'org-batch-store-agenda-views)))
20230 ;; FIXME, why is this a macro?????
20231 ;;;###autoload
20232 (defmacro org-batch-store-agenda-views (&rest parameters)
20233 "Run all custom agenda commands that have a file argument."
20234 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20235 (pop-up-frames nil)
20236 (dir default-directory)
20237 pars cmd thiscmdkey files opts)
20238 (while parameters
20239 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20240 (setq pars (reverse pars))
20241 (save-window-excursion
20242 (while cmds
20243 (setq cmd (pop cmds)
20244 thiscmdkey (car cmd)
20245 opts (nth 4 cmd)
20246 files (nth 5 cmd))
20247 (if (stringp files) (setq files (list files)))
20248 (when files
20249 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20250 (list 'org-agenda nil thiscmdkey)))
20251 (set-buffer org-agenda-buffer-name)
20252 (while files
20253 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20254 (list 'org-write-agenda
20255 (expand-file-name (pop files) dir) t))))
20256 (and (get-buffer org-agenda-buffer-name)
20257 (kill-buffer org-agenda-buffer-name)))))))
20259 (defun org-write-agenda (file &optional nosettings)
20260 "Write the current buffer (an agenda view) as a file.
20261 Depending on the extension of the file name, plain text (.txt),
20262 HTML (.html or .htm) or Postscript (.ps) is produced.
20263 If NOSETTINGS is given, do not scope the settings of
20264 `org-agenda-exporter-settings' into the export commands. This is used when
20265 the settings have already been scoped and we do not wish to overrule other,
20266 higher priority settings."
20267 (interactive "FWrite agenda to file: ")
20268 (if (not (file-writable-p file))
20269 (error "Cannot write agenda to file %s" file))
20270 (cond
20271 ((string-match "\\.html?\\'" file) (require 'htmlize))
20272 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20273 (org-let (if nosettings nil org-agenda-exporter-settings)
20274 '(save-excursion
20275 (save-window-excursion
20276 (cond
20277 ((string-match "\\.html?\\'" file)
20278 (set-buffer (htmlize-buffer (current-buffer)))
20280 (when (and org-agenda-export-html-style
20281 (string-match "<style>" org-agenda-export-html-style))
20282 ;; replace <style> section with org-agenda-export-html-style
20283 (goto-char (point-min))
20284 (kill-region (- (search-forward "<style") 6)
20285 (search-forward "</style>"))
20286 (insert org-agenda-export-html-style))
20287 (write-file file)
20288 (kill-buffer (current-buffer))
20289 (message "HTML written to %s" file))
20290 ((string-match "\\.ps\\'" file)
20291 (ps-print-buffer-with-faces file)
20292 (message "Postscript written to %s" file))
20294 (let ((bs (buffer-string)))
20295 (find-file file)
20296 (insert bs)
20297 (save-buffer 0)
20298 (kill-buffer (current-buffer))
20299 (message "Plain text written to %s" file))))))
20300 (set-buffer org-agenda-buffer-name)))
20302 (defmacro org-no-read-only (&rest body)
20303 "Inhibit read-only for BODY."
20304 `(let ((inhibit-read-only t)) ,@body))
20306 (defun org-check-for-org-mode ()
20307 "Make sure current buffer is in org-mode. Error if not."
20308 (or (org-mode-p)
20309 (error "Cannot execute org-mode agenda command on buffer in %s."
20310 major-mode)))
20312 (defun org-fit-agenda-window ()
20313 "Fit the window to the buffer size."
20314 (and (memq org-agenda-window-setup '(reorganize-frame))
20315 (fboundp 'fit-window-to-buffer)
20316 (fit-window-to-buffer
20318 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20319 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20321 ;;; Agenda file list
20323 (defun org-agenda-files (&optional unrestricted)
20324 "Get the list of agenda files.
20325 Optional UNRESTRICTED means return the full list even if a restriction
20326 is currently in place."
20327 (let ((files
20328 (cond
20329 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20330 ((stringp org-agenda-files) (org-read-agenda-file-list))
20331 ((listp org-agenda-files) org-agenda-files)
20332 (t (error "Invalid value of `org-agenda-files'")))))
20333 (setq files (apply 'append
20334 (mapcar (lambda (f)
20335 (if (file-directory-p f)
20336 (directory-files f t
20337 org-agenda-file-regexp)
20338 (list f)))
20339 files)))
20340 (if org-agenda-skip-unavailable-files
20341 (delq nil
20342 (mapcar (function
20343 (lambda (file)
20344 (and (file-readable-p file) file)))
20345 files))
20346 files))) ; `org-check-agenda-file' will remove them from the list
20348 (defun org-edit-agenda-file-list ()
20349 "Edit the list of agenda files.
20350 Depending on setup, this either uses customize to edit the variable
20351 `org-agenda-files', or it visits the file that is holding the list. In the
20352 latter case, the buffer is set up in a way that saving it automatically kills
20353 the buffer and restores the previous window configuration."
20354 (interactive)
20355 (if (stringp org-agenda-files)
20356 (let ((cw (current-window-configuration)))
20357 (find-file org-agenda-files)
20358 (org-set-local 'org-window-configuration cw)
20359 (org-add-hook 'after-save-hook
20360 (lambda ()
20361 (set-window-configuration
20362 (prog1 org-window-configuration
20363 (kill-buffer (current-buffer))))
20364 (org-install-agenda-files-menu)
20365 (message "New agenda file list installed"))
20366 nil 'local)
20367 (message "%s" (substitute-command-keys
20368 "Edit list and finish with \\[save-buffer]")))
20369 (customize-variable 'org-agenda-files)))
20371 (defun org-store-new-agenda-file-list (list)
20372 "Set new value for the agenda file list and save it correcly."
20373 (if (stringp org-agenda-files)
20374 (let ((f org-agenda-files) b)
20375 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20376 (with-temp-file f
20377 (insert (mapconcat 'identity list "\n") "\n")))
20378 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20379 (setq org-agenda-files list)
20380 (customize-save-variable 'org-agenda-files org-agenda-files))))
20382 (defun org-read-agenda-file-list ()
20383 "Read the list of agenda files from a file."
20384 (when (stringp org-agenda-files)
20385 (with-temp-buffer
20386 (insert-file-contents org-agenda-files)
20387 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20390 ;;;###autoload
20391 (defun org-cycle-agenda-files ()
20392 "Cycle through the files in `org-agenda-files'.
20393 If the current buffer visits an agenda file, find the next one in the list.
20394 If the current buffer does not, find the first agenda file."
20395 (interactive)
20396 (let* ((fs (org-agenda-files t))
20397 (files (append fs (list (car fs))))
20398 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20399 file)
20400 (unless files (error "No agenda files"))
20401 (catch 'exit
20402 (while (setq file (pop files))
20403 (if (equal (file-truename file) tcf)
20404 (when (car files)
20405 (find-file (car files))
20406 (throw 'exit t))))
20407 (find-file (car fs)))
20408 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20410 (defun org-agenda-file-to-front (&optional to-end)
20411 "Move/add the current file to the top of the agenda file list.
20412 If the file is not present in the list, it is added to the front. If it is
20413 present, it is moved there. With optional argument TO-END, add/move to the
20414 end of the list."
20415 (interactive "P")
20416 (let ((org-agenda-skip-unavailable-files nil)
20417 (file-alist (mapcar (lambda (x)
20418 (cons (file-truename x) x))
20419 (org-agenda-files t)))
20420 (ctf (file-truename buffer-file-name))
20421 x had)
20422 (setq x (assoc ctf file-alist) had x)
20424 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20425 (if to-end
20426 (setq file-alist (append (delq x file-alist) (list x)))
20427 (setq file-alist (cons x (delq x file-alist))))
20428 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20429 (org-install-agenda-files-menu)
20430 (message "File %s to %s of agenda file list"
20431 (if had "moved" "added") (if to-end "end" "front"))))
20433 (defun org-remove-file (&optional file)
20434 "Remove current file from the list of files in variable `org-agenda-files'.
20435 These are the files which are being checked for agenda entries.
20436 Optional argument FILE means, use this file instead of the current."
20437 (interactive)
20438 (let* ((org-agenda-skip-unavailable-files nil)
20439 (file (or file buffer-file-name))
20440 (true-file (file-truename file))
20441 (afile (abbreviate-file-name file))
20442 (files (delq nil (mapcar
20443 (lambda (x)
20444 (if (equal true-file
20445 (file-truename x))
20446 nil x))
20447 (org-agenda-files t)))))
20448 (if (not (= (length files) (length (org-agenda-files t))))
20449 (progn
20450 (org-store-new-agenda-file-list files)
20451 (org-install-agenda-files-menu)
20452 (message "Removed file: %s" afile))
20453 (message "File was not in list: %s (not removed)" afile))))
20455 (defun org-file-menu-entry (file)
20456 (vector file (list 'find-file file) t))
20458 (defun org-check-agenda-file (file)
20459 "Make sure FILE exists. If not, ask user what to do."
20460 (when (not (file-exists-p file))
20461 (message "non-existent file %s. [R]emove from list or [A]bort?"
20462 (abbreviate-file-name file))
20463 (let ((r (downcase (read-char-exclusive))))
20464 (cond
20465 ((equal r ?r)
20466 (org-remove-file file)
20467 (throw 'nextfile t))
20468 (t (error "Abort"))))))
20470 ;;; Agenda prepare and finalize
20472 (defvar org-agenda-multi nil) ; dynammically scoped
20473 (defvar org-agenda-buffer-name "*Org Agenda*")
20474 (defvar org-pre-agenda-window-conf nil)
20475 (defvar org-agenda-name nil)
20476 (defun org-prepare-agenda (&optional name)
20477 (setq org-todo-keywords-for-agenda nil)
20478 (setq org-done-keywords-for-agenda nil)
20479 (if org-agenda-multi
20480 (progn
20481 (setq buffer-read-only nil)
20482 (goto-char (point-max))
20483 (unless (or (bobp) org-agenda-compact-blocks)
20484 (insert "\n" (make-string (window-width) ?=) "\n"))
20485 (narrow-to-region (point) (point-max)))
20486 (org-agenda-reset-markers)
20487 (org-prepare-agenda-buffers (org-agenda-files))
20488 (setq org-todo-keywords-for-agenda
20489 (org-uniquify org-todo-keywords-for-agenda))
20490 (setq org-done-keywords-for-agenda
20491 (org-uniquify org-done-keywords-for-agenda))
20492 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20493 (awin (get-buffer-window abuf)))
20494 (cond
20495 ((equal (current-buffer) abuf) nil)
20496 (awin (select-window awin))
20497 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20498 ((equal org-agenda-window-setup 'current-window)
20499 (switch-to-buffer abuf))
20500 ((equal org-agenda-window-setup 'other-window)
20501 (org-switch-to-buffer-other-window abuf))
20502 ((equal org-agenda-window-setup 'other-frame)
20503 (switch-to-buffer-other-frame abuf))
20504 ((equal org-agenda-window-setup 'reorganize-frame)
20505 (delete-other-windows)
20506 (org-switch-to-buffer-other-window abuf))))
20507 (setq buffer-read-only nil)
20508 (erase-buffer)
20509 (org-agenda-mode)
20510 (and name (not org-agenda-name)
20511 (org-set-local 'org-agenda-name name)))
20512 (setq buffer-read-only nil))
20514 (defun org-finalize-agenda ()
20515 "Finishing touch for the agenda buffer, called just before displaying it."
20516 (unless org-agenda-multi
20517 (save-excursion
20518 (let ((inhibit-read-only t))
20519 (goto-char (point-min))
20520 (while (org-activate-bracket-links (point-max))
20521 (add-text-properties (match-beginning 0) (match-end 0)
20522 '(face org-link)))
20523 (org-agenda-align-tags)
20524 (unless org-agenda-with-colors
20525 (remove-text-properties (point-min) (point-max) '(face nil))))
20526 (if (and (boundp 'org-overriding-columns-format)
20527 org-overriding-columns-format)
20528 (org-set-local 'org-overriding-columns-format
20529 org-overriding-columns-format))
20530 (if (and (boundp 'org-agenda-view-columns-initially)
20531 org-agenda-view-columns-initially)
20532 (org-agenda-columns))
20533 (when org-agenda-fontify-priorities
20534 (org-fontify-priorities))
20535 (run-hooks 'org-finalize-agenda-hook)
20536 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20539 (defun org-fontify-priorities ()
20540 "Make highest priority lines bold, and lowest italic."
20541 (interactive)
20542 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20543 (org-delete-overlay o)))
20544 (org-overlays-in (point-min) (point-max)))
20545 (save-excursion
20546 (let ((inhibit-read-only t)
20547 b e p ov h l)
20548 (goto-char (point-min))
20549 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20550 (setq h (or (get-char-property (point) 'org-highest-priority)
20551 org-highest-priority)
20552 l (or (get-char-property (point) 'org-lowest-priority)
20553 org-lowest-priority)
20554 p (string-to-char (match-string 1))
20555 b (match-beginning 0) e (point-at-eol)
20556 ov (org-make-overlay b e))
20557 (org-overlay-put
20558 ov 'face
20559 (cond ((listp org-agenda-fontify-priorities)
20560 (cdr (assoc p org-agenda-fontify-priorities)))
20561 ((equal p l) 'italic)
20562 ((equal p h) 'bold)))
20563 (org-overlay-put ov 'org-type 'org-priority)))))
20565 (defun org-prepare-agenda-buffers (files)
20566 "Create buffers for all agenda files, protect archived trees and comments."
20567 (interactive)
20568 (let ((pa '(:org-archived t))
20569 (pc '(:org-comment t))
20570 (pall '(:org-archived t :org-comment t))
20571 (inhibit-read-only t)
20572 (rea (concat ":" org-archive-tag ":"))
20573 bmp file re)
20574 (save-excursion
20575 (save-restriction
20576 (while (setq file (pop files))
20577 (if (bufferp file)
20578 (set-buffer file)
20579 (org-check-agenda-file file)
20580 (set-buffer (org-get-agenda-file-buffer file)))
20581 (widen)
20582 (setq bmp (buffer-modified-p))
20583 (org-refresh-category-properties)
20584 (setq org-todo-keywords-for-agenda
20585 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20586 (setq org-done-keywords-for-agenda
20587 (append org-done-keywords-for-agenda org-done-keywords))
20588 (save-excursion
20589 (remove-text-properties (point-min) (point-max) pall)
20590 (when org-agenda-skip-archived-trees
20591 (goto-char (point-min))
20592 (while (re-search-forward rea nil t)
20593 (if (org-on-heading-p t)
20594 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20595 (goto-char (point-min))
20596 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20597 (while (re-search-forward re nil t)
20598 (add-text-properties
20599 (match-beginning 0) (org-end-of-subtree t) pc)))
20600 (set-buffer-modified-p bmp))))))
20602 (defvar org-agenda-skip-function nil
20603 "Function to be called at each match during agenda construction.
20604 If this function returns nil, the current match should not be skipped.
20605 Otherwise, the function must return a position from where the search
20606 should be continued.
20607 This may also be a Lisp form, it will be evaluated.
20608 Never set this variable using `setq' or so, because then it will apply
20609 to all future agenda commands. Instead, bind it with `let' to scope
20610 it dynamically into the agenda-constructing command. A good way to set
20611 it is through options in org-agenda-custom-commands.")
20613 (defun org-agenda-skip ()
20614 "Throw to `:skip' in places that should be skipped.
20615 Also moves point to the end of the skipped region, so that search can
20616 continue from there."
20617 (let ((p (point-at-bol)) to fp)
20618 (and org-agenda-skip-archived-trees
20619 (get-text-property p :org-archived)
20620 (org-end-of-subtree t)
20621 (throw :skip t))
20622 (and (get-text-property p :org-comment)
20623 (org-end-of-subtree t)
20624 (throw :skip t))
20625 (if (equal (char-after p) ?#) (throw :skip t))
20626 (when (and (or (setq fp (functionp org-agenda-skip-function))
20627 (consp org-agenda-skip-function))
20628 (setq to (save-excursion
20629 (save-match-data
20630 (if fp
20631 (funcall org-agenda-skip-function)
20632 (eval org-agenda-skip-function))))))
20633 (goto-char to)
20634 (throw :skip t))))
20636 (defvar org-agenda-markers nil
20637 "List of all currently active markers created by `org-agenda'.")
20638 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20639 "Creation time of the last agenda marker.")
20641 (defun org-agenda-new-marker (&optional pos)
20642 "Return a new agenda marker.
20643 Org-mode keeps a list of these markers and resets them when they are
20644 no longer in use."
20645 (let ((m (copy-marker (or pos (point)))))
20646 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20647 (push m org-agenda-markers)
20650 (defun org-agenda-reset-markers ()
20651 "Reset markers created by `org-agenda'."
20652 (while org-agenda-markers
20653 (move-marker (pop org-agenda-markers) nil)))
20655 (defun org-get-agenda-file-buffer (file)
20656 "Get a buffer visiting FILE. If the buffer needs to be created, add
20657 it to the list of buffers which might be released later."
20658 (let ((buf (org-find-base-buffer-visiting file)))
20659 (if buf
20660 buf ; just return it
20661 ;; Make a new buffer and remember it
20662 (setq buf (find-file-noselect file))
20663 (if buf (push buf org-agenda-new-buffers))
20664 buf)))
20666 (defun org-release-buffers (blist)
20667 "Release all buffers in list, asking the user for confirmation when needed.
20668 When a buffer is unmodified, it is just killed. When modified, it is saved
20669 \(if the user agrees) and then killed."
20670 (let (buf file)
20671 (while (setq buf (pop blist))
20672 (setq file (buffer-file-name buf))
20673 (when (and (buffer-modified-p buf)
20674 file
20675 (y-or-n-p (format "Save file %s? " file)))
20676 (with-current-buffer buf (save-buffer)))
20677 (kill-buffer buf))))
20679 (defun org-get-category (&optional pos)
20680 "Get the category applying to position POS."
20681 (get-text-property (or pos (point)) 'org-category))
20683 ;;; Agenda timeline
20685 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20687 (defun org-timeline (&optional include-all)
20688 "Show a time-sorted view of the entries in the current org file.
20689 Only entries with a time stamp of today or later will be listed. With
20690 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20691 under the current date.
20692 If the buffer contains an active region, only check the region for
20693 dates."
20694 (interactive "P")
20695 (require 'calendar)
20696 (org-compile-prefix-format 'timeline)
20697 (org-set-sorting-strategy 'timeline)
20698 (let* ((dopast t)
20699 (dotodo include-all)
20700 (doclosed org-agenda-show-log)
20701 (entry buffer-file-name)
20702 (date (calendar-current-date))
20703 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20704 (end (if (org-region-active-p) (region-end) (point-max)))
20705 (day-numbers (org-get-all-dates beg end 'no-ranges
20706 t doclosed ; always include today
20707 org-timeline-show-empty-dates))
20708 (org-deadline-warning-days 0)
20709 (org-agenda-only-exact-dates t)
20710 (today (time-to-days (current-time)))
20711 (past t)
20712 args
20713 s e rtn d emptyp)
20714 (setq org-agenda-redo-command
20715 (list 'progn
20716 (list 'org-switch-to-buffer-other-window (current-buffer))
20717 (list 'org-timeline (list 'quote include-all))))
20718 (if (not dopast)
20719 ;; Remove past dates from the list of dates.
20720 (setq day-numbers (delq nil (mapcar (lambda(x)
20721 (if (>= x today) x nil))
20722 day-numbers))))
20723 (org-prepare-agenda (concat "Timeline "
20724 (file-name-nondirectory buffer-file-name)))
20725 (if doclosed (push :closed args))
20726 (push :timestamp args)
20727 (push :deadline args)
20728 (push :scheduled args)
20729 (push :sexp args)
20730 (if dotodo (push :todo args))
20731 (while (setq d (pop day-numbers))
20732 (if (and (listp d) (eq (car d) :omitted))
20733 (progn
20734 (setq s (point))
20735 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20736 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20737 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20738 (if (and (>= d today)
20739 dopast
20740 past)
20741 (progn
20742 (setq past nil)
20743 (insert (make-string 79 ?-) "\n")))
20744 (setq date (calendar-gregorian-from-absolute d))
20745 (setq s (point))
20746 (setq rtn (and (not emptyp)
20747 (apply 'org-agenda-get-day-entries entry
20748 date args)))
20749 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20750 (progn
20751 (insert
20752 (if (stringp org-agenda-format-date)
20753 (format-time-string org-agenda-format-date
20754 (org-time-from-absolute date))
20755 (funcall org-agenda-format-date date))
20756 "\n")
20757 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20758 (put-text-property s (1- (point)) 'org-date-line t)
20759 (if (equal d today)
20760 (put-text-property s (1- (point)) 'org-today t))
20761 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20762 (put-text-property s (1- (point)) 'day d)))))
20763 (goto-char (point-min))
20764 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20765 (point-min)))
20766 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20767 (org-finalize-agenda)
20768 (setq buffer-read-only t)))
20770 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20771 "Return a list of all relevant day numbers from BEG to END buffer positions.
20772 If NO-RANGES is non-nil, include only the start and end dates of a range,
20773 not every single day in the range. If FORCE-TODAY is non-nil, make
20774 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20775 inactive time stamps (those in square brackets) are included.
20776 When EMPTY is non-nil, also include days without any entries."
20777 (let ((re (concat
20778 (if pre-re pre-re "")
20779 (if inactive org-ts-regexp-both org-ts-regexp)))
20780 dates dates1 date day day1 day2 ts1 ts2)
20781 (if force-today
20782 (setq dates (list (time-to-days (current-time)))))
20783 (save-excursion
20784 (goto-char beg)
20785 (while (re-search-forward re end t)
20786 (setq day (time-to-days (org-time-string-to-time
20787 (substring (match-string 1) 0 10))))
20788 (or (memq day dates) (push day dates)))
20789 (unless no-ranges
20790 (goto-char beg)
20791 (while (re-search-forward org-tr-regexp end t)
20792 (setq ts1 (substring (match-string 1) 0 10)
20793 ts2 (substring (match-string 2) 0 10)
20794 day1 (time-to-days (org-time-string-to-time ts1))
20795 day2 (time-to-days (org-time-string-to-time ts2)))
20796 (while (< (setq day1 (1+ day1)) day2)
20797 (or (memq day1 dates) (push day1 dates)))))
20798 (setq dates (sort dates '<))
20799 (when empty
20800 (while (setq day (pop dates))
20801 (setq day2 (car dates))
20802 (push day dates1)
20803 (when (and day2 empty)
20804 (if (or (eq empty t)
20805 (and (numberp empty) (<= (- day2 day) empty)))
20806 (while (< (setq day (1+ day)) day2)
20807 (push (list day) dates1))
20808 (push (cons :omitted (- day2 day)) dates1))))
20809 (setq dates (nreverse dates1)))
20810 dates)))
20812 ;;; Agenda Daily/Weekly
20814 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20815 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20816 (defvar org-agenda-last-arguments nil
20817 "The arguments of the previous call to org-agenda")
20818 (defvar org-starting-day nil) ; local variable in the agenda buffer
20819 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20820 (defvar org-include-all-loc nil) ; local variable
20821 (defvar org-agenda-remove-date nil) ; dynamically scoped
20823 ;;;###autoload
20824 (defun org-agenda-list (&optional include-all start-day ndays)
20825 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20826 The view will be for the current day or week, but from the overview buffer
20827 you will be able to go to other days/weeks.
20829 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20830 all unfinished TODO items will also be shown, before the agenda.
20831 This feature is considered obsolete, please use the TODO list or a block
20832 agenda instead.
20834 With a numeric prefix argument in an interactive call, the agenda will
20835 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20836 the number of days. NDAYS defaults to `org-agenda-ndays'.
20838 START-DAY defaults to TODAY, or to the most recent match for the weekday
20839 given in `org-agenda-start-on-weekday'."
20840 (interactive "P")
20841 (if (and (integerp include-all) (> include-all 0))
20842 (setq ndays include-all include-all nil))
20843 (setq ndays (or ndays org-agenda-ndays)
20844 start-day (or start-day org-agenda-start-day))
20845 (if org-agenda-overriding-arguments
20846 (setq include-all (car org-agenda-overriding-arguments)
20847 start-day (nth 1 org-agenda-overriding-arguments)
20848 ndays (nth 2 org-agenda-overriding-arguments)))
20849 (if (stringp start-day)
20850 ;; Convert to an absolute day number
20851 (setq start-day (time-to-days (org-read-date nil t start-day))))
20852 (setq org-agenda-last-arguments (list include-all start-day ndays))
20853 (org-compile-prefix-format 'agenda)
20854 (org-set-sorting-strategy 'agenda)
20855 (require 'calendar)
20856 (let* ((org-agenda-start-on-weekday
20857 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20858 org-agenda-start-on-weekday nil))
20859 (thefiles (org-agenda-files))
20860 (files thefiles)
20861 (today (time-to-days
20862 (time-subtract (current-time)
20863 (list 0 (* 3600 org-extend-today-until) 0))))
20864 (sd (or start-day today))
20865 (start (if (or (null org-agenda-start-on-weekday)
20866 (< org-agenda-ndays 7))
20868 (let* ((nt (calendar-day-of-week
20869 (calendar-gregorian-from-absolute sd)))
20870 (n1 org-agenda-start-on-weekday)
20871 (d (- nt n1)))
20872 (- sd (+ (if (< d 0) 7 0) d)))))
20873 (day-numbers (list start))
20874 (day-cnt 0)
20875 (inhibit-redisplay (not debug-on-error))
20876 s e rtn rtnall file date d start-pos end-pos todayp nd)
20877 (setq org-agenda-redo-command
20878 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
20879 ;; Make the list of days
20880 (setq ndays (or ndays org-agenda-ndays)
20881 nd ndays)
20882 (while (> ndays 1)
20883 (push (1+ (car day-numbers)) day-numbers)
20884 (setq ndays (1- ndays)))
20885 (setq day-numbers (nreverse day-numbers))
20886 (org-prepare-agenda "Day/Week")
20887 (org-set-local 'org-starting-day (car day-numbers))
20888 (org-set-local 'org-include-all-loc include-all)
20889 (org-set-local 'org-agenda-span
20890 (org-agenda-ndays-to-span nd))
20891 (when (and (or include-all org-agenda-include-all-todo)
20892 (member today day-numbers))
20893 (setq files thefiles
20894 rtnall nil)
20895 (while (setq file (pop files))
20896 (catch 'nextfile
20897 (org-check-agenda-file file)
20898 (setq date (calendar-gregorian-from-absolute today)
20899 rtn (org-agenda-get-day-entries
20900 file date :todo))
20901 (setq rtnall (append rtnall rtn))))
20902 (when rtnall
20903 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
20904 (add-text-properties (point-min) (1- (point))
20905 (list 'face 'org-agenda-structure))
20906 (insert (org-finalize-agenda-entries rtnall) "\n")))
20907 (unless org-agenda-compact-blocks
20908 (setq s (point))
20909 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
20910 "-agenda:\n")
20911 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
20912 'org-date-line t)))
20913 (while (setq d (pop day-numbers))
20914 (setq date (calendar-gregorian-from-absolute d)
20915 s (point))
20916 (if (or (setq todayp (= d today))
20917 (and (not start-pos) (= d sd)))
20918 (setq start-pos (point))
20919 (if (and start-pos (not end-pos))
20920 (setq end-pos (point))))
20921 (setq files thefiles
20922 rtnall nil)
20923 (while (setq file (pop files))
20924 (catch 'nextfile
20925 (org-check-agenda-file file)
20926 (if org-agenda-show-log
20927 (setq rtn (org-agenda-get-day-entries
20928 file date
20929 :deadline :scheduled :timestamp :sexp :closed))
20930 (setq rtn (org-agenda-get-day-entries
20931 file date
20932 :deadline :scheduled :sexp :timestamp)))
20933 (setq rtnall (append rtnall rtn))))
20934 (if org-agenda-include-diary
20935 (progn
20936 (require 'diary-lib)
20937 (setq rtn (org-get-entries-from-diary date))
20938 (setq rtnall (append rtnall rtn))))
20939 (if (or rtnall org-agenda-show-all-dates)
20940 (progn
20941 (setq day-cnt (1+ day-cnt))
20942 (insert
20943 (if (stringp org-agenda-format-date)
20944 (format-time-string org-agenda-format-date
20945 (org-time-from-absolute date))
20946 (funcall org-agenda-format-date date))
20947 "\n")
20948 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20949 (put-text-property s (1- (point)) 'org-date-line t)
20950 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
20951 (if todayp (put-text-property s (1- (point)) 'org-today t))
20952 (if rtnall (insert
20953 (org-finalize-agenda-entries
20954 (org-agenda-add-time-grid-maybe
20955 rtnall nd todayp))
20956 "\n"))
20957 (put-text-property s (1- (point)) 'day d)
20958 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
20959 (goto-char (point-min))
20960 (org-fit-agenda-window)
20961 (unless (and (pos-visible-in-window-p (point-min))
20962 (pos-visible-in-window-p (point-max)))
20963 (goto-char (1- (point-max)))
20964 (recenter -1)
20965 (if (not (pos-visible-in-window-p (or start-pos 1)))
20966 (progn
20967 (goto-char (or start-pos 1))
20968 (recenter 1))))
20969 (goto-char (or start-pos 1))
20970 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
20971 (org-finalize-agenda)
20972 (setq buffer-read-only t)
20973 (message "")))
20975 (defun org-agenda-ndays-to-span (n)
20976 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
20978 ;;; Agenda word search
20980 (defvar org-agenda-search-history nil)
20982 ;;;###autoload
20983 (defun org-search-view (&optional arg string)
20984 "Show all entries that contain words or regular expressions.
20985 If the first character of the search string is an asterisks,
20986 search only the headlines.
20988 The search string is broken into \"words\" by splitting at whitespace.
20989 The individual words are then interpreted as a boolean expression with
20990 logical AND. Words prefixed with a minus must not occur in the entry.
20991 Words without a prefix or prefixed with a plus must occur in the entry.
20992 Matching is case-insensitive and the words are enclosed by word delimiters.
20994 Words enclosed by curly braces are interpreted as regular expressions
20995 that must or must not match in the entry.
20997 This command searches the agenda files, and in addition the files listed
20998 in `org-agenda-text-search-extra-files'."
20999 (interactive "P")
21000 (org-compile-prefix-format 'search)
21001 (org-set-sorting-strategy 'search)
21002 (org-prepare-agenda "SEARCH")
21003 (let* ((props (list 'face nil
21004 'done-face 'org-done
21005 'org-not-done-regexp org-not-done-regexp
21006 'org-todo-regexp org-todo-regexp
21007 'mouse-face 'highlight
21008 'keymap org-agenda-keymap
21009 'help-echo (format "mouse-2 or RET jump to location")))
21010 regexp rtn rtnall files file pos
21011 marker priority category tags c neg re
21012 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21013 (unless (and (not arg)
21014 (stringp string)
21015 (string-match "\\S-" string))
21016 (setq string (read-string "[+-]Word/{Regexp} ...: "
21017 (cond
21018 ((integerp arg) (cons string arg))
21019 (arg string))
21020 'org-agenda-search-history)))
21021 (setq org-agenda-redo-command
21022 (list 'org-search-view 'current-prefix-arg string))
21023 (setq org-agenda-query-string string)
21025 (if (equal (string-to-char string) ?*)
21026 (setq hdl-only t
21027 words (substring string 1))
21028 (setq words string))
21029 (setq words (org-split-string words))
21030 (mapc (lambda (w)
21031 (setq c (string-to-char w))
21032 (if (equal c ?-)
21033 (setq neg t w (substring w 1))
21034 (if (equal c ?+)
21035 (setq neg nil w (substring w 1))
21036 (setq neg nil)))
21037 (if (string-match "\\`{.*}\\'" w)
21038 (setq re (substring w 1 -1))
21039 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21040 (if neg (push re regexps-) (push re regexps+)))
21041 words)
21042 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21043 (if (not regexps+)
21044 (setq regexp (concat "^" org-outline-regexp))
21045 (setq regexp (pop regexps+))
21046 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21047 regexp))))
21048 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21049 rtnall nil)
21050 (while (setq file (pop files))
21051 (setq ee nil)
21052 (catch 'nextfile
21053 (org-check-agenda-file file)
21054 (setq buffer (if (file-exists-p file)
21055 (org-get-agenda-file-buffer file)
21056 (error "No such file %s" file)))
21057 (if (not buffer)
21058 ;; If file does not exist, make sure an error message is sent
21059 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21060 file))))
21061 (with-current-buffer buffer
21062 (unless (org-mode-p)
21063 (error "Agenda file %s is not in `org-mode'" file))
21064 (let ((case-fold-search t))
21065 (save-excursion
21066 (save-restriction
21067 (if org-agenda-restrict
21068 (narrow-to-region org-agenda-restrict-begin
21069 org-agenda-restrict-end)
21070 (widen))
21071 (goto-char (point-min))
21072 (unless (or (org-on-heading-p)
21073 (outline-next-heading))
21074 (throw 'nextfile t))
21075 (goto-char (max (point-min) (1- (point))))
21076 (while (re-search-forward regexp nil t)
21077 (org-back-to-heading t)
21078 (skip-chars-forward "* ")
21079 (setq beg (point-at-bol)
21080 beg1 (point)
21081 end (progn (outline-next-heading) (point)))
21082 (catch :skip
21083 (goto-char beg)
21084 (org-agenda-skip)
21085 (setq str (buffer-substring-no-properties
21086 (point-at-bol)
21087 (if hdl-only (point-at-eol) end)))
21088 (mapc (lambda (wr) (when (string-match wr str)
21089 (goto-char (1- end))
21090 (throw :skip t)))
21091 regexps-)
21092 (mapc (lambda (wr) (unless (string-match wr str)
21093 (goto-char (1- end))
21094 (throw :skip t)))
21095 regexps+)
21096 (goto-char beg)
21097 (setq marker (org-agenda-new-marker (point))
21098 category (org-get-category)
21099 tags (org-get-tags-at (point))
21100 txt (org-format-agenda-item
21102 (buffer-substring-no-properties
21103 beg1 (point-at-eol))
21104 category tags))
21105 (org-add-props txt props
21106 'org-marker marker 'org-hd-marker marker
21107 'priority 1000 'org-category category
21108 'type "search")
21109 (push txt ee)
21110 (goto-char (1- end)))))))))
21111 (setq rtn (nreverse ee))
21112 (setq rtnall (append rtnall rtn)))
21113 (if org-agenda-overriding-header
21114 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21115 nil 'face 'org-agenda-structure) "\n")
21116 (insert "Search words: ")
21117 (add-text-properties (point-min) (1- (point))
21118 (list 'face 'org-agenda-structure))
21119 (setq pos (point))
21120 (insert string "\n")
21121 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21122 (setq pos (point))
21123 (unless org-agenda-multi
21124 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21125 (add-text-properties pos (1- (point))
21126 (list 'face 'org-agenda-structure))))
21127 (when rtnall
21128 (insert (org-finalize-agenda-entries rtnall) "\n"))
21129 (goto-char (point-min))
21130 (org-fit-agenda-window)
21131 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21132 (org-finalize-agenda)
21133 (setq buffer-read-only t)))
21135 ;;; Agenda TODO list
21137 (defvar org-select-this-todo-keyword nil)
21138 (defvar org-last-arg nil)
21140 ;;;###autoload
21141 (defun org-todo-list (arg)
21142 "Show all TODO entries from all agenda file in a single list.
21143 The prefix arg can be used to select a specific TODO keyword and limit
21144 the list to these. When using \\[universal-argument], you will be prompted
21145 for a keyword. A numeric prefix directly selects the Nth keyword in
21146 `org-todo-keywords-1'."
21147 (interactive "P")
21148 (require 'calendar)
21149 (org-compile-prefix-format 'todo)
21150 (org-set-sorting-strategy 'todo)
21151 (org-prepare-agenda "TODO")
21152 (let* ((today (time-to-days (current-time)))
21153 (date (calendar-gregorian-from-absolute today))
21154 (kwds org-todo-keywords-for-agenda)
21155 (completion-ignore-case t)
21156 (org-select-this-todo-keyword
21157 (if (stringp arg) arg
21158 (and arg (integerp arg) (> arg 0)
21159 (nth (1- arg) kwds))))
21160 rtn rtnall files file pos)
21161 (when (equal arg '(4))
21162 (setq org-select-this-todo-keyword
21163 (completing-read "Keyword (or KWD1|K2D2|...): "
21164 (mapcar 'list kwds) nil nil)))
21165 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21166 (org-set-local 'org-last-arg arg)
21167 (setq org-agenda-redo-command
21168 '(org-todo-list (or current-prefix-arg org-last-arg)))
21169 (setq files (org-agenda-files)
21170 rtnall nil)
21171 (while (setq file (pop files))
21172 (catch 'nextfile
21173 (org-check-agenda-file file)
21174 (setq rtn (org-agenda-get-day-entries file date :todo))
21175 (setq rtnall (append rtnall rtn))))
21176 (if org-agenda-overriding-header
21177 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21178 nil 'face 'org-agenda-structure) "\n")
21179 (insert "Global list of TODO items of type: ")
21180 (add-text-properties (point-min) (1- (point))
21181 (list 'face 'org-agenda-structure))
21182 (setq pos (point))
21183 (insert (or org-select-this-todo-keyword "ALL") "\n")
21184 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21185 (setq pos (point))
21186 (unless org-agenda-multi
21187 (insert "Available with `N r': (0)ALL")
21188 (let ((n 0) s)
21189 (mapc (lambda (x)
21190 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21191 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21192 (insert "\n "))
21193 (insert " " s))
21194 kwds))
21195 (insert "\n"))
21196 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21197 (when rtnall
21198 (insert (org-finalize-agenda-entries rtnall) "\n"))
21199 (goto-char (point-min))
21200 (org-fit-agenda-window)
21201 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21202 (org-finalize-agenda)
21203 (setq buffer-read-only t)))
21205 ;;; Agenda tags match
21207 ;;;###autoload
21208 (defun org-tags-view (&optional todo-only match)
21209 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21210 The prefix arg TODO-ONLY limits the search to TODO entries."
21211 (interactive "P")
21212 (org-compile-prefix-format 'tags)
21213 (org-set-sorting-strategy 'tags)
21214 (let* ((org-tags-match-list-sublevels
21215 (if todo-only t org-tags-match-list-sublevels))
21216 (completion-ignore-case t)
21217 rtn rtnall files file pos matcher
21218 buffer)
21219 (setq matcher (org-make-tags-matcher match)
21220 match (car matcher) matcher (cdr matcher))
21221 (org-prepare-agenda (concat "TAGS " match))
21222 (setq org-agenda-redo-command
21223 (list 'org-tags-view (list 'quote todo-only)
21224 (list 'if 'current-prefix-arg nil match)))
21225 (setq files (org-agenda-files)
21226 rtnall nil)
21227 (while (setq file (pop files))
21228 (catch 'nextfile
21229 (org-check-agenda-file file)
21230 (setq buffer (if (file-exists-p file)
21231 (org-get-agenda-file-buffer file)
21232 (error "No such file %s" file)))
21233 (if (not buffer)
21234 ;; If file does not exist, merror message to agenda
21235 (setq rtn (list
21236 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21237 rtnall (append rtnall rtn))
21238 (with-current-buffer buffer
21239 (unless (org-mode-p)
21240 (error "Agenda file %s is not in `org-mode'" file))
21241 (save-excursion
21242 (save-restriction
21243 (if org-agenda-restrict
21244 (narrow-to-region org-agenda-restrict-begin
21245 org-agenda-restrict-end)
21246 (widen))
21247 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21248 (setq rtnall (append rtnall rtn))))))))
21249 (if org-agenda-overriding-header
21250 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21251 nil 'face 'org-agenda-structure) "\n")
21252 (insert "Headlines with TAGS match: ")
21253 (add-text-properties (point-min) (1- (point))
21254 (list 'face 'org-agenda-structure))
21255 (setq pos (point))
21256 (insert match "\n")
21257 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21258 (setq pos (point))
21259 (unless org-agenda-multi
21260 (insert "Press `C-u r' to search again with new search string\n"))
21261 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21262 (when rtnall
21263 (insert (org-finalize-agenda-entries rtnall) "\n"))
21264 (goto-char (point-min))
21265 (org-fit-agenda-window)
21266 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21267 (org-finalize-agenda)
21268 (setq buffer-read-only t)))
21270 ;;; Agenda Finding stuck projects
21272 (defvar org-agenda-skip-regexp nil
21273 "Regular expression used in skipping subtrees for the agenda.
21274 This is basically a temporary global variable that can be set and then
21275 used by user-defined selections using `org-agenda-skip-function'.")
21277 (defvar org-agenda-overriding-header nil
21278 "When this is set during todo and tags searches, will replace header.")
21280 (defun org-agenda-skip-subtree-when-regexp-matches ()
21281 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21282 If yes, it returns the end position of this tree, causing agenda commands
21283 to skip this subtree. This is a function that can be put into
21284 `org-agenda-skip-function' for the duration of a command."
21285 (let ((end (save-excursion (org-end-of-subtree t)))
21286 skip)
21287 (save-excursion
21288 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21289 (and skip end)))
21291 (defun org-agenda-skip-entry-if (&rest conditions)
21292 "Skip entry if any of CONDITIONS is true.
21293 See `org-agenda-skip-if' for details."
21294 (org-agenda-skip-if nil conditions))
21296 (defun org-agenda-skip-subtree-if (&rest conditions)
21297 "Skip entry if any of CONDITIONS is true.
21298 See `org-agenda-skip-if' for details."
21299 (org-agenda-skip-if t conditions))
21301 (defun org-agenda-skip-if (subtree conditions)
21302 "Checks current entity for CONDITIONS.
21303 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21304 the entry, i.e. the text before the next heading is checked.
21306 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21307 from different tests. Valid conditions are:
21309 scheduled Check if there is a scheduled cookie
21310 notscheduled Check if there is no scheduled cookie
21311 deadline Check if there is a deadline
21312 notdeadline Check if there is no deadline
21313 regexp Check if regexp matches
21314 notregexp Check if regexp does not match.
21316 The regexp is taken from the conditions list, it must come right after
21317 the `regexp' or `notregexp' element.
21319 If any of these conditions is met, this function returns the end point of
21320 the entity, causing the search to continue from there. This is a function
21321 that can be put into `org-agenda-skip-function' for the duration of a command."
21322 (let (beg end m)
21323 (org-back-to-heading t)
21324 (setq beg (point)
21325 end (if subtree
21326 (progn (org-end-of-subtree t) (point))
21327 (progn (outline-next-heading) (1- (point)))))
21328 (goto-char beg)
21329 (and
21331 (and (memq 'scheduled conditions)
21332 (re-search-forward org-scheduled-time-regexp end t))
21333 (and (memq 'notscheduled conditions)
21334 (not (re-search-forward org-scheduled-time-regexp end t)))
21335 (and (memq 'deadline conditions)
21336 (re-search-forward org-deadline-time-regexp end t))
21337 (and (memq 'notdeadline conditions)
21338 (not (re-search-forward org-deadline-time-regexp end t)))
21339 (and (setq m (memq 'regexp conditions))
21340 (stringp (nth 1 m))
21341 (re-search-forward (nth 1 m) end t))
21342 (and (setq m (memq 'notregexp conditions))
21343 (stringp (nth 1 m))
21344 (not (re-search-forward (nth 1 m) end t))))
21345 end)))
21347 ;;;###autoload
21348 (defun org-agenda-list-stuck-projects (&rest ignore)
21349 "Create agenda view for projects that are stuck.
21350 Stuck projects are project that have no next actions. For the definitions
21351 of what a project is and how to check if it stuck, customize the variable
21352 `org-stuck-projects'.
21353 MATCH is being ignored."
21354 (interactive)
21355 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21356 ;; FIXME: we could have used org-agenda-skip-if here.
21357 (org-agenda-overriding-header "List of stuck projects: ")
21358 (matcher (nth 0 org-stuck-projects))
21359 (todo (nth 1 org-stuck-projects))
21360 (todo-wds (if (member "*" todo)
21361 (progn
21362 (org-prepare-agenda-buffers (org-agenda-files))
21363 (org-delete-all
21364 org-done-keywords-for-agenda
21365 (copy-sequence org-todo-keywords-for-agenda)))
21366 todo))
21367 (todo-re (concat "^\\*+[ \t]+\\("
21368 (mapconcat 'identity todo-wds "\\|")
21369 "\\)\\>"))
21370 (tags (nth 2 org-stuck-projects))
21371 (tags-re (if (member "*" tags)
21372 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21373 (concat "^\\*+ .*:\\("
21374 (mapconcat 'identity tags "\\|")
21375 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21376 (gen-re (nth 3 org-stuck-projects))
21377 (re-list
21378 (delq nil
21379 (list
21380 (if todo todo-re)
21381 (if tags tags-re)
21382 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21383 gen-re)))))
21384 (setq org-agenda-skip-regexp
21385 (if re-list
21386 (mapconcat 'identity re-list "\\|")
21387 (error "No information how to identify unstuck projects")))
21388 (org-tags-view nil matcher)
21389 (with-current-buffer org-agenda-buffer-name
21390 (setq org-agenda-redo-command
21391 '(org-agenda-list-stuck-projects
21392 (or current-prefix-arg org-last-arg))))))
21394 ;;; Diary integration
21396 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21398 (defun org-get-entries-from-diary (date)
21399 "Get the (Emacs Calendar) diary entries for DATE."
21400 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21401 (diary-display-hook '(fancy-diary-display))
21402 (pop-up-frames nil)
21403 (list-diary-entries-hook
21404 (cons 'org-diary-default-entry list-diary-entries-hook))
21405 (diary-file-name-prefix-function nil) ; turn this feature off
21406 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21407 entries
21408 (org-disable-agenda-to-diary t))
21409 (save-excursion
21410 (save-window-excursion
21411 (funcall (if (fboundp 'diary-list-entries)
21412 'diary-list-entries 'list-diary-entries)
21413 date 1)))
21414 (if (not (get-buffer fancy-diary-buffer))
21415 (setq entries nil)
21416 (with-current-buffer fancy-diary-buffer
21417 (setq buffer-read-only nil)
21418 (if (zerop (buffer-size))
21419 ;; No entries
21420 (setq entries nil)
21421 ;; Omit the date and other unnecessary stuff
21422 (org-agenda-cleanup-fancy-diary)
21423 ;; Add prefix to each line and extend the text properties
21424 (if (zerop (buffer-size))
21425 (setq entries nil)
21426 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21427 (set-buffer-modified-p nil)
21428 (kill-buffer fancy-diary-buffer)))
21429 (when entries
21430 (setq entries (org-split-string entries "\n"))
21431 (setq entries
21432 (mapcar
21433 (lambda (x)
21434 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21435 ;; Extend the text properties to the beginning of the line
21436 (org-add-props x (text-properties-at (1- (length x)) x)
21437 'type "diary" 'date date))
21438 entries)))))
21440 (defun org-agenda-cleanup-fancy-diary ()
21441 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21442 This gets rid of the date, the underline under the date, and
21443 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21444 date. It also removes lines that contain only whitespace."
21445 (goto-char (point-min))
21446 (if (looking-at ".*?:[ \t]*")
21447 (progn
21448 (replace-match "")
21449 (re-search-forward "\n=+$" nil t)
21450 (replace-match "")
21451 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21452 (re-search-forward "\n=+$" nil t)
21453 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21454 (goto-char (point-min))
21455 (while (re-search-forward "^ +\n" nil t)
21456 (replace-match ""))
21457 (goto-char (point-min))
21458 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21459 (replace-match "")))
21461 ;; Make sure entries from the diary have the right text properties.
21462 (eval-after-load "diary-lib"
21463 '(if (boundp 'diary-modify-entry-list-string-function)
21464 ;; We can rely on the hook, nothing to do
21466 ;; Hook not avaiable, must use advice to make this work
21467 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21468 "Make the position visible."
21469 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21470 (stringp string)
21471 buffer-file-name)
21472 (setq string (org-modify-diary-entry-string string))))))
21474 (defun org-modify-diary-entry-string (string)
21475 "Add text properties to string, allowing org-mode to act on it."
21476 (org-add-props string nil
21477 'mouse-face 'highlight
21478 'keymap org-agenda-keymap
21479 'help-echo (if buffer-file-name
21480 (format "mouse-2 or RET jump to diary file %s"
21481 (abbreviate-file-name buffer-file-name))
21483 'org-agenda-diary-link t
21484 'org-marker (org-agenda-new-marker (point-at-bol))))
21486 (defun org-diary-default-entry ()
21487 "Add a dummy entry to the diary.
21488 Needed to avoid empty dates which mess up holiday display."
21489 ;; Catch the error if dealing with the new add-to-diary-alist
21490 (when org-disable-agenda-to-diary
21491 (condition-case nil
21492 (add-to-diary-list original-date "Org-mode dummy" "")
21493 (error
21494 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21496 ;;;###autoload
21497 (defun org-diary (&rest args)
21498 "Return diary information from org-files.
21499 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21500 It accesses org files and extracts information from those files to be
21501 listed in the diary. The function accepts arguments specifying what
21502 items should be listed. The following arguments are allowed:
21504 :timestamp List the headlines of items containing a date stamp or
21505 date range matching the selected date. Deadlines will
21506 also be listed, on the expiration day.
21508 :sexp List entries resulting from diary-like sexps.
21510 :deadline List any deadlines past due, or due within
21511 `org-deadline-warning-days'. The listing occurs only
21512 in the diary for *today*, not at any other date. If
21513 an entry is marked DONE, it is no longer listed.
21515 :scheduled List all items which are scheduled for the given date.
21516 The diary for *today* also contains items which were
21517 scheduled earlier and are not yet marked DONE.
21519 :todo List all TODO items from the org-file. This may be a
21520 long list - so this is not turned on by default.
21521 Like deadlines, these entries only show up in the
21522 diary for *today*, not at any other date.
21524 The call in the diary file should look like this:
21526 &%%(org-diary) ~/path/to/some/orgfile.org
21528 Use a separate line for each org file to check. Or, if you omit the file name,
21529 all files listed in `org-agenda-files' will be checked automatically:
21531 &%%(org-diary)
21533 If you don't give any arguments (as in the example above), the default
21534 arguments (:deadline :scheduled :timestamp :sexp) are used.
21535 So the example above may also be written as
21537 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21539 The function expects the lisp variables `entry' and `date' to be provided
21540 by the caller, because this is how the calendar works. Don't use this
21541 function from a program - use `org-agenda-get-day-entries' instead."
21542 (when (> (- (time-to-seconds (current-time))
21543 org-agenda-last-marker-time)
21545 (org-agenda-reset-markers))
21546 (org-compile-prefix-format 'agenda)
21547 (org-set-sorting-strategy 'agenda)
21548 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21549 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21550 (list entry)
21551 (org-agenda-files t)))
21552 file rtn results)
21553 (org-prepare-agenda-buffers files)
21554 ;; If this is called during org-agenda, don't return any entries to
21555 ;; the calendar. Org Agenda will list these entries itself.
21556 (if org-disable-agenda-to-diary (setq files nil))
21557 (while (setq file (pop files))
21558 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21559 (setq results (append results rtn)))
21560 (if results
21561 (concat (org-finalize-agenda-entries results) "\n"))))
21563 ;;; Agenda entry finders
21565 (defun org-agenda-get-day-entries (file date &rest args)
21566 "Does the work for `org-diary' and `org-agenda'.
21567 FILE is the path to a file to be checked for entries. DATE is date like
21568 the one returned by `calendar-current-date'. ARGS are symbols indicating
21569 which kind of entries should be extracted. For details about these, see
21570 the documentation of `org-diary'."
21571 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21572 (let* ((org-startup-folded nil)
21573 (org-startup-align-all-tables nil)
21574 (buffer (if (file-exists-p file)
21575 (org-get-agenda-file-buffer file)
21576 (error "No such file %s" file)))
21577 arg results rtn)
21578 (if (not buffer)
21579 ;; If file does not exist, make sure an error message ends up in diary
21580 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21581 (with-current-buffer buffer
21582 (unless (org-mode-p)
21583 (error "Agenda file %s is not in `org-mode'" file))
21584 (let ((case-fold-search nil))
21585 (save-excursion
21586 (save-restriction
21587 (if org-agenda-restrict
21588 (narrow-to-region org-agenda-restrict-begin
21589 org-agenda-restrict-end)
21590 (widen))
21591 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21592 (while (setq arg (pop args))
21593 (cond
21594 ((and (eq arg :todo)
21595 (equal date (calendar-current-date)))
21596 (setq rtn (org-agenda-get-todos))
21597 (setq results (append results rtn)))
21598 ((eq arg :timestamp)
21599 (setq rtn (org-agenda-get-blocks))
21600 (setq results (append results rtn))
21601 (setq rtn (org-agenda-get-timestamps))
21602 (setq results (append results rtn)))
21603 ((eq arg :sexp)
21604 (setq rtn (org-agenda-get-sexps))
21605 (setq results (append results rtn)))
21606 ((eq arg :scheduled)
21607 (setq rtn (org-agenda-get-scheduled))
21608 (setq results (append results rtn)))
21609 ((eq arg :closed)
21610 (setq rtn (org-agenda-get-closed))
21611 (setq results (append results rtn)))
21612 ((eq arg :deadline)
21613 (setq rtn (org-agenda-get-deadlines))
21614 (setq results (append results rtn))))))))
21615 results))))
21617 (defun org-entry-is-todo-p ()
21618 (member (org-get-todo-state) org-not-done-keywords))
21620 (defun org-entry-is-done-p ()
21621 (member (org-get-todo-state) org-done-keywords))
21623 (defun org-get-todo-state ()
21624 (save-excursion
21625 (org-back-to-heading t)
21626 (and (looking-at org-todo-line-regexp)
21627 (match-end 2)
21628 (match-string 2))))
21630 (defun org-at-date-range-p (&optional inactive-ok)
21631 "Is the cursor inside a date range?"
21632 (interactive)
21633 (save-excursion
21634 (catch 'exit
21635 (let ((pos (point)))
21636 (skip-chars-backward "^[<\r\n")
21637 (skip-chars-backward "<[")
21638 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21639 (>= (match-end 0) pos)
21640 (throw 'exit t))
21641 (skip-chars-backward "^<[\r\n")
21642 (skip-chars-backward "<[")
21643 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21644 (>= (match-end 0) pos)
21645 (throw 'exit t)))
21646 nil)))
21648 (defun org-agenda-get-todos ()
21649 "Return the TODO information for agenda display."
21650 (let* ((props (list 'face nil
21651 'done-face 'org-done
21652 'org-not-done-regexp org-not-done-regexp
21653 'org-todo-regexp org-todo-regexp
21654 'mouse-face 'highlight
21655 'keymap org-agenda-keymap
21656 'help-echo
21657 (format "mouse-2 or RET jump to org file %s"
21658 (abbreviate-file-name buffer-file-name))))
21659 ;; FIXME: get rid of the \n at some point but watch out
21660 (regexp (concat "^\\*+[ \t]+\\("
21661 (if org-select-this-todo-keyword
21662 (if (equal org-select-this-todo-keyword "*")
21663 org-todo-regexp
21664 (concat "\\<\\("
21665 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21666 "\\)\\>"))
21667 org-not-done-regexp)
21668 "[^\n\r]*\\)"))
21669 marker priority category tags
21670 ee txt beg end)
21671 (goto-char (point-min))
21672 (while (re-search-forward regexp nil t)
21673 (catch :skip
21674 (save-match-data
21675 (beginning-of-line)
21676 (setq beg (point) end (progn (outline-next-heading) (point)))
21677 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21678 (re-search-forward org-ts-regexp end t))
21679 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21680 (re-search-forward org-scheduled-time-regexp end t))
21681 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21682 (re-search-forward org-deadline-time-regexp end t)
21683 (org-deadline-close (match-string 1))))
21684 (goto-char (1+ beg))
21685 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21686 (throw :skip nil)))
21687 (goto-char beg)
21688 (org-agenda-skip)
21689 (goto-char (match-beginning 1))
21690 (setq marker (org-agenda-new-marker (match-beginning 0))
21691 category (org-get-category)
21692 tags (org-get-tags-at (point))
21693 txt (org-format-agenda-item "" (match-string 1) category tags)
21694 priority (1+ (org-get-priority txt)))
21695 (org-add-props txt props
21696 'org-marker marker 'org-hd-marker marker
21697 'priority priority 'org-category category
21698 'type "todo")
21699 (push txt ee)
21700 (if org-agenda-todo-list-sublevels
21701 (goto-char (match-end 1))
21702 (org-end-of-subtree 'invisible))))
21703 (nreverse ee)))
21705 (defconst org-agenda-no-heading-message
21706 "No heading for this item in buffer or region.")
21708 (defun org-agenda-get-timestamps ()
21709 "Return the date stamp information for agenda display."
21710 (let* ((props (list 'face nil
21711 'org-not-done-regexp org-not-done-regexp
21712 'org-todo-regexp org-todo-regexp
21713 'mouse-face 'highlight
21714 'keymap org-agenda-keymap
21715 'help-echo
21716 (format "mouse-2 or RET jump to org file %s"
21717 (abbreviate-file-name buffer-file-name))))
21718 (d1 (calendar-absolute-from-gregorian date))
21719 (remove-re
21720 (concat
21721 (regexp-quote
21722 (format-time-string
21723 "<%Y-%m-%d"
21724 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21725 ".*?>"))
21726 (regexp
21727 (concat
21728 (regexp-quote
21729 (substring
21730 (format-time-string
21731 (car org-time-stamp-formats)
21732 (apply 'encode-time ; DATE bound by calendar
21733 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21734 0 11))
21735 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21736 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21737 marker hdmarker deadlinep scheduledp donep tmp priority category
21738 ee txt timestr tags b0 b3 e3 head)
21739 (goto-char (point-min))
21740 (while (re-search-forward regexp nil t)
21741 (setq b0 (match-beginning 0)
21742 b3 (match-beginning 3) e3 (match-end 3))
21743 (catch :skip
21744 (and (org-at-date-range-p) (throw :skip nil))
21745 (org-agenda-skip)
21746 (if (and (match-end 1)
21747 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21748 (throw :skip nil))
21749 (if (and e3
21750 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21751 (throw :skip nil))
21752 (setq marker (org-agenda-new-marker b0)
21753 category (org-get-category b0)
21754 tmp (buffer-substring (max (point-min)
21755 (- b0 org-ds-keyword-length))
21757 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21758 deadlinep (string-match org-deadline-regexp tmp)
21759 scheduledp (string-match org-scheduled-regexp tmp)
21760 donep (org-entry-is-done-p))
21761 (if (or scheduledp deadlinep) (throw :skip t))
21762 (if (string-match ">" timestr)
21763 ;; substring should only run to end of time stamp
21764 (setq timestr (substring timestr 0 (match-end 0))))
21765 (save-excursion
21766 (if (re-search-backward "^\\*+ " nil t)
21767 (progn
21768 (goto-char (match-beginning 0))
21769 (setq hdmarker (org-agenda-new-marker)
21770 tags (org-get-tags-at))
21771 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21772 (setq head (match-string 1))
21773 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21774 (setq txt (org-format-agenda-item
21775 nil head category tags timestr nil
21776 remove-re)))
21777 (setq txt org-agenda-no-heading-message))
21778 (setq priority (org-get-priority txt))
21779 (org-add-props txt props
21780 'org-marker marker 'org-hd-marker hdmarker)
21781 (org-add-props txt nil 'priority priority
21782 'org-category category 'date date
21783 'type "timestamp")
21784 (push txt ee))
21785 (outline-next-heading)))
21786 (nreverse ee)))
21788 (defun org-agenda-get-sexps ()
21789 "Return the sexp information for agenda display."
21790 (require 'diary-lib)
21791 (let* ((props (list 'face nil
21792 'mouse-face 'highlight
21793 'keymap org-agenda-keymap
21794 'help-echo
21795 (format "mouse-2 or RET jump to org file %s"
21796 (abbreviate-file-name buffer-file-name))))
21797 (regexp "^&?%%(")
21798 marker category ee txt tags entry result beg b sexp sexp-entry)
21799 (goto-char (point-min))
21800 (while (re-search-forward regexp nil t)
21801 (catch :skip
21802 (org-agenda-skip)
21803 (setq beg (match-beginning 0))
21804 (goto-char (1- (match-end 0)))
21805 (setq b (point))
21806 (forward-sexp 1)
21807 (setq sexp (buffer-substring b (point)))
21808 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21809 (org-trim (match-string 1))
21810 ""))
21811 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21812 (when result
21813 (setq marker (org-agenda-new-marker beg)
21814 category (org-get-category beg))
21816 (if (string-match "\\S-" result)
21817 (setq txt result)
21818 (setq txt "SEXP entry returned empty string"))
21820 (setq txt (org-format-agenda-item
21821 "" txt category tags 'time))
21822 (org-add-props txt props 'org-marker marker)
21823 (org-add-props txt nil
21824 'org-category category 'date date
21825 'type "sexp")
21826 (push txt ee))))
21827 (nreverse ee)))
21829 (defun org-agenda-get-closed ()
21830 "Return the logged TODO entries for agenda display."
21831 (let* ((props (list 'mouse-face 'highlight
21832 'org-not-done-regexp org-not-done-regexp
21833 'org-todo-regexp org-todo-regexp
21834 'keymap org-agenda-keymap
21835 'help-echo
21836 (format "mouse-2 or RET jump to org file %s"
21837 (abbreviate-file-name buffer-file-name))))
21838 (regexp (concat
21839 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21840 (regexp-quote
21841 (substring
21842 (format-time-string
21843 (car org-time-stamp-formats)
21844 (apply 'encode-time ; DATE bound by calendar
21845 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21846 1 11))))
21847 marker hdmarker priority category tags closedp
21848 ee txt timestr)
21849 (goto-char (point-min))
21850 (while (re-search-forward regexp nil t)
21851 (catch :skip
21852 (org-agenda-skip)
21853 (setq marker (org-agenda-new-marker (match-beginning 0))
21854 closedp (equal (match-string 1) org-closed-string)
21855 category (org-get-category (match-beginning 0))
21856 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21857 ;; donep (org-entry-is-done-p)
21859 (if (string-match "\\]" timestr)
21860 ;; substring should only run to end of time stamp
21861 (setq timestr (substring timestr 0 (match-end 0))))
21862 (save-excursion
21863 (if (re-search-backward "^\\*+ " nil t)
21864 (progn
21865 (goto-char (match-beginning 0))
21866 (setq hdmarker (org-agenda-new-marker)
21867 tags (org-get-tags-at))
21868 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21869 (setq txt (org-format-agenda-item
21870 (if closedp "Closed: " "Clocked: ")
21871 (match-string 1) category tags timestr)))
21872 (setq txt org-agenda-no-heading-message))
21873 (setq priority 100000)
21874 (org-add-props txt props
21875 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
21876 'priority priority 'org-category category
21877 'type "closed" 'date date
21878 'undone-face 'org-warning 'done-face 'org-done)
21879 (push txt ee))
21880 (goto-char (point-at-eol))))
21881 (nreverse ee)))
21883 (defun org-agenda-get-deadlines ()
21884 "Return the deadline information for agenda display."
21885 (let* ((props (list 'mouse-face 'highlight
21886 'org-not-done-regexp org-not-done-regexp
21887 'org-todo-regexp org-todo-regexp
21888 'keymap org-agenda-keymap
21889 'help-echo
21890 (format "mouse-2 or RET jump to org file %s"
21891 (abbreviate-file-name buffer-file-name))))
21892 (regexp org-deadline-time-regexp)
21893 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21894 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21895 d2 diff dfrac wdays pos pos1 category tags
21896 ee txt head face s upcomingp donep timestr)
21897 (goto-char (point-min))
21898 (while (re-search-forward regexp nil t)
21899 (catch :skip
21900 (org-agenda-skip)
21901 (setq s (match-string 1)
21902 pos (1- (match-beginning 1))
21903 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21904 diff (- d2 d1)
21905 wdays (org-get-wdays s)
21906 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
21907 upcomingp (and todayp (> diff 0)))
21908 ;; When to show a deadline in the calendar:
21909 ;; If the expiration is within wdays warning time.
21910 ;; Past-due deadlines are only shown on the current date
21911 (if (or (and (<= diff wdays)
21912 (and todayp (not org-agenda-only-exact-dates)))
21913 (= diff 0))
21914 (save-excursion
21915 (setq category (org-get-category))
21916 (if (re-search-backward "^\\*+[ \t]+" nil t)
21917 (progn
21918 (goto-char (match-end 0))
21919 (setq pos1 (match-beginning 0))
21920 (setq tags (org-get-tags-at pos1))
21921 (setq head (buffer-substring-no-properties
21922 (point)
21923 (progn (skip-chars-forward "^\r\n")
21924 (point))))
21925 (setq donep (string-match org-looking-at-done-regexp head))
21926 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
21927 (setq timestr
21928 (concat (substring s (match-beginning 1)) " "))
21929 (setq timestr 'time))
21930 (if (and donep
21931 (or org-agenda-skip-deadline-if-done
21932 (not (= diff 0))))
21933 (setq txt nil)
21934 (setq txt (org-format-agenda-item
21935 (if (= diff 0)
21936 (car org-agenda-deadline-leaders)
21937 (format (nth 1 org-agenda-deadline-leaders)
21938 diff))
21939 head category tags timestr))))
21940 (setq txt org-agenda-no-heading-message))
21941 (when txt
21942 (setq face (org-agenda-deadline-face dfrac wdays))
21943 (org-add-props txt props
21944 'org-marker (org-agenda-new-marker pos)
21945 'org-hd-marker (org-agenda-new-marker pos1)
21946 'priority (+ (- diff)
21947 (org-get-priority txt))
21948 'org-category category
21949 'type (if upcomingp "upcoming-deadline" "deadline")
21950 'date (if upcomingp date d2)
21951 'face (if donep 'org-done face)
21952 'undone-face face 'done-face 'org-done)
21953 (push txt ee))))))
21954 (nreverse ee)))
21956 (defun org-agenda-deadline-face (fraction &optional wdays)
21957 "Return the face to displaying a deadline item.
21958 FRACTION is what fraction of the head-warning time has passed."
21959 (if (equal wdays 0) (setq fraction 1.))
21960 (let ((faces org-agenda-deadline-faces) f)
21961 (catch 'exit
21962 (while (setq f (pop faces))
21963 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
21965 (defun org-agenda-get-scheduled ()
21966 "Return the scheduled information for agenda display."
21967 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
21968 'org-todo-regexp org-todo-regexp
21969 'done-face 'org-done
21970 'mouse-face 'highlight
21971 'keymap org-agenda-keymap
21972 'help-echo
21973 (format "mouse-2 or RET jump to org file %s"
21974 (abbreviate-file-name buffer-file-name))))
21975 (regexp org-scheduled-time-regexp)
21976 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
21977 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
21978 d2 diff pos pos1 category tags
21979 ee txt head pastschedp donep face timestr s)
21980 (goto-char (point-min))
21981 (while (re-search-forward regexp nil t)
21982 (catch :skip
21983 (org-agenda-skip)
21984 (setq s (match-string 1)
21985 pos (1- (match-beginning 1))
21986 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
21987 ;;; is this right?
21988 ;;; do we need to do this for deadleine too????
21989 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
21990 diff (- d2 d1))
21991 (setq pastschedp (and todayp (< diff 0)))
21992 ;; When to show a scheduled item in the calendar:
21993 ;; If it is on or past the date.
21994 (if (or (and (< diff 0)
21995 (and todayp (not org-agenda-only-exact-dates)))
21996 (= diff 0))
21997 (save-excursion
21998 (setq category (org-get-category))
21999 (if (re-search-backward "^\\*+[ \t]+" nil t)
22000 (progn
22001 (goto-char (match-end 0))
22002 (setq pos1 (match-beginning 0))
22003 (setq tags (org-get-tags-at))
22004 (setq head (buffer-substring-no-properties
22005 (point)
22006 (progn (skip-chars-forward "^\r\n") (point))))
22007 (setq donep (string-match org-looking-at-done-regexp head))
22008 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22009 (setq timestr
22010 (concat (substring s (match-beginning 1)) " "))
22011 (setq timestr 'time))
22012 (if (and donep
22013 (or org-agenda-skip-scheduled-if-done
22014 (not (= diff 0))))
22015 (setq txt nil)
22016 (setq txt (org-format-agenda-item
22017 (if (= diff 0)
22018 (car org-agenda-scheduled-leaders)
22019 (format (nth 1 org-agenda-scheduled-leaders)
22020 (- 1 diff)))
22021 head category tags timestr))))
22022 (setq txt org-agenda-no-heading-message))
22023 (when txt
22024 (setq face (if pastschedp
22025 'org-scheduled-previously
22026 'org-scheduled-today))
22027 (org-add-props txt props
22028 'undone-face face
22029 'face (if donep 'org-done face)
22030 'org-marker (org-agenda-new-marker pos)
22031 'org-hd-marker (org-agenda-new-marker pos1)
22032 'type (if pastschedp "past-scheduled" "scheduled")
22033 'date (if pastschedp d2 date)
22034 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22035 'org-category category)
22036 (push txt ee))))))
22037 (nreverse ee)))
22039 (defun org-agenda-get-blocks ()
22040 "Return the date-range information for agenda display."
22041 (let* ((props (list 'face nil
22042 'org-not-done-regexp org-not-done-regexp
22043 'org-todo-regexp org-todo-regexp
22044 'mouse-face 'highlight
22045 'keymap org-agenda-keymap
22046 'help-echo
22047 (format "mouse-2 or RET jump to org file %s"
22048 (abbreviate-file-name buffer-file-name))))
22049 (regexp org-tr-regexp)
22050 (d0 (calendar-absolute-from-gregorian date))
22051 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22052 donep head)
22053 (goto-char (point-min))
22054 (while (re-search-forward regexp nil t)
22055 (catch :skip
22056 (org-agenda-skip)
22057 (setq pos (point))
22058 (setq timestr (match-string 0)
22059 s1 (match-string 1)
22060 s2 (match-string 2)
22061 d1 (time-to-days (org-time-string-to-time s1))
22062 d2 (time-to-days (org-time-string-to-time s2)))
22063 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22064 ;; Only allow days between the limits, because the normal
22065 ;; date stamps will catch the limits.
22066 (save-excursion
22067 (setq marker (org-agenda-new-marker (point)))
22068 (setq category (org-get-category))
22069 (if (re-search-backward "^\\*+ " nil t)
22070 (progn
22071 (goto-char (match-beginning 0))
22072 (setq hdmarker (org-agenda-new-marker (point)))
22073 (setq tags (org-get-tags-at))
22074 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22075 (setq head (match-string 1))
22076 (and org-agenda-skip-timestamp-if-done
22077 (org-entry-is-done-p)
22078 (throw :skip t))
22079 (setq txt (org-format-agenda-item
22080 (format (if (= d1 d2) "" "(%d/%d): ")
22081 (1+ (- d0 d1)) (1+ (- d2 d1)))
22082 head category tags
22083 (if (= d0 d1) timestr))))
22084 (setq txt org-agenda-no-heading-message))
22085 (org-add-props txt props
22086 'org-marker marker 'org-hd-marker hdmarker
22087 'type "block" 'date date
22088 'priority (org-get-priority txt) 'org-category category)
22089 (push txt ee)))
22090 (goto-char pos)))
22091 ;; Sort the entries by expiration date.
22092 (nreverse ee)))
22094 ;;; Agenda presentation and sorting
22096 (defconst org-plain-time-of-day-regexp
22097 (concat
22098 "\\(\\<[012]?[0-9]"
22099 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22100 "\\(--?"
22101 "\\(\\<[012]?[0-9]"
22102 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22103 "\\)?")
22104 "Regular expression to match a plain time or time range.
22105 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22106 groups carry important information:
22107 0 the full match
22108 1 the first time, range or not
22109 8 the second time, if it is a range.")
22111 (defconst org-plain-time-extension-regexp
22112 (concat
22113 "\\(\\<[012]?[0-9]"
22114 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22115 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22116 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22117 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22118 groups carry important information:
22119 0 the full match
22120 7 hours of duration
22121 9 minutes of duration")
22123 (defconst org-stamp-time-of-day-regexp
22124 (concat
22125 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22126 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22127 "\\(--?"
22128 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22129 "Regular expression to match a timestamp time or time range.
22130 After a match, the following groups carry important information:
22131 0 the full match
22132 1 date plus weekday, for backreferencing to make sure both times on same day
22133 2 the first time, range or not
22134 4 the second time, if it is a range.")
22136 (defvar org-prefix-has-time nil
22137 "A flag, set by `org-compile-prefix-format'.
22138 The flag is set if the currently compiled format contains a `%t'.")
22139 (defvar org-prefix-has-tag nil
22140 "A flag, set by `org-compile-prefix-format'.
22141 The flag is set if the currently compiled format contains a `%T'.")
22143 (defun org-format-agenda-item (extra txt &optional category tags dotime
22144 noprefix remove-re)
22145 "Format TXT to be inserted into the agenda buffer.
22146 In particular, it adds the prefix and corresponding text properties. EXTRA
22147 must be a string and replaces the `%s' specifier in the prefix format.
22148 CATEGORY (string, symbol or nil) may be used to overrule the default
22149 category taken from local variable or file name. It will replace the `%c'
22150 specifier in the format. DOTIME, when non-nil, indicates that a
22151 time-of-day should be extracted from TXT for sorting of this entry, and for
22152 the `%t' specifier in the format. When DOTIME is a string, this string is
22153 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22154 only the correctly processes TXT should be returned - this is used by
22155 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22156 Any match of REMOVE-RE will be removed from TXT."
22157 (save-match-data
22158 ;; Diary entries sometimes have extra whitespace at the beginning
22159 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22160 (let* ((category (or category
22161 org-category
22162 (if buffer-file-name
22163 (file-name-sans-extension
22164 (file-name-nondirectory buffer-file-name))
22165 "")))
22166 (tag (if tags (nth (1- (length tags)) tags) ""))
22167 time ; time and tag are needed for the eval of the prefix format
22168 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22169 (time-of-day (and dotime (org-get-time-of-day ts)))
22170 stamp plain s0 s1 s2 rtn srp)
22171 (when (and dotime time-of-day org-prefix-has-time)
22172 ;; Extract starting and ending time and move them to prefix
22173 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22174 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22175 (setq s0 (match-string 0 ts)
22176 srp (and stamp (match-end 3))
22177 s1 (match-string (if plain 1 2) ts)
22178 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22180 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22181 ;; them, we might want to remove them there to avoid duplication.
22182 ;; The user can turn this off with a variable.
22183 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22184 (string-match (concat (regexp-quote s0) " *") txt)
22185 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22186 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22187 (= (match-beginning 0) 0)
22189 (setq txt (replace-match "" nil nil txt))))
22190 ;; Normalize the time(s) to 24 hour
22191 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22192 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22194 (when (and s1 (not s2) org-agenda-default-appointment-duration
22195 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22196 (let ((m (+ (string-to-number (match-string 2 s1))
22197 (* 60 (string-to-number (match-string 1 s1)))
22198 org-agenda-default-appointment-duration))
22200 (setq h (/ m 60) m (- m (* h 60)))
22201 (setq s2 (format "%02d:%02d" h m))))
22203 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22204 txt)
22205 ;; Tags are in the string
22206 (if (or (eq org-agenda-remove-tags t)
22207 (and org-agenda-remove-tags
22208 org-prefix-has-tag))
22209 (setq txt (replace-match "" t t txt))
22210 (setq txt (replace-match
22211 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22212 (match-string 2 txt))
22213 t t txt))))
22215 (when remove-re
22216 (while (string-match remove-re txt)
22217 (setq txt (replace-match "" t t txt))))
22219 ;; Create the final string
22220 (if noprefix
22221 (setq rtn txt)
22222 ;; Prepare the variables needed in the eval of the compiled format
22223 (setq time (cond (s2 (concat s1 "-" s2))
22224 (s1 (concat s1 "......"))
22225 (t ""))
22226 extra (or extra "")
22227 category (if (symbolp category) (symbol-name category) category))
22228 ;; Evaluate the compiled format
22229 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22231 ;; And finally add the text properties
22232 (org-add-props rtn nil
22233 'org-category (downcase category) 'tags tags
22234 'org-highest-priority org-highest-priority
22235 'org-lowest-priority org-lowest-priority
22236 'prefix-length (- (length rtn) (length txt))
22237 'time-of-day time-of-day
22238 'txt txt
22239 'time time
22240 'extra extra
22241 'dotime dotime))))
22243 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22244 (defvar org-agenda-sorting-strategy-selected nil)
22246 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22247 (catch 'exit
22248 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22249 ((and todayp (member 'today (car org-agenda-time-grid))))
22250 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22251 ((member 'weekly (car org-agenda-time-grid)))
22252 (t (throw 'exit list)))
22253 (let* ((have (delq nil (mapcar
22254 (lambda (x) (get-text-property 1 'time-of-day x))
22255 list)))
22256 (string (nth 1 org-agenda-time-grid))
22257 (gridtimes (nth 2 org-agenda-time-grid))
22258 (req (car org-agenda-time-grid))
22259 (remove (member 'remove-match req))
22260 new time)
22261 (if (and (member 'require-timed req) (not have))
22262 ;; don't show empty grid
22263 (throw 'exit list))
22264 (while (setq time (pop gridtimes))
22265 (unless (and remove (member time have))
22266 (setq time (int-to-string time))
22267 (push (org-format-agenda-item
22268 nil string "" nil
22269 (concat (substring time 0 -2) ":" (substring time -2)))
22270 new)
22271 (put-text-property
22272 1 (length (car new)) 'face 'org-time-grid (car new))))
22273 (if (member 'time-up org-agenda-sorting-strategy-selected)
22274 (append new list)
22275 (append list new)))))
22277 (defun org-compile-prefix-format (key)
22278 "Compile the prefix format into a Lisp form that can be evaluated.
22279 The resulting form is returned and stored in the variable
22280 `org-prefix-format-compiled'."
22281 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22282 (let ((s (cond
22283 ((stringp org-agenda-prefix-format)
22284 org-agenda-prefix-format)
22285 ((assq key org-agenda-prefix-format)
22286 (cdr (assq key org-agenda-prefix-format)))
22287 (t " %-12:c%?-12t% s")))
22288 (start 0)
22289 varform vars var e c f opt)
22290 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22291 s start)
22292 (setq var (cdr (assoc (match-string 4 s)
22293 '(("c" . category) ("t" . time) ("s" . extra)
22294 ("T" . tag))))
22295 c (or (match-string 3 s) "")
22296 opt (match-beginning 1)
22297 start (1+ (match-beginning 0)))
22298 (if (equal var 'time) (setq org-prefix-has-time t))
22299 (if (equal var 'tag) (setq org-prefix-has-tag t))
22300 (setq f (concat "%" (match-string 2 s) "s"))
22301 (if opt
22302 (setq varform
22303 `(if (equal "" ,var)
22305 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22306 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22307 (setq s (replace-match "%s" t nil s))
22308 (push varform vars))
22309 (setq vars (nreverse vars))
22310 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22312 (defun org-set-sorting-strategy (key)
22313 (if (symbolp (car org-agenda-sorting-strategy))
22314 ;; the old format
22315 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22316 (setq org-agenda-sorting-strategy-selected
22317 (or (cdr (assq key org-agenda-sorting-strategy))
22318 (cdr (assq 'agenda org-agenda-sorting-strategy))
22319 '(time-up category-keep priority-down)))))
22321 (defun org-get-time-of-day (s &optional string mod24)
22322 "Check string S for a time of day.
22323 If found, return it as a military time number between 0 and 2400.
22324 If not found, return nil.
22325 The optional STRING argument forces conversion into a 5 character wide string
22326 HH:MM."
22327 (save-match-data
22328 (when
22329 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22330 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22331 (let* ((h (string-to-number (match-string 1 s)))
22332 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22333 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22334 (am-p (equal ampm "am"))
22335 (h1 (cond ((not ampm) h)
22336 ((= h 12) (if am-p 0 12))
22337 (t (+ h (if am-p 0 12)))))
22338 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22339 (mod h1 24) h1))
22340 (t0 (+ (* 100 h2) m))
22341 (t1 (concat (if (>= h1 24) "+" " ")
22342 (if (< t0 100) "0" "")
22343 (if (< t0 10) "0" "")
22344 (int-to-string t0))))
22345 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22347 (defun org-finalize-agenda-entries (list &optional nosort)
22348 "Sort and concatenate the agenda items."
22349 (setq list (mapcar 'org-agenda-highlight-todo list))
22350 (if nosort
22351 list
22352 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22354 (defun org-agenda-highlight-todo (x)
22355 (let (re pl)
22356 (if (eq x 'line)
22357 (save-excursion
22358 (beginning-of-line 1)
22359 (setq re (get-text-property (point) 'org-todo-regexp))
22360 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22361 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22362 (add-text-properties (match-beginning 0) (match-end 0)
22363 (list 'face (org-get-todo-face 0)))
22364 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22365 (delete-region (match-beginning 1) (1- (match-end 0)))
22366 (goto-char (match-beginning 1))
22367 (insert (format org-agenda-todo-keyword-format s)))))
22368 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22369 pl (get-text-property 0 'prefix-length x))
22370 (when (and re
22371 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22372 x (or pl 0)) pl))
22373 (add-text-properties
22374 (or (match-end 1) (match-end 0)) (match-end 0)
22375 (list 'face (org-get-todo-face (match-string 2 x)))
22377 (setq x (concat (substring x 0 (match-end 1))
22378 (format org-agenda-todo-keyword-format
22379 (match-string 2 x))
22381 (substring x (match-end 3)))))
22382 x)))
22384 (defsubst org-cmp-priority (a b)
22385 "Compare the priorities of string A and B."
22386 (let ((pa (or (get-text-property 1 'priority a) 0))
22387 (pb (or (get-text-property 1 'priority b) 0)))
22388 (cond ((> pa pb) +1)
22389 ((< pa pb) -1)
22390 (t nil))))
22392 (defsubst org-cmp-category (a b)
22393 "Compare the string values of categories of strings A and B."
22394 (let ((ca (or (get-text-property 1 'org-category a) ""))
22395 (cb (or (get-text-property 1 'org-category b) "")))
22396 (cond ((string-lessp ca cb) -1)
22397 ((string-lessp cb ca) +1)
22398 (t nil))))
22400 (defsubst org-cmp-tag (a b)
22401 "Compare the string values of categories of strings A and B."
22402 (let ((ta (car (last (get-text-property 1 'tags a))))
22403 (tb (car (last (get-text-property 1 'tags b)))))
22404 (cond ((not ta) +1)
22405 ((not tb) -1)
22406 ((string-lessp ta tb) -1)
22407 ((string-lessp tb ta) +1)
22408 (t nil))))
22410 (defsubst org-cmp-time (a b)
22411 "Compare the time-of-day values of strings A and B."
22412 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22413 (ta (or (get-text-property 1 'time-of-day a) def))
22414 (tb (or (get-text-property 1 'time-of-day b) def)))
22415 (cond ((< ta tb) -1)
22416 ((< tb ta) +1)
22417 (t nil))))
22419 (defun org-entries-lessp (a b)
22420 "Predicate for sorting agenda entries."
22421 ;; The following variables will be used when the form is evaluated.
22422 ;; So even though the compiler complains, keep them.
22423 (let* ((time-up (org-cmp-time a b))
22424 (time-down (if time-up (- time-up) nil))
22425 (priority-up (org-cmp-priority a b))
22426 (priority-down (if priority-up (- priority-up) nil))
22427 (category-up (org-cmp-category a b))
22428 (category-down (if category-up (- category-up) nil))
22429 (category-keep (if category-up +1 nil))
22430 (tag-up (org-cmp-tag a b))
22431 (tag-down (if tag-up (- tag-up) nil)))
22432 (cdr (assoc
22433 (eval (cons 'or org-agenda-sorting-strategy-selected))
22434 '((-1 . t) (1 . nil) (nil . nil))))))
22436 ;;; Agenda restriction lock
22438 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22439 "Overlay to mark the headline to which arenda commands are restricted.")
22440 (org-overlay-put org-agenda-restriction-lock-overlay
22441 'face 'org-agenda-restriction-lock)
22442 (org-overlay-put org-agenda-restriction-lock-overlay
22443 'help-echo "Agendas are currently limited to this subtree.")
22444 (org-detach-overlay org-agenda-restriction-lock-overlay)
22445 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22446 "Overlay marking the agenda restriction line in speedbar.")
22447 (org-overlay-put org-speedbar-restriction-lock-overlay
22448 'face 'org-agenda-restriction-lock)
22449 (org-overlay-put org-speedbar-restriction-lock-overlay
22450 'help-echo "Agendas are currently limited to this item.")
22451 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22453 (defun org-agenda-set-restriction-lock (&optional type)
22454 "Set restriction lock for agenda, to current subtree or file.
22455 Restriction will be the file if TYPE is `file', or if type is the
22456 universal prefix '(4), or if the cursor is before the first headline
22457 in the file. Otherwise, restriction will be to the current subtree."
22458 (interactive "P")
22459 (and (equal type '(4)) (setq type 'file))
22460 (setq type (cond
22461 (type type)
22462 ((org-at-heading-p) 'subtree)
22463 ((condition-case nil (org-back-to-heading t) (error nil))
22464 'subtree)
22465 (t 'file)))
22466 (if (eq type 'subtree)
22467 (progn
22468 (setq org-agenda-restrict t)
22469 (setq org-agenda-overriding-restriction 'subtree)
22470 (put 'org-agenda-files 'org-restrict
22471 (list (buffer-file-name (buffer-base-buffer))))
22472 (org-back-to-heading t)
22473 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22474 (move-marker org-agenda-restrict-begin (point))
22475 (move-marker org-agenda-restrict-end
22476 (save-excursion (org-end-of-subtree t)))
22477 (message "Locking agenda restriction to subtree"))
22478 (put 'org-agenda-files 'org-restrict
22479 (list (buffer-file-name (buffer-base-buffer))))
22480 (setq org-agenda-restrict nil)
22481 (setq org-agenda-overriding-restriction 'file)
22482 (move-marker org-agenda-restrict-begin nil)
22483 (move-marker org-agenda-restrict-end nil)
22484 (message "Locking agenda restriction to file"))
22485 (setq current-prefix-arg nil)
22486 (org-agenda-maybe-redo))
22488 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22489 "Remove the agenda restriction lock."
22490 (interactive "P")
22491 (org-detach-overlay org-agenda-restriction-lock-overlay)
22492 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22493 (setq org-agenda-overriding-restriction nil)
22494 (setq org-agenda-restrict nil)
22495 (put 'org-agenda-files 'org-restrict nil)
22496 (move-marker org-agenda-restrict-begin nil)
22497 (move-marker org-agenda-restrict-end nil)
22498 (setq current-prefix-arg nil)
22499 (message "Agenda restriction lock removed")
22500 (or noupdate (org-agenda-maybe-redo)))
22502 (defun org-agenda-maybe-redo ()
22503 "If there is any window showing the agenda view, update it."
22504 (let ((w (get-buffer-window org-agenda-buffer-name t))
22505 (w0 (selected-window)))
22506 (when w
22507 (select-window w)
22508 (org-agenda-redo)
22509 (select-window w0)
22510 (if org-agenda-overriding-restriction
22511 (message "Agenda view shifted to new %s restriction"
22512 org-agenda-overriding-restriction)
22513 (message "Agenda restriction lock removed")))))
22515 ;;; Agenda commands
22517 (defun org-agenda-check-type (error &rest types)
22518 "Check if agenda buffer is of allowed type.
22519 If ERROR is non-nil, throw an error, otherwise just return nil."
22520 (if (memq org-agenda-type types)
22522 (if error
22523 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22524 nil)))
22526 (defun org-agenda-quit ()
22527 "Exit agenda by removing the window or the buffer."
22528 (interactive)
22529 (let ((buf (current-buffer)))
22530 (if (not (one-window-p)) (delete-window))
22531 (kill-buffer buf)
22532 (org-agenda-reset-markers)
22533 (org-columns-remove-overlays))
22534 ;; Maybe restore the pre-agenda window configuration.
22535 (and org-agenda-restore-windows-after-quit
22536 (not (eq org-agenda-window-setup 'other-frame))
22537 org-pre-agenda-window-conf
22538 (set-window-configuration org-pre-agenda-window-conf)))
22540 (defun org-agenda-exit ()
22541 "Exit agenda by removing the window or the buffer.
22542 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22543 Org-mode buffers visited directly by the user will not be touched."
22544 (interactive)
22545 (org-release-buffers org-agenda-new-buffers)
22546 (setq org-agenda-new-buffers nil)
22547 (org-agenda-quit))
22549 (defun org-agenda-execute (arg)
22550 "Execute another agenda command, keeping same window.\\<global-map>
22551 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22552 (interactive "P")
22553 (let ((org-agenda-window-setup 'current-window))
22554 (org-agenda arg)))
22556 (defun org-save-all-org-buffers ()
22557 "Save all Org-mode buffers without user confirmation."
22558 (interactive)
22559 (message "Saving all Org-mode buffers...")
22560 (save-some-buffers t 'org-mode-p)
22561 (message "Saving all Org-mode buffers... done"))
22563 (defun org-agenda-redo ()
22564 "Rebuild Agenda.
22565 When this is the global TODO list, a prefix argument will be interpreted."
22566 (interactive)
22567 (let* ((org-agenda-keep-modes t)
22568 (line (org-current-line))
22569 (window-line (- line (org-current-line (window-start))))
22570 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22571 (message "Rebuilding agenda buffer...")
22572 (org-let lprops '(eval org-agenda-redo-command))
22573 (setq org-agenda-undo-list nil
22574 org-agenda-pending-undo-list nil)
22575 (message "Rebuilding agenda buffer...done")
22576 (goto-line line)
22577 (recenter window-line)))
22579 (defun org-agenda-manipulate-query-add ()
22580 "Manipulate the query by adding a search term with positive selection.
22581 Positive selection means, the term must be matched for selection of an entry."
22582 (interactive)
22583 (org-agenda-manipulate-query ?\[))
22584 (defun org-agenda-manipulate-query-subtract ()
22585 "Manipulate the query by adding a search term with negative selection.
22586 Negative selection means, term must not be matched for selection of an entry."
22587 (interactive)
22588 (org-agenda-manipulate-query ?\]))
22589 (defun org-agenda-manipulate-query-add-re ()
22590 "Manipulate the query by adding a search regexp with positive selection.
22591 Positive selection means, the regexp must match for selection of an entry."
22592 (interactive)
22593 (org-agenda-manipulate-query ?\{))
22594 (defun org-agenda-manipulate-query-subtract-re ()
22595 "Manipulate the query by adding a search regexp with negative selection.
22596 Negative selection means, regexp must not match for selection of an entry."
22597 (interactive)
22598 (org-agenda-manipulate-query ?\}))
22599 (defun org-agenda-manipulate-query (char)
22600 (cond
22601 ((eq org-agenda-type 'search)
22602 (org-add-to-string
22603 'org-agenda-query-string
22604 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22605 (?\{ . " +{}") (?\} . " -{}")))))
22606 (setq org-agenda-redo-command
22607 (list 'org-search-view
22608 (+ (length org-agenda-query-string)
22609 (if (member char '(?\{ ?\})) 0 1))
22610 org-agenda-query-string))
22611 (set-register org-agenda-query-register org-agenda-query-string)
22612 (org-agenda-redo))
22613 (t (error "Canot manipulate query for %s-type agenda buffers"
22614 org-agenda-type))))
22616 (defun org-add-to-string (var string)
22617 (set var (concat (symbol-value var) string)))
22619 (defun org-agenda-goto-date (date)
22620 "Jump to DATE in agenda."
22621 (interactive (list (org-read-date)))
22622 (org-agenda-list nil date))
22624 (defun org-agenda-goto-today ()
22625 "Go to today."
22626 (interactive)
22627 (org-agenda-check-type t 'timeline 'agenda)
22628 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22629 (cond
22630 (tdpos (goto-char tdpos))
22631 ((eq org-agenda-type 'agenda)
22632 (let* ((sd (time-to-days
22633 (time-subtract (current-time)
22634 (list 0 (* 3600 org-extend-today-until) 0))))
22635 (comp (org-agenda-compute-time-span sd org-agenda-span))
22636 (org-agenda-overriding-arguments org-agenda-last-arguments))
22637 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22638 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22639 (org-agenda-redo)
22640 (org-agenda-find-same-or-today-or-agenda)))
22641 (t (error "Cannot find today")))))
22643 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22644 (goto-char
22645 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22646 (text-property-any (point-min) (point-max) 'org-today t)
22647 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22648 (point-min))))
22650 (defun org-agenda-later (arg)
22651 "Go forward in time by thee current span.
22652 With prefix ARG, go forward that many times the current span."
22653 (interactive "p")
22654 (org-agenda-check-type t 'agenda)
22655 (let* ((span org-agenda-span)
22656 (sd org-starting-day)
22657 (greg (calendar-gregorian-from-absolute sd))
22658 (cnt (get-text-property (point) 'org-day-cnt))
22659 greg2 nd)
22660 (cond
22661 ((eq span 'day)
22662 (setq sd (+ arg sd) nd 1))
22663 ((eq span 'week)
22664 (setq sd (+ (* 7 arg) sd) nd 7))
22665 ((eq span 'month)
22666 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22667 sd (calendar-absolute-from-gregorian greg2))
22668 (setcar greg2 (1+ (car greg2)))
22669 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22670 ((eq span 'year)
22671 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22672 sd (calendar-absolute-from-gregorian greg2))
22673 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22674 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22675 (let ((org-agenda-overriding-arguments
22676 (list (car org-agenda-last-arguments) sd nd t)))
22677 (org-agenda-redo)
22678 (org-agenda-find-same-or-today-or-agenda cnt))))
22680 (defun org-agenda-earlier (arg)
22681 "Go backward in time by the current span.
22682 With prefix ARG, go backward that many times the current span."
22683 (interactive "p")
22684 (org-agenda-later (- arg)))
22686 (defun org-agenda-day-view ()
22687 "Switch to daily view for agenda."
22688 (interactive)
22689 (setq org-agenda-ndays 1)
22690 (org-agenda-change-time-span 'day))
22691 (defun org-agenda-week-view ()
22692 "Switch to daily view for agenda."
22693 (interactive)
22694 (setq org-agenda-ndays 7)
22695 (org-agenda-change-time-span 'week))
22696 (defun org-agenda-month-view ()
22697 "Switch to daily view for agenda."
22698 (interactive)
22699 (org-agenda-change-time-span 'month))
22700 (defun org-agenda-year-view ()
22701 "Switch to daily view for agenda."
22702 (interactive)
22703 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22704 (org-agenda-change-time-span 'year)
22705 (error "Abort")))
22707 (defun org-agenda-change-time-span (span)
22708 "Change the agenda view to SPAN.
22709 SPAN may be `day', `week', `month', `year'."
22710 (org-agenda-check-type t 'agenda)
22711 (if (equal org-agenda-span span)
22712 (error "Viewing span is already \"%s\"" span))
22713 (let* ((sd (or (get-text-property (point) 'day)
22714 org-starting-day))
22715 (computed (org-agenda-compute-time-span sd span))
22716 (org-agenda-overriding-arguments
22717 (list (car org-agenda-last-arguments)
22718 (car computed) (cdr computed) t)))
22719 (org-agenda-redo)
22720 (org-agenda-find-same-or-today-or-agenda))
22721 (org-agenda-set-mode-name)
22722 (message "Switched to %s view" span))
22724 (defun org-agenda-compute-time-span (sd span)
22725 "Compute starting date and number of days for agenda.
22726 SPAN may be `day', `week', `month', `year'. The return value
22727 is a cons cell with the starting date and the number of days,
22728 so that the date SD will be in that range."
22729 (let* ((greg (calendar-gregorian-from-absolute sd))
22731 (cond
22732 ((eq span 'day)
22733 (setq nd 1))
22734 ((eq span 'week)
22735 (let* ((nt (calendar-day-of-week
22736 (calendar-gregorian-from-absolute sd)))
22737 (d (if org-agenda-start-on-weekday
22738 (- nt org-agenda-start-on-weekday)
22739 0)))
22740 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22741 (setq nd 7)))
22742 ((eq span 'month)
22743 (setq sd (calendar-absolute-from-gregorian
22744 (list (car greg) 1 (nth 2 greg)))
22745 nd (- (calendar-absolute-from-gregorian
22746 (list (1+ (car greg)) 1 (nth 2 greg)))
22747 sd)))
22748 ((eq span 'year)
22749 (setq sd (calendar-absolute-from-gregorian
22750 (list 1 1 (nth 2 greg)))
22751 nd (- (calendar-absolute-from-gregorian
22752 (list 1 1 (1+ (nth 2 greg))))
22753 sd))))
22754 (cons sd nd)))
22756 ;; FIXME: does not work if user makes date format that starts with a blank
22757 (defun org-agenda-next-date-line (&optional arg)
22758 "Jump to the next line indicating a date in agenda buffer."
22759 (interactive "p")
22760 (org-agenda-check-type t 'agenda 'timeline)
22761 (beginning-of-line 1)
22762 (if (looking-at "^\\S-") (forward-char 1))
22763 (if (not (re-search-forward "^\\S-" nil t arg))
22764 (progn
22765 (backward-char 1)
22766 (error "No next date after this line in this buffer")))
22767 (goto-char (match-beginning 0)))
22769 (defun org-agenda-previous-date-line (&optional arg)
22770 "Jump to the previous line indicating a date in agenda buffer."
22771 (interactive "p")
22772 (org-agenda-check-type t 'agenda 'timeline)
22773 (beginning-of-line 1)
22774 (if (not (re-search-backward "^\\S-" nil t arg))
22775 (error "No previous date before this line in this buffer")))
22777 ;; Initialize the highlight
22778 (defvar org-hl (org-make-overlay 1 1))
22779 (org-overlay-put org-hl 'face 'highlight)
22781 (defun org-highlight (begin end &optional buffer)
22782 "Highlight a region with overlay."
22783 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22784 org-hl begin end (or buffer (current-buffer))))
22786 (defun org-unhighlight ()
22787 "Detach overlay INDEX."
22788 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22790 ;; FIXME this is currently not used.
22791 (defun org-highlight-until-next-command (beg end &optional buffer)
22792 (org-highlight beg end buffer)
22793 (add-hook 'pre-command-hook 'org-unhighlight-once))
22794 (defun org-unhighlight-once ()
22795 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22796 (org-unhighlight))
22798 (defun org-agenda-follow-mode ()
22799 "Toggle follow mode in an agenda buffer."
22800 (interactive)
22801 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22802 (org-agenda-set-mode-name)
22803 (message "Follow mode is %s"
22804 (if org-agenda-follow-mode "on" "off")))
22806 (defun org-agenda-log-mode ()
22807 "Toggle log mode in an agenda buffer."
22808 (interactive)
22809 (org-agenda-check-type t 'agenda 'timeline)
22810 (setq org-agenda-show-log (not org-agenda-show-log))
22811 (org-agenda-set-mode-name)
22812 (org-agenda-redo)
22813 (message "Log mode is %s"
22814 (if org-agenda-show-log "on" "off")))
22816 (defun org-agenda-toggle-diary ()
22817 "Toggle diary inclusion in an agenda buffer."
22818 (interactive)
22819 (org-agenda-check-type t 'agenda)
22820 (setq org-agenda-include-diary (not org-agenda-include-diary))
22821 (org-agenda-redo)
22822 (org-agenda-set-mode-name)
22823 (message "Diary inclusion turned %s"
22824 (if org-agenda-include-diary "on" "off")))
22826 (defun org-agenda-toggle-time-grid ()
22827 "Toggle time grid in an agenda buffer."
22828 (interactive)
22829 (org-agenda-check-type t 'agenda)
22830 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22831 (org-agenda-redo)
22832 (org-agenda-set-mode-name)
22833 (message "Time-grid turned %s"
22834 (if org-agenda-use-time-grid "on" "off")))
22836 (defun org-agenda-set-mode-name ()
22837 "Set the mode name to indicate all the small mode settings."
22838 (setq mode-name
22839 (concat "Org-Agenda"
22840 (if (equal org-agenda-ndays 1) " Day" "")
22841 (if (equal org-agenda-ndays 7) " Week" "")
22842 (if org-agenda-follow-mode " Follow" "")
22843 (if org-agenda-include-diary " Diary" "")
22844 (if org-agenda-use-time-grid " Grid" "")
22845 (if org-agenda-show-log " Log" "")))
22846 (force-mode-line-update))
22848 (defun org-agenda-post-command-hook ()
22849 (and (eolp) (not (bolp)) (backward-char 1))
22850 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22851 (if (and org-agenda-follow-mode
22852 (get-text-property (point) 'org-marker))
22853 (org-agenda-show)))
22855 (defun org-agenda-show-priority ()
22856 "Show the priority of the current item.
22857 This priority is composed of the main priority given with the [#A] cookies,
22858 and by additional input from the age of a schedules or deadline entry."
22859 (interactive)
22860 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22861 (message "Priority is %d" (if pri pri -1000))))
22863 (defun org-agenda-show-tags ()
22864 "Show the tags applicable to the current item."
22865 (interactive)
22866 (let* ((tags (get-text-property (point-at-bol) 'tags)))
22867 (if tags
22868 (message "Tags are :%s:"
22869 (org-no-properties (mapconcat 'identity tags ":")))
22870 (message "No tags associated with this line"))))
22872 (defun org-agenda-goto (&optional highlight)
22873 "Go to the Org-mode file which contains the item at point."
22874 (interactive)
22875 (let* ((marker (or (get-text-property (point) 'org-marker)
22876 (org-agenda-error)))
22877 (buffer (marker-buffer marker))
22878 (pos (marker-position marker)))
22879 (switch-to-buffer-other-window buffer)
22880 (widen)
22881 (goto-char pos)
22882 (when (org-mode-p)
22883 (org-show-context 'agenda)
22884 (save-excursion
22885 (and (outline-next-heading)
22886 (org-flag-heading nil)))) ; show the next heading
22887 (recenter (/ (window-height) 2))
22888 (run-hooks 'org-agenda-after-show-hook)
22889 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
22891 (defvar org-agenda-after-show-hook nil
22892 "Normal hook run after an item has been shown from the agenda.
22893 Point is in the buffer where the item originated.")
22895 (defun org-agenda-kill ()
22896 "Kill the entry or subtree belonging to the current agenda entry."
22897 (interactive)
22898 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22899 (let* ((marker (or (get-text-property (point) 'org-marker)
22900 (org-agenda-error)))
22901 (buffer (marker-buffer marker))
22902 (pos (marker-position marker))
22903 (type (get-text-property (point) 'type))
22904 dbeg dend (n 0) conf)
22905 (org-with-remote-undo buffer
22906 (with-current-buffer buffer
22907 (save-excursion
22908 (goto-char pos)
22909 (if (and (org-mode-p) (not (member type '("sexp"))))
22910 (setq dbeg (progn (org-back-to-heading t) (point))
22911 dend (org-end-of-subtree t t))
22912 (setq dbeg (point-at-bol)
22913 dend (min (point-max) (1+ (point-at-eol)))))
22914 (goto-char dbeg)
22915 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
22916 (setq conf (or (eq t org-agenda-confirm-kill)
22917 (and (numberp org-agenda-confirm-kill)
22918 (> n org-agenda-confirm-kill))))
22919 (and conf
22920 (not (y-or-n-p
22921 (format "Delete entry with %d lines in buffer \"%s\"? "
22922 n (buffer-name buffer))))
22923 (error "Abort"))
22924 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
22925 (with-current-buffer buffer (delete-region dbeg dend))
22926 (message "Agenda item and source killed"))))
22928 (defun org-agenda-archive ()
22929 "Kill the entry or subtree belonging to the current agenda entry."
22930 (interactive)
22931 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
22932 (let* ((marker (or (get-text-property (point) 'org-marker)
22933 (org-agenda-error)))
22934 (buffer (marker-buffer marker))
22935 (pos (marker-position marker)))
22936 (org-with-remote-undo buffer
22937 (with-current-buffer buffer
22938 (if (org-mode-p)
22939 (save-excursion
22940 (goto-char pos)
22941 (org-remove-subtree-entries-from-agenda)
22942 (org-back-to-heading t)
22943 (org-archive-subtree))
22944 (error "Archiving works only in Org-mode files"))))))
22946 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
22947 "Remove all lines in the agenda that correspond to a given subtree.
22948 The subtree is the one in buffer BUF, starting at BEG and ending at END.
22949 If this information is not given, the function uses the tree at point."
22950 (let ((buf (or buf (current-buffer))) m p)
22951 (save-excursion
22952 (unless (and beg end)
22953 (org-back-to-heading t)
22954 (setq beg (point))
22955 (org-end-of-subtree t)
22956 (setq end (point)))
22957 (set-buffer (get-buffer org-agenda-buffer-name))
22958 (save-excursion
22959 (goto-char (point-max))
22960 (beginning-of-line 1)
22961 (while (not (bobp))
22962 (when (and (setq m (get-text-property (point) 'org-marker))
22963 (equal buf (marker-buffer m))
22964 (setq p (marker-position m))
22965 (>= p beg)
22966 (<= p end))
22967 (let ((inhibit-read-only t))
22968 (delete-region (point-at-bol) (1+ (point-at-eol)))))
22969 (beginning-of-line 0))))))
22971 (defun org-agenda-open-link ()
22972 "Follow the link in the current line, if any."
22973 (interactive)
22974 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
22975 (save-excursion
22976 (save-restriction
22977 (narrow-to-region (point-at-bol) (point-at-eol))
22978 (org-open-at-point))))
22980 (defun org-agenda-copy-local-variable (var)
22981 "Get a variable from a referenced buffer and install it here."
22982 (let ((m (get-text-property (point) 'org-marker)))
22983 (when (and m (buffer-live-p (marker-buffer m)))
22984 (org-set-local var (with-current-buffer (marker-buffer m)
22985 (symbol-value var))))))
22987 (defun org-agenda-switch-to (&optional delete-other-windows)
22988 "Go to the Org-mode file which contains the item at point."
22989 (interactive)
22990 (let* ((marker (or (get-text-property (point) 'org-marker)
22991 (org-agenda-error)))
22992 (buffer (marker-buffer marker))
22993 (pos (marker-position marker)))
22994 (switch-to-buffer buffer)
22995 (and delete-other-windows (delete-other-windows))
22996 (widen)
22997 (goto-char pos)
22998 (when (org-mode-p)
22999 (org-show-context 'agenda)
23000 (save-excursion
23001 (and (outline-next-heading)
23002 (org-flag-heading nil)))))) ; show the next heading
23004 (defun org-agenda-goto-mouse (ev)
23005 "Go to the Org-mode file which contains the item at the mouse click."
23006 (interactive "e")
23007 (mouse-set-point ev)
23008 (org-agenda-goto))
23010 (defun org-agenda-show ()
23011 "Display the Org-mode file which contains the item at point."
23012 (interactive)
23013 (let ((win (selected-window)))
23014 (org-agenda-goto t)
23015 (select-window win)))
23017 (defun org-agenda-recenter (arg)
23018 "Display the Org-mode file which contains the item at point and recenter."
23019 (interactive "P")
23020 (let ((win (selected-window)))
23021 (org-agenda-goto t)
23022 (recenter arg)
23023 (select-window win)))
23025 (defun org-agenda-show-mouse (ev)
23026 "Display the Org-mode file which contains the item at the mouse click."
23027 (interactive "e")
23028 (mouse-set-point ev)
23029 (org-agenda-show))
23031 (defun org-agenda-check-no-diary ()
23032 "Check if the entry is a diary link and abort if yes."
23033 (if (get-text-property (point) 'org-agenda-diary-link)
23034 (org-agenda-error)))
23036 (defun org-agenda-error ()
23037 (error "Command not allowed in this line"))
23039 (defun org-agenda-tree-to-indirect-buffer ()
23040 "Show the subtree corresponding to the current entry in an indirect buffer.
23041 This calls the command `org-tree-to-indirect-buffer' from the original
23042 Org-mode buffer.
23043 With numerical prefix arg ARG, go up to this level and then take that tree.
23044 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23045 dedicated frame)."
23046 (interactive)
23047 (org-agenda-check-no-diary)
23048 (let* ((marker (or (get-text-property (point) 'org-marker)
23049 (org-agenda-error)))
23050 (buffer (marker-buffer marker))
23051 (pos (marker-position marker)))
23052 (with-current-buffer buffer
23053 (save-excursion
23054 (goto-char pos)
23055 (call-interactively 'org-tree-to-indirect-buffer)))))
23057 (defvar org-last-heading-marker (make-marker)
23058 "Marker pointing to the headline that last changed its TODO state
23059 by a remote command from the agenda.")
23061 (defun org-agenda-todo-nextset ()
23062 "Switch TODO entry to next sequence."
23063 (interactive)
23064 (org-agenda-todo 'nextset))
23066 (defun org-agenda-todo-previousset ()
23067 "Switch TODO entry to previous sequence."
23068 (interactive)
23069 (org-agenda-todo 'previousset))
23071 (defun org-agenda-todo (&optional arg)
23072 "Cycle TODO state of line at point, also in Org-mode file.
23073 This changes the line at point, all other lines in the agenda referring to
23074 the same tree node, and the headline of the tree node in the Org-mode file."
23075 (interactive "P")
23076 (org-agenda-check-no-diary)
23077 (let* ((col (current-column))
23078 (marker (or (get-text-property (point) 'org-marker)
23079 (org-agenda-error)))
23080 (buffer (marker-buffer marker))
23081 (pos (marker-position marker))
23082 (hdmarker (get-text-property (point) 'org-hd-marker))
23083 (inhibit-read-only t)
23084 newhead)
23085 (org-with-remote-undo buffer
23086 (with-current-buffer buffer
23087 (widen)
23088 (goto-char pos)
23089 (org-show-context 'agenda)
23090 (save-excursion
23091 (and (outline-next-heading)
23092 (org-flag-heading nil))) ; show the next heading
23093 (org-todo arg)
23094 (and (bolp) (forward-char 1))
23095 (setq newhead (org-get-heading))
23096 (save-excursion
23097 (org-back-to-heading)
23098 (move-marker org-last-heading-marker (point))))
23099 (beginning-of-line 1)
23100 (save-excursion
23101 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23102 (move-to-column col))))
23104 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23105 "Change all lines in the agenda buffer which match HDMARKER.
23106 The new content of the line will be NEWHEAD (as modified by
23107 `org-format-agenda-item'). HDMARKER is checked with
23108 `equal' against all `org-hd-marker' text properties in the file.
23109 If FIXFACE is non-nil, the face of each item is modified acording to
23110 the new TODO state."
23111 (let* ((inhibit-read-only t)
23112 props m pl undone-face done-face finish new dotime cat tags)
23113 (save-excursion
23114 (goto-char (point-max))
23115 (beginning-of-line 1)
23116 (while (not finish)
23117 (setq finish (bobp))
23118 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23119 (equal m hdmarker))
23120 (setq props (text-properties-at (point))
23121 dotime (get-text-property (point) 'dotime)
23122 cat (get-text-property (point) 'org-category)
23123 tags (get-text-property (point) 'tags)
23124 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23125 pl (get-text-property (point) 'prefix-length)
23126 undone-face (get-text-property (point) 'undone-face)
23127 done-face (get-text-property (point) 'done-face))
23128 (move-to-column pl)
23129 (cond
23130 ((equal new "")
23131 (beginning-of-line 1)
23132 (and (looking-at ".*\n?") (replace-match "")))
23133 ((looking-at ".*")
23134 (replace-match new t t)
23135 (beginning-of-line 1)
23136 (add-text-properties (point-at-bol) (point-at-eol) props)
23137 (when fixface
23138 (add-text-properties
23139 (point-at-bol) (point-at-eol)
23140 (list 'face
23141 (if org-last-todo-state-is-todo
23142 undone-face done-face))))
23143 (org-agenda-highlight-todo 'line)
23144 (beginning-of-line 1))
23145 (t (error "Line update did not work"))))
23146 (beginning-of-line 0)))
23147 (org-finalize-agenda)))
23149 (defun org-agenda-align-tags (&optional line)
23150 "Align all tags in agenda items to `org-agenda-tags-column'."
23151 (let ((inhibit-read-only t) l c)
23152 (save-excursion
23153 (goto-char (if line (point-at-bol) (point-min)))
23154 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23155 (if line (point-at-eol) nil) t)
23156 (add-text-properties
23157 (match-beginning 2) (match-end 2)
23158 (list 'face (delq nil (list 'org-tag (get-text-property
23159 (match-beginning 2) 'face)))))
23160 (setq l (- (match-end 2) (match-beginning 2))
23161 c (if (< org-agenda-tags-column 0)
23162 (- (abs org-agenda-tags-column) l)
23163 org-agenda-tags-column))
23164 (delete-region (match-beginning 1) (match-end 1))
23165 (goto-char (match-beginning 1))
23166 (insert (org-add-props
23167 (make-string (max 1 (- c (current-column))) ?\ )
23168 (text-properties-at (point))))))))
23170 (defun org-agenda-priority-up ()
23171 "Increase the priority of line at point, also in Org-mode file."
23172 (interactive)
23173 (org-agenda-priority 'up))
23175 (defun org-agenda-priority-down ()
23176 "Decrease the priority of line at point, also in Org-mode file."
23177 (interactive)
23178 (org-agenda-priority 'down))
23180 (defun org-agenda-priority (&optional force-direction)
23181 "Set the priority of line at point, also in Org-mode file.
23182 This changes the line at point, all other lines in the agenda referring to
23183 the same tree node, and the headline of the tree node in the Org-mode file."
23184 (interactive)
23185 (org-agenda-check-no-diary)
23186 (let* ((marker (or (get-text-property (point) 'org-marker)
23187 (org-agenda-error)))
23188 (hdmarker (get-text-property (point) 'org-hd-marker))
23189 (buffer (marker-buffer hdmarker))
23190 (pos (marker-position hdmarker))
23191 (inhibit-read-only t)
23192 newhead)
23193 (org-with-remote-undo buffer
23194 (with-current-buffer buffer
23195 (widen)
23196 (goto-char pos)
23197 (org-show-context 'agenda)
23198 (save-excursion
23199 (and (outline-next-heading)
23200 (org-flag-heading nil))) ; show the next heading
23201 (funcall 'org-priority force-direction)
23202 (end-of-line 1)
23203 (setq newhead (org-get-heading)))
23204 (org-agenda-change-all-lines newhead hdmarker)
23205 (beginning-of-line 1))))
23207 (defun org-get-tags-at (&optional pos)
23208 "Get a list of all headline tags applicable at POS.
23209 POS defaults to point. If tags are inherited, the list contains
23210 the targets in the same sequence as the headlines appear, i.e.
23211 the tags of the current headline come last."
23212 (interactive)
23213 (let (tags lastpos)
23214 (save-excursion
23215 (save-restriction
23216 (widen)
23217 (goto-char (or pos (point)))
23218 (save-match-data
23219 (org-back-to-heading t)
23220 (condition-case nil
23221 (while (not (equal lastpos (point)))
23222 (setq lastpos (point))
23223 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23224 (setq tags (append (org-split-string
23225 (org-match-string-no-properties 1) ":")
23226 tags)))
23227 (or org-use-tag-inheritance (error ""))
23228 (org-up-heading-all 1))
23229 (error nil))))
23230 tags)))
23232 ;; FIXME: should fix the tags property of the agenda line.
23233 (defun org-agenda-set-tags ()
23234 "Set tags for the current headline."
23235 (interactive)
23236 (org-agenda-check-no-diary)
23237 (if (and (org-region-active-p) (interactive-p))
23238 (call-interactively 'org-change-tag-in-region)
23239 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23240 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23241 (org-agenda-error)))
23242 (buffer (marker-buffer hdmarker))
23243 (pos (marker-position hdmarker))
23244 (inhibit-read-only t)
23245 newhead)
23246 (org-with-remote-undo buffer
23247 (with-current-buffer buffer
23248 (widen)
23249 (goto-char pos)
23250 (save-excursion
23251 (org-show-context 'agenda))
23252 (save-excursion
23253 (and (outline-next-heading)
23254 (org-flag-heading nil))) ; show the next heading
23255 (goto-char pos)
23256 (call-interactively 'org-set-tags)
23257 (end-of-line 1)
23258 (setq newhead (org-get-heading)))
23259 (org-agenda-change-all-lines newhead hdmarker)
23260 (beginning-of-line 1)))))
23262 (defun org-agenda-toggle-archive-tag ()
23263 "Toggle the archive tag for the current entry."
23264 (interactive)
23265 (org-agenda-check-no-diary)
23266 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23267 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23268 (org-agenda-error)))
23269 (buffer (marker-buffer hdmarker))
23270 (pos (marker-position hdmarker))
23271 (inhibit-read-only t)
23272 newhead)
23273 (org-with-remote-undo buffer
23274 (with-current-buffer buffer
23275 (widen)
23276 (goto-char pos)
23277 (org-show-context 'agenda)
23278 (save-excursion
23279 (and (outline-next-heading)
23280 (org-flag-heading nil))) ; show the next heading
23281 (call-interactively 'org-toggle-archive-tag)
23282 (end-of-line 1)
23283 (setq newhead (org-get-heading)))
23284 (org-agenda-change-all-lines newhead hdmarker)
23285 (beginning-of-line 1))))
23287 (defun org-agenda-date-later (arg &optional what)
23288 "Change the date of this item to one day later."
23289 (interactive "p")
23290 (org-agenda-check-type t 'agenda 'timeline)
23291 (org-agenda-check-no-diary)
23292 (let* ((marker (or (get-text-property (point) 'org-marker)
23293 (org-agenda-error)))
23294 (buffer (marker-buffer marker))
23295 (pos (marker-position marker)))
23296 (org-with-remote-undo buffer
23297 (with-current-buffer buffer
23298 (widen)
23299 (goto-char pos)
23300 (if (not (org-at-timestamp-p))
23301 (error "Cannot find time stamp"))
23302 (org-timestamp-change arg (or what 'day)))
23303 (org-agenda-show-new-time marker org-last-changed-timestamp))
23304 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23306 (defun org-agenda-date-earlier (arg &optional what)
23307 "Change the date of this item to one day earlier."
23308 (interactive "p")
23309 (org-agenda-date-later (- arg) what))
23311 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23312 "Show new date stamp via text properties."
23313 ;; We use text properties to make this undoable
23314 (let ((inhibit-read-only t))
23315 (setq stamp (concat " " prefix " => " stamp))
23316 (save-excursion
23317 (goto-char (point-max))
23318 (while (not (bobp))
23319 (when (equal marker (get-text-property (point) 'org-marker))
23320 (move-to-column (- (window-width) (length stamp)) t)
23321 (if (featurep 'xemacs)
23322 ;; Use `duplicable' property to trigger undo recording
23323 (let ((ex (make-extent nil nil))
23324 (gl (make-glyph stamp)))
23325 (set-glyph-face gl 'secondary-selection)
23326 (set-extent-properties
23327 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23328 (insert-extent ex (1- (point)) (point-at-eol)))
23329 (add-text-properties
23330 (1- (point)) (point-at-eol)
23331 (list 'display (org-add-props stamp nil
23332 'face 'secondary-selection))))
23333 (beginning-of-line 1))
23334 (beginning-of-line 0)))))
23336 (defun org-agenda-date-prompt (arg)
23337 "Change the date of this item. Date is prompted for, with default today.
23338 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23339 be used to request time specification in the time stamp."
23340 (interactive "P")
23341 (org-agenda-check-type t 'agenda 'timeline)
23342 (org-agenda-check-no-diary)
23343 (let* ((marker (or (get-text-property (point) 'org-marker)
23344 (org-agenda-error)))
23345 (buffer (marker-buffer marker))
23346 (pos (marker-position marker)))
23347 (org-with-remote-undo buffer
23348 (with-current-buffer buffer
23349 (widen)
23350 (goto-char pos)
23351 (if (not (org-at-timestamp-p))
23352 (error "Cannot find time stamp"))
23353 (org-time-stamp arg)
23354 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23356 (defun org-agenda-schedule (arg)
23357 "Schedule the item at point."
23358 (interactive "P")
23359 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23360 (org-agenda-check-no-diary)
23361 (let* ((marker (or (get-text-property (point) 'org-marker)
23362 (org-agenda-error)))
23363 (buffer (marker-buffer marker))
23364 (pos (marker-position marker))
23365 (org-insert-labeled-timestamps-at-point nil)
23367 (message "%s" (marker-insertion-type marker)) (sit-for 3)
23368 (set-marker-insertion-type marker t)
23369 (org-with-remote-undo buffer
23370 (with-current-buffer buffer
23371 (widen)
23372 (goto-char pos)
23373 (setq ts (org-schedule arg)))
23374 (org-agenda-show-new-time marker ts "S"))
23375 (message "Item scheduled for %s" ts)))
23377 (defun org-agenda-deadline (arg)
23378 "Schedule the item at point."
23379 (interactive "P")
23380 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23381 (org-agenda-check-no-diary)
23382 (let* ((marker (or (get-text-property (point) 'org-marker)
23383 (org-agenda-error)))
23384 (buffer (marker-buffer marker))
23385 (pos (marker-position marker))
23386 (org-insert-labeled-timestamps-at-point nil)
23388 (org-with-remote-undo buffer
23389 (with-current-buffer buffer
23390 (widen)
23391 (goto-char pos)
23392 (setq ts (org-deadline arg)))
23393 (org-agenda-show-new-time marker ts "S"))
23394 (message "Deadline for this item set to %s" ts)))
23396 (defun org-get-heading (&optional no-tags)
23397 "Return the heading of the current entry, without the stars."
23398 (save-excursion
23399 (org-back-to-heading t)
23400 (if (looking-at
23401 (if no-tags
23402 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23403 "\\*+[ \t]+\\([^\r\n]*\\)"))
23404 (match-string 1) "")))
23406 (defun org-agenda-clock-in (&optional arg)
23407 "Start the clock on the currently selected item."
23408 (interactive "P")
23409 (org-agenda-check-no-diary)
23410 (let* ((marker (or (get-text-property (point) 'org-marker)
23411 (org-agenda-error)))
23412 (pos (marker-position marker)))
23413 (org-with-remote-undo (marker-buffer marker)
23414 (with-current-buffer (marker-buffer marker)
23415 (widen)
23416 (goto-char pos)
23417 (org-clock-in)))))
23419 (defun org-agenda-clock-out (&optional arg)
23420 "Stop the currently running clock."
23421 (interactive "P")
23422 (unless (marker-buffer org-clock-marker)
23423 (error "No running clock"))
23424 (org-with-remote-undo (marker-buffer org-clock-marker)
23425 (org-clock-out)))
23427 (defun org-agenda-clock-cancel (&optional arg)
23428 "Cancel the currently running clock."
23429 (interactive "P")
23430 (unless (marker-buffer org-clock-marker)
23431 (error "No running clock"))
23432 (org-with-remote-undo (marker-buffer org-clock-marker)
23433 (org-clock-cancel)))
23435 (defun org-agenda-diary-entry ()
23436 "Make a diary entry, like the `i' command from the calendar.
23437 All the standard commands work: block, weekly etc."
23438 (interactive)
23439 (org-agenda-check-type t 'agenda 'timeline)
23440 (require 'diary-lib)
23441 (let* ((char (progn
23442 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23443 (read-char-exclusive)))
23444 (cmd (cdr (assoc char
23445 '((?d . insert-diary-entry)
23446 (?w . insert-weekly-diary-entry)
23447 (?m . insert-monthly-diary-entry)
23448 (?y . insert-yearly-diary-entry)
23449 (?a . insert-anniversary-diary-entry)
23450 (?b . insert-block-diary-entry)
23451 (?c . insert-cyclic-diary-entry)))))
23452 (oldf (symbol-function 'calendar-cursor-to-date))
23453 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23454 (point (point))
23455 (mark (or (mark t) (point))))
23456 (unless cmd
23457 (error "No command associated with <%c>" char))
23458 (unless (and (get-text-property point 'day)
23459 (or (not (equal ?b char))
23460 (get-text-property mark 'day)))
23461 (error "Don't know which date to use for diary entry"))
23462 ;; We implement this by hacking the `calendar-cursor-to-date' function
23463 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23464 (let ((calendar-mark-ring
23465 (list (calendar-gregorian-from-absolute
23466 (or (get-text-property mark 'day)
23467 (get-text-property point 'day))))))
23468 (unwind-protect
23469 (progn
23470 (fset 'calendar-cursor-to-date
23471 (lambda (&optional error)
23472 (calendar-gregorian-from-absolute
23473 (get-text-property point 'day))))
23474 (call-interactively cmd))
23475 (fset 'calendar-cursor-to-date oldf)))))
23478 (defun org-agenda-execute-calendar-command (cmd)
23479 "Execute a calendar command from the agenda, with the date associated to
23480 the cursor position."
23481 (org-agenda-check-type t 'agenda 'timeline)
23482 (require 'diary-lib)
23483 (unless (get-text-property (point) 'day)
23484 (error "Don't know which date to use for calendar command"))
23485 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23486 (point (point))
23487 (date (calendar-gregorian-from-absolute
23488 (get-text-property point 'day)))
23489 ;; the following 3 vars are needed in the calendar
23490 (displayed-day (extract-calendar-day date))
23491 (displayed-month (extract-calendar-month date))
23492 (displayed-year (extract-calendar-year date)))
23493 (unwind-protect
23494 (progn
23495 (fset 'calendar-cursor-to-date
23496 (lambda (&optional error)
23497 (calendar-gregorian-from-absolute
23498 (get-text-property point 'day))))
23499 (call-interactively cmd))
23500 (fset 'calendar-cursor-to-date oldf))))
23502 (defun org-agenda-phases-of-moon ()
23503 "Display the phases of the moon for the 3 months around the cursor date."
23504 (interactive)
23505 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23507 (defun org-agenda-holidays ()
23508 "Display the holidays for the 3 months around the cursor date."
23509 (interactive)
23510 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23512 (defun org-agenda-sunrise-sunset (arg)
23513 "Display sunrise and sunset for the cursor date.
23514 Latitude and longitude can be specified with the variables
23515 `calendar-latitude' and `calendar-longitude'. When called with prefix
23516 argument, latitude and longitude will be prompted for."
23517 (interactive "P")
23518 (let ((calendar-longitude (if arg nil calendar-longitude))
23519 (calendar-latitude (if arg nil calendar-latitude))
23520 (calendar-location-name
23521 (if arg "the given coordinates" calendar-location-name)))
23522 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23524 (defun org-agenda-goto-calendar ()
23525 "Open the Emacs calendar with the date at the cursor."
23526 (interactive)
23527 (org-agenda-check-type t 'agenda 'timeline)
23528 (let* ((day (or (get-text-property (point) 'day)
23529 (error "Don't know which date to open in calendar")))
23530 (date (calendar-gregorian-from-absolute day))
23531 (calendar-move-hook nil)
23532 (view-calendar-holidays-initially nil)
23533 (view-diary-entries-initially nil))
23534 (calendar)
23535 (calendar-goto-date date)))
23537 (defun org-calendar-goto-agenda ()
23538 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23539 This is a command that has to be installed in `calendar-mode-map'."
23540 (interactive)
23541 (org-agenda-list nil (calendar-absolute-from-gregorian
23542 (calendar-cursor-to-date))
23543 nil))
23545 (defun org-agenda-convert-date ()
23546 (interactive)
23547 (org-agenda-check-type t 'agenda 'timeline)
23548 (let ((day (get-text-property (point) 'day))
23549 date s)
23550 (unless day
23551 (error "Don't know which date to convert"))
23552 (setq date (calendar-gregorian-from-absolute day))
23553 (setq s (concat
23554 "Gregorian: " (calendar-date-string date) "\n"
23555 "ISO: " (calendar-iso-date-string date) "\n"
23556 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23557 "Julian: " (calendar-julian-date-string date) "\n"
23558 "Astron. JD: " (calendar-astro-date-string date)
23559 " (Julian date number at noon UTC)\n"
23560 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23561 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23562 "French: " (calendar-french-date-string date) "\n"
23563 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23564 "Mayan: " (calendar-mayan-date-string date) "\n"
23565 "Coptic: " (calendar-coptic-date-string date) "\n"
23566 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23567 "Persian: " (calendar-persian-date-string date) "\n"
23568 "Chinese: " (calendar-chinese-date-string date) "\n"))
23569 (with-output-to-temp-buffer "*Dates*"
23570 (princ s))
23571 (if (fboundp 'fit-window-to-buffer)
23572 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23575 ;;;; Embedded LaTeX
23577 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23578 "Keymap for the minor `org-cdlatex-mode'.")
23580 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23581 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23582 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23583 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23584 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23586 (defvar org-cdlatex-texmathp-advice-is-done nil
23587 "Flag remembering if we have applied the advice to texmathp already.")
23589 (define-minor-mode org-cdlatex-mode
23590 "Toggle the minor `org-cdlatex-mode'.
23591 This mode supports entering LaTeX environment and math in LaTeX fragments
23592 in Org-mode.
23593 \\{org-cdlatex-mode-map}"
23594 nil " OCDL" nil
23595 (when org-cdlatex-mode (require 'cdlatex))
23596 (unless org-cdlatex-texmathp-advice-is-done
23597 (setq org-cdlatex-texmathp-advice-is-done t)
23598 (defadvice texmathp (around org-math-always-on activate)
23599 "Always return t in org-mode buffers.
23600 This is because we want to insert math symbols without dollars even outside
23601 the LaTeX math segments. If Orgmode thinks that point is actually inside
23602 en embedded LaTeX fragement, let texmathp do its job.
23603 \\[org-cdlatex-mode-map]"
23604 (interactive)
23605 (let (p)
23606 (cond
23607 ((not (org-mode-p)) ad-do-it)
23608 ((eq this-command 'cdlatex-math-symbol)
23609 (setq ad-return-value t
23610 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23612 (let ((p (org-inside-LaTeX-fragment-p)))
23613 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23614 (setq ad-return-value t
23615 texmathp-why '("Org-mode embedded math" . 0))
23616 (if p ad-do-it)))))))))
23618 (defun turn-on-org-cdlatex ()
23619 "Unconditionally turn on `org-cdlatex-mode'."
23620 (org-cdlatex-mode 1))
23622 (defun org-inside-LaTeX-fragment-p ()
23623 "Test if point is inside a LaTeX fragment.
23624 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23625 sequence appearing also before point.
23626 Even though the matchers for math are configurable, this function assumes
23627 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23628 delimiters are skipped when they have been removed by customization.
23629 The return value is nil, or a cons cell with the delimiter and
23630 and the position of this delimiter.
23632 This function does a reasonably good job, but can locally be fooled by
23633 for example currency specifications. For example it will assume being in
23634 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23635 fragments that are properly closed, but during editing, we have to live
23636 with the uncertainty caused by missing closing delimiters. This function
23637 looks only before point, not after."
23638 (catch 'exit
23639 (let ((pos (point))
23640 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23641 (lim (progn
23642 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23643 (point)))
23644 dd-on str (start 0) m re)
23645 (goto-char pos)
23646 (when dodollar
23647 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23648 re (nth 1 (assoc "$" org-latex-regexps)))
23649 (while (string-match re str start)
23650 (cond
23651 ((= (match-end 0) (length str))
23652 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23653 ((= (match-end 0) (- (length str) 5))
23654 (throw 'exit nil))
23655 (t (setq start (match-end 0))))))
23656 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23657 (goto-char pos)
23658 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23659 (and (match-beginning 2) (throw 'exit nil))
23660 ;; count $$
23661 (while (re-search-backward "\\$\\$" lim t)
23662 (setq dd-on (not dd-on)))
23663 (goto-char pos)
23664 (if dd-on (cons "$$" m))))))
23667 (defun org-try-cdlatex-tab ()
23668 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23669 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23670 - inside a LaTeX fragment, or
23671 - after the first word in a line, where an abbreviation expansion could
23672 insert a LaTeX environment."
23673 (when org-cdlatex-mode
23674 (cond
23675 ((save-excursion
23676 (skip-chars-backward "a-zA-Z0-9*")
23677 (skip-chars-backward " \t")
23678 (bolp))
23679 (cdlatex-tab) t)
23680 ((org-inside-LaTeX-fragment-p)
23681 (cdlatex-tab) t)
23682 (t nil))))
23684 (defun org-cdlatex-underscore-caret (&optional arg)
23685 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23686 Revert to the normal definition outside of these fragments."
23687 (interactive "P")
23688 (if (org-inside-LaTeX-fragment-p)
23689 (call-interactively 'cdlatex-sub-superscript)
23690 (let (org-cdlatex-mode)
23691 (call-interactively (key-binding (vector last-input-event))))))
23693 (defun org-cdlatex-math-modify (&optional arg)
23694 "Execute `cdlatex-math-modify' in LaTeX fragments.
23695 Revert to the normal definition outside of these fragments."
23696 (interactive "P")
23697 (if (org-inside-LaTeX-fragment-p)
23698 (call-interactively 'cdlatex-math-modify)
23699 (let (org-cdlatex-mode)
23700 (call-interactively (key-binding (vector last-input-event))))))
23702 (defvar org-latex-fragment-image-overlays nil
23703 "List of overlays carrying the images of latex fragments.")
23704 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23706 (defun org-remove-latex-fragment-image-overlays ()
23707 "Remove all overlays with LaTeX fragment images in current buffer."
23708 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23709 (setq org-latex-fragment-image-overlays nil))
23711 (defun org-preview-latex-fragment (&optional subtree)
23712 "Preview the LaTeX fragment at point, or all locally or globally.
23713 If the cursor is in a LaTeX fragment, create the image and overlay
23714 it over the source code. If there is no fragment at point, display
23715 all fragments in the current text, from one headline to the next. With
23716 prefix SUBTREE, display all fragments in the current subtree. With a
23717 double prefix `C-u C-u', or when the cursor is before the first headline,
23718 display all fragments in the buffer.
23719 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23720 (interactive "P")
23721 (org-remove-latex-fragment-image-overlays)
23722 (save-excursion
23723 (save-restriction
23724 (let (beg end at msg)
23725 (cond
23726 ((or (equal subtree '(16))
23727 (not (save-excursion
23728 (re-search-backward (concat "^" outline-regexp) nil t))))
23729 (setq beg (point-min) end (point-max)
23730 msg "Creating images for buffer...%s"))
23731 ((equal subtree '(4))
23732 (org-back-to-heading)
23733 (setq beg (point) end (org-end-of-subtree t)
23734 msg "Creating images for subtree...%s"))
23736 (if (setq at (org-inside-LaTeX-fragment-p))
23737 (goto-char (max (point-min) (- (cdr at) 2)))
23738 (org-back-to-heading))
23739 (setq beg (point) end (progn (outline-next-heading) (point))
23740 msg (if at "Creating image...%s"
23741 "Creating images for entry...%s"))))
23742 (message msg "")
23743 (narrow-to-region beg end)
23744 (goto-char beg)
23745 (org-format-latex
23746 (concat "ltxpng/" (file-name-sans-extension
23747 (file-name-nondirectory
23748 buffer-file-name)))
23749 default-directory 'overlays msg at 'forbuffer)
23750 (message msg "done. Use `C-c C-c' to remove images.")))))
23752 (defvar org-latex-regexps
23753 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23754 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23755 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23756 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23757 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23758 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23759 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23760 "Regular expressions for matching embedded LaTeX.")
23762 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23763 "Replace LaTeX fragments with links to an image, and produce images."
23764 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23765 (let* ((prefixnodir (file-name-nondirectory prefix))
23766 (absprefix (expand-file-name prefix dir))
23767 (todir (file-name-directory absprefix))
23768 (opt org-format-latex-options)
23769 (matchers (plist-get opt :matchers))
23770 (re-list org-latex-regexps)
23771 (cnt 0) txt link beg end re e checkdir
23772 m n block linkfile movefile ov)
23773 ;; Check if there are old images files with this prefix, and remove them
23774 (when (file-directory-p todir)
23775 (mapc 'delete-file
23776 (directory-files
23777 todir 'full
23778 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23779 ;; Check the different regular expressions
23780 (while (setq e (pop re-list))
23781 (setq m (car e) re (nth 1 e) n (nth 2 e)
23782 block (if (nth 3 e) "\n\n" ""))
23783 (when (member m matchers)
23784 (goto-char (point-min))
23785 (while (re-search-forward re nil t)
23786 (when (or (not at) (equal (cdr at) (match-beginning n)))
23787 (setq txt (match-string n)
23788 beg (match-beginning n) end (match-end n)
23789 cnt (1+ cnt)
23790 linkfile (format "%s_%04d.png" prefix cnt)
23791 movefile (format "%s_%04d.png" absprefix cnt)
23792 link (concat block "[[file:" linkfile "]]" block))
23793 (if msg (message msg cnt))
23794 (goto-char beg)
23795 (unless checkdir ; make sure the directory exists
23796 (setq checkdir t)
23797 (or (file-directory-p todir) (make-directory todir)))
23798 (org-create-formula-image
23799 txt movefile opt forbuffer)
23800 (if overlays
23801 (progn
23802 (setq ov (org-make-overlay beg end))
23803 (if (featurep 'xemacs)
23804 (progn
23805 (org-overlay-put ov 'invisible t)
23806 (org-overlay-put
23807 ov 'end-glyph
23808 (make-glyph (vector 'png :file movefile))))
23809 (org-overlay-put
23810 ov 'display
23811 (list 'image :type 'png :file movefile :ascent 'center)))
23812 (push ov org-latex-fragment-image-overlays)
23813 (goto-char end))
23814 (delete-region beg end)
23815 (insert link))))))))
23817 ;; This function borrows from Ganesh Swami's latex2png.el
23818 (defun org-create-formula-image (string tofile options buffer)
23819 (let* ((tmpdir (if (featurep 'xemacs)
23820 (temp-directory)
23821 temporary-file-directory))
23822 (texfilebase (make-temp-name
23823 (expand-file-name "orgtex" tmpdir)))
23824 (texfile (concat texfilebase ".tex"))
23825 (dvifile (concat texfilebase ".dvi"))
23826 (pngfile (concat texfilebase ".png"))
23827 (fnh (face-attribute 'default :height nil))
23828 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23829 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23830 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23831 "Black"))
23832 (bg (or (plist-get options (if buffer :background :html-background))
23833 "Transparent")))
23834 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23835 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23836 (with-temp-file texfile
23837 (insert org-format-latex-header
23838 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23839 (let ((dir default-directory))
23840 (condition-case nil
23841 (progn
23842 (cd tmpdir)
23843 (call-process "latex" nil nil nil texfile))
23844 (error nil))
23845 (cd dir))
23846 (if (not (file-exists-p dvifile))
23847 (progn (message "Failed to create dvi file from %s" texfile) nil)
23848 (call-process "dvipng" nil nil nil
23849 "-E" "-fg" fg "-bg" bg
23850 "-D" dpi
23851 ;;"-x" scale "-y" scale
23852 "-T" "tight"
23853 "-o" pngfile
23854 dvifile)
23855 (if (not (file-exists-p pngfile))
23856 (progn (message "Failed to create png file from %s" texfile) nil)
23857 ;; Use the requested file name and clean up
23858 (copy-file pngfile tofile 'replace)
23859 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
23860 (delete-file (concat texfilebase e)))
23861 pngfile))))
23863 (defun org-dvipng-color (attr)
23864 "Return an rgb color specification for dvipng."
23865 (apply 'format "rgb %s %s %s"
23866 (mapcar 'org-normalize-color
23867 (color-values (face-attribute 'default attr nil)))))
23869 (defun org-normalize-color (value)
23870 "Return string to be used as color value for an RGB component."
23871 (format "%g" (/ value 65535.0)))
23873 ;;;; Exporting
23875 ;;; Variables, constants, and parameter plists
23877 (defconst org-level-max 20)
23879 (defvar org-export-html-preamble nil
23880 "Preamble, to be inserted just after <body>. Set by publishing functions.")
23881 (defvar org-export-html-postamble nil
23882 "Preamble, to be inserted just before </body>. Set by publishing functions.")
23883 (defvar org-export-html-auto-preamble t
23884 "Should default preamble be inserted? Set by publishing functions.")
23885 (defvar org-export-html-auto-postamble t
23886 "Should default postamble be inserted? Set by publishing functions.")
23887 (defvar org-current-export-file nil) ; dynamically scoped parameter
23888 (defvar org-current-export-dir nil) ; dynamically scoped parameter
23891 (defconst org-export-plist-vars
23892 '((:language . org-export-default-language)
23893 (:customtime . org-display-custom-times)
23894 (:headline-levels . org-export-headline-levels)
23895 (:section-numbers . org-export-with-section-numbers)
23896 (:table-of-contents . org-export-with-toc)
23897 (:preserve-breaks . org-export-preserve-breaks)
23898 (:archived-trees . org-export-with-archived-trees)
23899 (:emphasize . org-export-with-emphasize)
23900 (:sub-superscript . org-export-with-sub-superscripts)
23901 (:special-strings . org-export-with-special-strings)
23902 (:footnotes . org-export-with-footnotes)
23903 (:drawers . org-export-with-drawers)
23904 (:tags . org-export-with-tags)
23905 (:TeX-macros . org-export-with-TeX-macros)
23906 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
23907 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
23908 (:fixed-width . org-export-with-fixed-width)
23909 (:timestamps . org-export-with-timestamps)
23910 (:author-info . org-export-author-info)
23911 (:time-stamp-file . org-export-time-stamp-file)
23912 (:tables . org-export-with-tables)
23913 (:table-auto-headline . org-export-highlight-first-table-line)
23914 (:style . org-export-html-style)
23915 (:agenda-style . org-agenda-export-html-style)
23916 (:convert-org-links . org-export-html-link-org-files-as-html)
23917 (:inline-images . org-export-html-inline-images)
23918 (:html-extension . org-export-html-extension)
23919 (:html-table-tag . org-export-html-table-tag)
23920 (:expand-quoted-html . org-export-html-expand)
23921 (:timestamp . org-export-html-with-timestamp)
23922 (:publishing-directory . org-export-publishing-directory)
23923 (:preamble . org-export-html-preamble)
23924 (:postamble . org-export-html-postamble)
23925 (:auto-preamble . org-export-html-auto-preamble)
23926 (:auto-postamble . org-export-html-auto-postamble)
23927 (:author . user-full-name)
23928 (:email . user-mail-address)))
23930 (defun org-default-export-plist ()
23931 "Return the property list with default settings for the export variables."
23932 (let ((l org-export-plist-vars) rtn e)
23933 (while (setq e (pop l))
23934 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
23935 rtn))
23937 (defun org-infile-export-plist ()
23938 "Return the property list with file-local settings for export."
23939 (save-excursion
23940 (save-restriction
23941 (widen)
23942 (goto-char 0)
23943 (let ((re (org-make-options-regexp
23944 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
23945 p key val text options)
23946 (while (re-search-forward re nil t)
23947 (setq key (org-match-string-no-properties 1)
23948 val (org-match-string-no-properties 2))
23949 (cond
23950 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
23951 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
23952 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
23953 ((string-equal key "DATE") (setq p (plist-put p :date val)))
23954 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
23955 ((string-equal key "TEXT")
23956 (setq text (if text (concat text "\n" val) val)))
23957 ((string-equal key "OPTIONS") (setq options val))))
23958 (setq p (plist-put p :text text))
23959 (when options
23960 (let ((op '(("H" . :headline-levels)
23961 ("num" . :section-numbers)
23962 ("toc" . :table-of-contents)
23963 ("\\n" . :preserve-breaks)
23964 ("@" . :expand-quoted-html)
23965 (":" . :fixed-width)
23966 ("|" . :tables)
23967 ("^" . :sub-superscript)
23968 ("-" . :special-strings)
23969 ("f" . :footnotes)
23970 ("d" . :drawers)
23971 ("tags" . :tags)
23972 ("*" . :emphasize)
23973 ("TeX" . :TeX-macros)
23974 ("LaTeX" . :LaTeX-fragments)
23975 ("skip" . :skip-before-1st-heading)
23976 ("author" . :author-info)
23977 ("timestamp" . :time-stamp-file)))
23979 (while (setq o (pop op))
23980 (if (string-match (concat (regexp-quote (car o))
23981 ":\\([^ \t\n\r;,.]*\\)")
23982 options)
23983 (setq p (plist-put p (cdr o)
23984 (car (read-from-string
23985 (match-string 1 options)))))))))
23986 p))))
23988 (defun org-export-directory (type plist)
23989 (let* ((val (plist-get plist :publishing-directory))
23990 (dir (if (listp val)
23991 (or (cdr (assoc type val)) ".")
23992 val)))
23993 dir))
23995 (defun org-skip-comments (lines)
23996 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
23997 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
23998 (re2 "^\\(\\*+\\)[ \t\n\r]")
23999 (case-fold-search nil)
24000 rtn line level)
24001 (while (setq line (pop lines))
24002 (cond
24003 ((and (string-match re1 line)
24004 (setq level (- (match-end 1) (match-beginning 1))))
24005 ;; Beginning of a COMMENT subtree. Skip it.
24006 (while (and (setq line (pop lines))
24007 (or (not (string-match re2 line))
24008 (> (- (match-end 1) (match-beginning 1)) level))))
24009 (setq lines (cons line lines)))
24010 ((string-match "^#" line)
24011 ;; an ordinary comment line
24013 ((and org-export-table-remove-special-lines
24014 (string-match "^[ \t]*|" line)
24015 (or (string-match "^[ \t]*| *[!_^] *|" line)
24016 (and (string-match "| *<[0-9]+> *|" line)
24017 (not (string-match "| *[^ <|]" line)))))
24018 ;; a special table line that should be removed
24020 (t (setq rtn (cons line rtn)))))
24021 (nreverse rtn)))
24023 (defun org-export (&optional arg)
24024 (interactive)
24025 (let ((help "[t] insert the export option template
24026 \[v] limit export to visible part of outline tree
24028 \[a] export as ASCII
24030 \[h] export as HTML
24031 \[H] export as HTML to temporary buffer
24032 \[R] export region as HTML
24033 \[b] export as HTML and browse immediately
24034 \[x] export as XOXO
24036 \[l] export as LaTeX
24037 \[L] export as LaTeX to temporary buffer
24039 \[i] export current file as iCalendar file
24040 \[I] export all agenda files as iCalendar files
24041 \[c] export agenda files into combined iCalendar file
24043 \[F] publish current file
24044 \[P] publish current project
24045 \[X] publish... (project will be prompted for)
24046 \[A] publish all projects")
24047 (cmds
24048 '((?t . org-insert-export-options-template)
24049 (?v . org-export-visible)
24050 (?a . org-export-as-ascii)
24051 (?h . org-export-as-html)
24052 (?b . org-export-as-html-and-open)
24053 (?H . org-export-as-html-to-buffer)
24054 (?R . org-export-region-as-html)
24055 (?x . org-export-as-xoxo)
24056 (?l . org-export-as-latex)
24057 (?L . org-export-as-latex-to-buffer)
24058 (?i . org-export-icalendar-this-file)
24059 (?I . org-export-icalendar-all-agenda-files)
24060 (?c . org-export-icalendar-combine-agenda-files)
24061 (?F . org-publish-current-file)
24062 (?P . org-publish-current-project)
24063 (?X . org-publish)
24064 (?A . org-publish-all)))
24065 r1 r2 ass)
24066 (save-window-excursion
24067 (delete-other-windows)
24068 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24069 (princ help))
24070 (message "Select command: ")
24071 (setq r1 (read-char-exclusive)))
24072 (setq r2 (if (< r1 27) (+ r1 96) r1))
24073 (if (setq ass (assq r2 cmds))
24074 (call-interactively (cdr ass))
24075 (error "No command associated with key %c" r1))))
24077 (defconst org-html-entities
24078 '(("nbsp")
24079 ("iexcl")
24080 ("cent")
24081 ("pound")
24082 ("curren")
24083 ("yen")
24084 ("brvbar")
24085 ("vert" . "&#124;")
24086 ("sect")
24087 ("uml")
24088 ("copy")
24089 ("ordf")
24090 ("laquo")
24091 ("not")
24092 ("shy")
24093 ("reg")
24094 ("macr")
24095 ("deg")
24096 ("plusmn")
24097 ("sup2")
24098 ("sup3")
24099 ("acute")
24100 ("micro")
24101 ("para")
24102 ("middot")
24103 ("odot"."o")
24104 ("star"."*")
24105 ("cedil")
24106 ("sup1")
24107 ("ordm")
24108 ("raquo")
24109 ("frac14")
24110 ("frac12")
24111 ("frac34")
24112 ("iquest")
24113 ("Agrave")
24114 ("Aacute")
24115 ("Acirc")
24116 ("Atilde")
24117 ("Auml")
24118 ("Aring") ("AA"."&Aring;")
24119 ("AElig")
24120 ("Ccedil")
24121 ("Egrave")
24122 ("Eacute")
24123 ("Ecirc")
24124 ("Euml")
24125 ("Igrave")
24126 ("Iacute")
24127 ("Icirc")
24128 ("Iuml")
24129 ("ETH")
24130 ("Ntilde")
24131 ("Ograve")
24132 ("Oacute")
24133 ("Ocirc")
24134 ("Otilde")
24135 ("Ouml")
24136 ("times")
24137 ("Oslash")
24138 ("Ugrave")
24139 ("Uacute")
24140 ("Ucirc")
24141 ("Uuml")
24142 ("Yacute")
24143 ("THORN")
24144 ("szlig")
24145 ("agrave")
24146 ("aacute")
24147 ("acirc")
24148 ("atilde")
24149 ("auml")
24150 ("aring")
24151 ("aelig")
24152 ("ccedil")
24153 ("egrave")
24154 ("eacute")
24155 ("ecirc")
24156 ("euml")
24157 ("igrave")
24158 ("iacute")
24159 ("icirc")
24160 ("iuml")
24161 ("eth")
24162 ("ntilde")
24163 ("ograve")
24164 ("oacute")
24165 ("ocirc")
24166 ("otilde")
24167 ("ouml")
24168 ("divide")
24169 ("oslash")
24170 ("ugrave")
24171 ("uacute")
24172 ("ucirc")
24173 ("uuml")
24174 ("yacute")
24175 ("thorn")
24176 ("yuml")
24177 ("fnof")
24178 ("Alpha")
24179 ("Beta")
24180 ("Gamma")
24181 ("Delta")
24182 ("Epsilon")
24183 ("Zeta")
24184 ("Eta")
24185 ("Theta")
24186 ("Iota")
24187 ("Kappa")
24188 ("Lambda")
24189 ("Mu")
24190 ("Nu")
24191 ("Xi")
24192 ("Omicron")
24193 ("Pi")
24194 ("Rho")
24195 ("Sigma")
24196 ("Tau")
24197 ("Upsilon")
24198 ("Phi")
24199 ("Chi")
24200 ("Psi")
24201 ("Omega")
24202 ("alpha")
24203 ("beta")
24204 ("gamma")
24205 ("delta")
24206 ("epsilon")
24207 ("varepsilon"."&epsilon;")
24208 ("zeta")
24209 ("eta")
24210 ("theta")
24211 ("iota")
24212 ("kappa")
24213 ("lambda")
24214 ("mu")
24215 ("nu")
24216 ("xi")
24217 ("omicron")
24218 ("pi")
24219 ("rho")
24220 ("sigmaf") ("varsigma"."&sigmaf;")
24221 ("sigma")
24222 ("tau")
24223 ("upsilon")
24224 ("phi")
24225 ("chi")
24226 ("psi")
24227 ("omega")
24228 ("thetasym") ("vartheta"."&thetasym;")
24229 ("upsih")
24230 ("piv")
24231 ("bull") ("bullet"."&bull;")
24232 ("hellip") ("dots"."&hellip;")
24233 ("prime")
24234 ("Prime")
24235 ("oline")
24236 ("frasl")
24237 ("weierp")
24238 ("image")
24239 ("real")
24240 ("trade")
24241 ("alefsym")
24242 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24243 ("uarr") ("uparrow"."&uarr;")
24244 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24245 ("darr")("downarrow"."&darr;")
24246 ("harr") ("leftrightarrow"."&harr;")
24247 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24248 ("lArr") ("Leftarrow"."&lArr;")
24249 ("uArr") ("Uparrow"."&uArr;")
24250 ("rArr") ("Rightarrow"."&rArr;")
24251 ("dArr") ("Downarrow"."&dArr;")
24252 ("hArr") ("Leftrightarrow"."&hArr;")
24253 ("forall")
24254 ("part") ("partial"."&part;")
24255 ("exist") ("exists"."&exist;")
24256 ("empty") ("emptyset"."&empty;")
24257 ("nabla")
24258 ("isin") ("in"."&isin;")
24259 ("notin")
24260 ("ni")
24261 ("prod")
24262 ("sum")
24263 ("minus")
24264 ("lowast") ("ast"."&lowast;")
24265 ("radic")
24266 ("prop") ("proptp"."&prop;")
24267 ("infin") ("infty"."&infin;")
24268 ("ang") ("angle"."&ang;")
24269 ("and") ("wedge"."&and;")
24270 ("or") ("vee"."&or;")
24271 ("cap")
24272 ("cup")
24273 ("int")
24274 ("there4")
24275 ("sim")
24276 ("cong") ("simeq"."&cong;")
24277 ("asymp")("approx"."&asymp;")
24278 ("ne") ("neq"."&ne;")
24279 ("equiv")
24280 ("le")
24281 ("ge")
24282 ("sub") ("subset"."&sub;")
24283 ("sup") ("supset"."&sup;")
24284 ("nsub")
24285 ("sube")
24286 ("supe")
24287 ("oplus")
24288 ("otimes")
24289 ("perp")
24290 ("sdot") ("cdot"."&sdot;")
24291 ("lceil")
24292 ("rceil")
24293 ("lfloor")
24294 ("rfloor")
24295 ("lang")
24296 ("rang")
24297 ("loz") ("Diamond"."&loz;")
24298 ("spades") ("spadesuit"."&spades;")
24299 ("clubs") ("clubsuit"."&clubs;")
24300 ("hearts") ("diamondsuit"."&hearts;")
24301 ("diams") ("diamondsuit"."&diams;")
24302 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24303 ("quot")
24304 ("amp")
24305 ("lt")
24306 ("gt")
24307 ("OElig")
24308 ("oelig")
24309 ("Scaron")
24310 ("scaron")
24311 ("Yuml")
24312 ("circ")
24313 ("tilde")
24314 ("ensp")
24315 ("emsp")
24316 ("thinsp")
24317 ("zwnj")
24318 ("zwj")
24319 ("lrm")
24320 ("rlm")
24321 ("ndash")
24322 ("mdash")
24323 ("lsquo")
24324 ("rsquo")
24325 ("sbquo")
24326 ("ldquo")
24327 ("rdquo")
24328 ("bdquo")
24329 ("dagger")
24330 ("Dagger")
24331 ("permil")
24332 ("lsaquo")
24333 ("rsaquo")
24334 ("euro")
24336 ("arccos"."arccos")
24337 ("arcsin"."arcsin")
24338 ("arctan"."arctan")
24339 ("arg"."arg")
24340 ("cos"."cos")
24341 ("cosh"."cosh")
24342 ("cot"."cot")
24343 ("coth"."coth")
24344 ("csc"."csc")
24345 ("deg"."deg")
24346 ("det"."det")
24347 ("dim"."dim")
24348 ("exp"."exp")
24349 ("gcd"."gcd")
24350 ("hom"."hom")
24351 ("inf"."inf")
24352 ("ker"."ker")
24353 ("lg"."lg")
24354 ("lim"."lim")
24355 ("liminf"."liminf")
24356 ("limsup"."limsup")
24357 ("ln"."ln")
24358 ("log"."log")
24359 ("max"."max")
24360 ("min"."min")
24361 ("Pr"."Pr")
24362 ("sec"."sec")
24363 ("sin"."sin")
24364 ("sinh"."sinh")
24365 ("sup"."sup")
24366 ("tan"."tan")
24367 ("tanh"."tanh")
24369 "Entities for TeX->HTML translation.
24370 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24371 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24372 In that case, \"\\ent\" will be translated to \"&other;\".
24373 The list contains HTML entities for Latin-1, Greek and other symbols.
24374 It is supplemented by a number of commonly used TeX macros with appropriate
24375 translations. There is currently no way for users to extend this.")
24377 ;;; General functions for all backends
24379 (defun org-cleaned-string-for-export (string &rest parameters)
24380 "Cleanup a buffer STRING so that links can be created safely."
24381 (interactive)
24382 (let* ((re-radio (and org-target-link-regexp
24383 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24384 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24385 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24386 (re-archive (concat ":" org-archive-tag ":"))
24387 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24388 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24389 (htmlp (plist-get parameters :for-html))
24390 (asciip (plist-get parameters :for-ascii))
24391 (latexp (plist-get parameters :for-LaTeX))
24392 (commentsp (plist-get parameters :comments))
24393 (archived-trees (plist-get parameters :archived-trees))
24394 (inhibit-read-only t)
24395 (drawers org-drawers)
24396 (exp-drawers (plist-get parameters :drawers))
24397 (outline-regexp "\\*+ ")
24398 a b xx
24399 rtn p)
24400 (with-current-buffer (get-buffer-create " org-mode-tmp")
24401 (erase-buffer)
24402 (insert string)
24403 ;; Remove license-to-kill stuff
24404 (while (setq p (text-property-any (point-min) (point-max)
24405 :org-license-to-kill t))
24406 (delete-region p (next-single-property-change p :org-license-to-kill)))
24408 (let ((org-inhibit-startup t)) (org-mode))
24409 (untabify (point-min) (point-max))
24411 ;; Get rid of drawers
24412 (unless (eq t exp-drawers)
24413 (goto-char (point-min))
24414 (let ((re (concat "^[ \t]*:\\("
24415 (mapconcat
24416 'identity
24417 (org-delete-all exp-drawers
24418 (copy-sequence drawers))
24419 "\\|")
24420 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24421 (while (re-search-forward re nil t)
24422 (replace-match ""))))
24424 ;; Get the correct stuff before the first headline
24425 (when (plist-get parameters :skip-before-1st-heading)
24426 (goto-char (point-min))
24427 (when (re-search-forward "^\\*+[ \t]" nil t)
24428 (delete-region (point-min) (match-beginning 0))
24429 (goto-char (point-min))
24430 (insert "\n")))
24431 (when (plist-get parameters :add-text)
24432 (goto-char (point-min))
24433 (insert (plist-get parameters :add-text) "\n"))
24435 ;; Get rid of archived trees
24436 (when (not (eq archived-trees t))
24437 (goto-char (point-min))
24438 (while (re-search-forward re-archive nil t)
24439 (if (not (org-on-heading-p t))
24440 (org-end-of-subtree t)
24441 (beginning-of-line 1)
24442 (setq a (if archived-trees
24443 (1+ (point-at-eol)) (point))
24444 b (org-end-of-subtree t))
24445 (if (> b a) (delete-region a b)))))
24447 ;; Find targets in comments and move them out of comments,
24448 ;; but mark them as targets that should be invisible
24449 (goto-char (point-min))
24450 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24451 (replace-match "\\1(INVISIBLE)"))
24453 ;; Protect backend specific stuff, throw away the others.
24454 (let ((formatters
24455 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24456 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24457 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24458 fmt)
24459 (goto-char (point-min))
24460 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24461 (goto-char (match-end 0))
24462 (while (not (looking-at "#\\+END_EXAMPLE"))
24463 (insert ": ")
24464 (beginning-of-line 2)))
24465 (goto-char (point-min))
24466 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24467 (add-text-properties (match-beginning 0) (match-end 0)
24468 '(org-protected t)))
24469 (while formatters
24470 (setq fmt (pop formatters))
24471 (when (car fmt)
24472 (goto-char (point-min))
24473 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24474 ":[ \t]*\\(.*\\)") nil t)
24475 (replace-match "\\1" t)
24476 (add-text-properties
24477 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24478 '(org-protected t))))
24479 (goto-char (point-min))
24480 (while (re-search-forward
24481 (concat "^#\\+"
24482 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24483 (cadddr fmt) "\\>.*\n?") nil t)
24484 (if (car fmt)
24485 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24486 '(org-protected t))
24487 (delete-region (match-beginning 0) (match-end 0))))))
24489 ;; Protect quoted subtrees
24490 (goto-char (point-min))
24491 (while (re-search-forward re-quote nil t)
24492 (goto-char (match-beginning 0))
24493 (end-of-line 1)
24494 (add-text-properties (point) (org-end-of-subtree t)
24495 '(org-protected t)))
24497 ;; Protect verbatim elements
24498 (goto-char (point-min))
24499 (while (re-search-forward org-verbatim-re nil t)
24500 (add-text-properties (match-beginning 4) (match-end 4)
24501 '(org-protected t))
24502 (goto-char (1+ (match-end 4))))
24504 ;; Remove subtrees that are commented
24505 (goto-char (point-min))
24506 (while (re-search-forward re-commented nil t)
24507 (goto-char (match-beginning 0))
24508 (delete-region (point) (org-end-of-subtree t)))
24510 ;; Remove special table lines
24511 (when org-export-table-remove-special-lines
24512 (goto-char (point-min))
24513 (while (re-search-forward "^[ \t]*|" nil t)
24514 (beginning-of-line 1)
24515 (if (or (looking-at "[ \t]*| *[!_^] *|")
24516 (and (looking-at ".*?| *<[0-9]+> *|")
24517 (not (looking-at ".*?| *[^ <|]"))))
24518 (delete-region (max (point-min) (1- (point-at-bol)))
24519 (point-at-eol))
24520 (end-of-line 1))))
24522 ;; Specific LaTeX stuff
24523 (when latexp
24524 (require 'org-export-latex nil)
24525 (org-export-latex-cleaned-string))
24527 (when asciip
24528 (org-export-ascii-clean-string))
24530 ;; Specific HTML stuff
24531 (when htmlp
24532 ;; Convert LaTeX fragments to images
24533 (when (plist-get parameters :LaTeX-fragments)
24534 (org-format-latex
24535 (concat "ltxpng/" (file-name-sans-extension
24536 (file-name-nondirectory
24537 org-current-export-file)))
24538 org-current-export-dir nil "Creating LaTeX image %s"))
24539 (message "Exporting..."))
24541 ;; Remove or replace comments
24542 (goto-char (point-min))
24543 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24544 (if commentsp
24545 (progn (add-text-properties
24546 (match-beginning 0) (match-end 0) '(org-protected t))
24547 (replace-match (format commentsp (match-string 1)) t t))
24548 (replace-match "")))
24550 ;; Find matches for radio targets and turn them into internal links
24551 (goto-char (point-min))
24552 (when re-radio
24553 (while (re-search-forward re-radio nil t)
24554 (org-if-unprotected
24555 (replace-match "\\1[[\\2]]"))))
24557 ;; Find all links that contain a newline and put them into a single line
24558 (goto-char (point-min))
24559 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24560 (org-if-unprotected
24561 (replace-match "\\1 \\3")
24562 (goto-char (match-beginning 0))))
24565 ;; Normalize links: Convert angle and plain links into bracket links
24566 ;; Expand link abbreviations
24567 (goto-char (point-min))
24568 (while (re-search-forward re-plain-link nil t)
24569 (goto-char (1- (match-end 0)))
24570 (org-if-unprotected
24571 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24572 ":" (match-string 3) "]]")))
24573 ;; added 'org-link face to links
24574 (put-text-property 0 (length s) 'face 'org-link s)
24575 (replace-match s t t))))
24576 (goto-char (point-min))
24577 (while (re-search-forward re-angle-link nil t)
24578 (goto-char (1- (match-end 0)))
24579 (org-if-unprotected
24580 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24581 ":" (match-string 3) "]]")))
24582 (put-text-property 0 (length s) 'face 'org-link s)
24583 (replace-match s t t))))
24584 (goto-char (point-min))
24585 (while (re-search-forward org-bracket-link-regexp nil t)
24586 (org-if-unprotected
24587 (let* ((s (concat "[[" (setq xx (save-match-data
24588 (org-link-expand-abbrev (match-string 1))))
24590 (if (match-end 3)
24591 (match-string 2)
24592 (concat "[" xx "]"))
24593 "]")))
24594 (put-text-property 0 (length s) 'face 'org-link s)
24595 (replace-match s t t))))
24597 ;; Find multiline emphasis and put them into single line
24598 (when (plist-get parameters :emph-multiline)
24599 (goto-char (point-min))
24600 (while (re-search-forward org-emph-re nil t)
24601 (if (not (= (char-after (match-beginning 3))
24602 (char-after (match-beginning 4))))
24603 (org-if-unprotected
24604 (subst-char-in-region (match-beginning 0) (match-end 0)
24605 ?\n ?\ t)
24606 (goto-char (1- (match-end 0))))
24607 (goto-char (1+ (match-beginning 0))))))
24609 (setq rtn (buffer-string)))
24610 (kill-buffer " org-mode-tmp")
24611 rtn))
24613 (defun org-export-grab-title-from-buffer ()
24614 "Get a title for the current document, from looking at the buffer."
24615 (let ((inhibit-read-only t))
24616 (save-excursion
24617 (goto-char (point-min))
24618 (let ((end (save-excursion (outline-next-heading) (point))))
24619 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24620 ;; Mark the line so that it will not be exported as normal text.
24621 (org-unmodified
24622 (add-text-properties (match-beginning 0) (match-end 0)
24623 (list :org-license-to-kill t)))
24624 ;; Return the title string
24625 (org-trim (match-string 0)))))))
24627 (defun org-export-get-title-from-subtree ()
24628 "Return subtree title and exclude it from export."
24629 (let (title (m (mark)))
24630 (save-excursion
24631 (goto-char (region-beginning))
24632 (when (and (org-at-heading-p)
24633 (>= (org-end-of-subtree t t) (region-end)))
24634 ;; This is a subtree, we take the title from the first heading
24635 (goto-char (region-beginning))
24636 (looking-at org-todo-line-regexp)
24637 (setq title (match-string 3))
24638 (org-unmodified
24639 (add-text-properties (point) (1+ (point-at-eol))
24640 (list :org-license-to-kill t)))))
24641 title))
24643 (defun org-solidify-link-text (s &optional alist)
24644 "Take link text and make a safe target out of it."
24645 (save-match-data
24646 (let* ((rtn
24647 (mapconcat
24648 'identity
24649 (org-split-string s "[ \t\r\n]+") "--"))
24650 (a (assoc rtn alist)))
24651 (or (cdr a) rtn))))
24653 (defun org-get-min-level (lines)
24654 "Get the minimum level in LINES."
24655 (let ((re "^\\(\\*+\\) ") l min)
24656 (catch 'exit
24657 (while (setq l (pop lines))
24658 (if (string-match re l)
24659 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24660 1)))
24662 ;; Variable holding the vector with section numbers
24663 (defvar org-section-numbers (make-vector org-level-max 0))
24665 (defun org-init-section-numbers ()
24666 "Initialize the vector for the section numbers."
24667 (let* ((level -1)
24668 (numbers (nreverse (org-split-string "" "\\.")))
24669 (depth (1- (length org-section-numbers)))
24670 (i depth) number-string)
24671 (while (>= i 0)
24672 (if (> i level)
24673 (aset org-section-numbers i 0)
24674 (setq number-string (or (car numbers) "0"))
24675 (if (string-match "\\`[A-Z]\\'" number-string)
24676 (aset org-section-numbers i
24677 (- (string-to-char number-string) ?A -1))
24678 (aset org-section-numbers i (string-to-number number-string)))
24679 (pop numbers))
24680 (setq i (1- i)))))
24682 (defun org-section-number (&optional level)
24683 "Return a string with the current section number.
24684 When LEVEL is non-nil, increase section numbers on that level."
24685 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24686 (when level
24687 (when (> level -1)
24688 (aset org-section-numbers
24689 level (1+ (aref org-section-numbers level))))
24690 (setq idx (1+ level))
24691 (while (<= idx depth)
24692 (if (not (= idx 1))
24693 (aset org-section-numbers idx 0))
24694 (setq idx (1+ idx))))
24695 (setq idx 0)
24696 (while (<= idx depth)
24697 (setq n (aref org-section-numbers idx))
24698 (setq string (concat string (if (not (string= string "")) "." "")
24699 (int-to-string n)))
24700 (setq idx (1+ idx)))
24701 (save-match-data
24702 (if (string-match "\\`\\([@0]\\.\\)+" string)
24703 (setq string (replace-match "" t nil string)))
24704 (if (string-match "\\(\\.0\\)+\\'" string)
24705 (setq string (replace-match "" t nil string))))
24706 string))
24708 ;;; ASCII export
24710 (defvar org-last-level nil) ; dynamically scoped variable
24711 (defvar org-min-level nil) ; dynamically scoped variable
24712 (defvar org-levels-open nil) ; dynamically scoped parameter
24713 (defvar org-ascii-current-indentation nil) ; For communication
24715 (defun org-export-as-ascii (arg)
24716 "Export the outline as a pretty ASCII file.
24717 If there is an active region, export only the region.
24718 The prefix ARG specifies how many levels of the outline should become
24719 underlined headlines. The default is 3."
24720 (interactive "P")
24721 (setq-default org-todo-line-regexp org-todo-line-regexp)
24722 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24723 (org-infile-export-plist)))
24724 (region-p (org-region-active-p))
24725 (subtree-p
24726 (when region-p
24727 (save-excursion
24728 (goto-char (region-beginning))
24729 (and (org-at-heading-p)
24730 (>= (org-end-of-subtree t t) (region-end))))))
24731 (custom-times org-display-custom-times)
24732 (org-ascii-current-indentation '(0 . 0))
24733 (level 0) line txt
24734 (umax nil)
24735 (umax-toc nil)
24736 (case-fold-search nil)
24737 (filename (concat (file-name-as-directory
24738 (org-export-directory :ascii opt-plist))
24739 (file-name-sans-extension
24740 (or (and subtree-p
24741 (org-entry-get (region-beginning)
24742 "EXPORT_FILE_NAME" t))
24743 (file-name-nondirectory buffer-file-name)))
24744 ".txt"))
24745 (filename (if (equal (file-truename filename)
24746 (file-truename buffer-file-name))
24747 (concat filename ".txt")
24748 filename))
24749 (buffer (find-file-noselect filename))
24750 (org-levels-open (make-vector org-level-max nil))
24751 (odd org-odd-levels-only)
24752 (date (plist-get opt-plist :date))
24753 (author (plist-get opt-plist :author))
24754 (title (or (and subtree-p (org-export-get-title-from-subtree))
24755 (plist-get opt-plist :title)
24756 (and (not
24757 (plist-get opt-plist :skip-before-1st-heading))
24758 (org-export-grab-title-from-buffer))
24759 (file-name-sans-extension
24760 (file-name-nondirectory buffer-file-name))))
24761 (email (plist-get opt-plist :email))
24762 (language (plist-get opt-plist :language))
24763 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24764 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24765 (todo nil)
24766 (lang-words nil)
24767 (region
24768 (buffer-substring
24769 (if (org-region-active-p) (region-beginning) (point-min))
24770 (if (org-region-active-p) (region-end) (point-max))))
24771 (lines (org-split-string
24772 (org-cleaned-string-for-export
24773 region
24774 :for-ascii t
24775 :skip-before-1st-heading
24776 (plist-get opt-plist :skip-before-1st-heading)
24777 :drawers (plist-get opt-plist :drawers)
24778 :verbatim-multiline t
24779 :archived-trees
24780 (plist-get opt-plist :archived-trees)
24781 :add-text (plist-get opt-plist :text))
24782 "\n"))
24783 thetoc have-headings first-heading-pos
24784 table-open table-buffer)
24786 (let ((inhibit-read-only t))
24787 (org-unmodified
24788 (remove-text-properties (point-min) (point-max)
24789 '(:org-license-to-kill t))))
24791 (setq org-min-level (org-get-min-level lines))
24792 (setq org-last-level org-min-level)
24793 (org-init-section-numbers)
24795 (find-file-noselect filename)
24797 (setq lang-words (or (assoc language org-export-language-setup)
24798 (assoc "en" org-export-language-setup)))
24799 (switch-to-buffer-other-window buffer)
24800 (erase-buffer)
24801 (fundamental-mode)
24802 ;; create local variables for all options, to make sure all called
24803 ;; functions get the correct information
24804 (mapc (lambda (x)
24805 (set (make-local-variable (cdr x))
24806 (plist-get opt-plist (car x))))
24807 org-export-plist-vars)
24808 (org-set-local 'org-odd-levels-only odd)
24809 (setq umax (if arg (prefix-numeric-value arg)
24810 org-export-headline-levels))
24811 (setq umax-toc (if (integerp org-export-with-toc)
24812 (min org-export-with-toc umax)
24813 umax))
24815 ;; File header
24816 (if title (org-insert-centered title ?=))
24817 (insert "\n")
24818 (if (and (or author email)
24819 org-export-author-info)
24820 (insert (concat (nth 1 lang-words) ": " (or author "")
24821 (if email (concat " <" email ">") "")
24822 "\n")))
24824 (cond
24825 ((and date (string-match "%" date))
24826 (setq date (format-time-string date (current-time))))
24827 (date)
24828 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24830 (if (and date org-export-time-stamp-file)
24831 (insert (concat (nth 2 lang-words) ": " date"\n")))
24833 (insert "\n\n")
24835 (if org-export-with-toc
24836 (progn
24837 (push (concat (nth 3 lang-words) "\n") thetoc)
24838 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24839 (mapc '(lambda (line)
24840 (if (string-match org-todo-line-regexp
24841 line)
24842 ;; This is a headline
24843 (progn
24844 (setq have-headings t)
24845 (setq level (- (match-end 1) (match-beginning 1))
24846 level (org-tr-level level)
24847 txt (match-string 3 line)
24848 todo
24849 (or (and org-export-mark-todo-in-toc
24850 (match-beginning 2)
24851 (not (member (match-string 2 line)
24852 org-done-keywords)))
24853 ; TODO, not DONE
24854 (and org-export-mark-todo-in-toc
24855 (= level umax-toc)
24856 (org-search-todo-below
24857 line lines level))))
24858 (setq txt (org-html-expand-for-ascii txt))
24860 (while (string-match org-bracket-link-regexp txt)
24861 (setq txt
24862 (replace-match
24863 (match-string (if (match-end 2) 3 1) txt)
24864 t t txt)))
24866 (if (and (memq org-export-with-tags '(not-in-toc nil))
24867 (string-match
24868 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
24869 txt))
24870 (setq txt (replace-match "" t t txt)))
24871 (if (string-match quote-re0 txt)
24872 (setq txt (replace-match "" t t txt)))
24874 (if org-export-with-section-numbers
24875 (setq txt (concat (org-section-number level)
24876 " " txt)))
24877 (if (<= level umax-toc)
24878 (progn
24879 (push
24880 (concat
24881 (make-string
24882 (* (max 0 (- level org-min-level)) 4) ?\ )
24883 (format (if todo "%s (*)\n" "%s\n") txt))
24884 thetoc)
24885 (setq org-last-level level))
24886 ))))
24887 lines)
24888 (setq thetoc (if have-headings (nreverse thetoc) nil))))
24890 (org-init-section-numbers)
24891 (while (setq line (pop lines))
24892 ;; Remove the quoted HTML tags.
24893 (setq line (org-html-expand-for-ascii line))
24894 ;; Remove targets
24895 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
24896 (setq line (replace-match "" t t line)))
24897 ;; Replace internal links
24898 (while (string-match org-bracket-link-regexp line)
24899 (setq line (replace-match
24900 (if (match-end 3) "[\\3]" "[\\1]")
24901 t nil line)))
24902 (when custom-times
24903 (setq line (org-translate-time line)))
24904 (cond
24905 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
24906 ;; a Headline
24907 (setq first-heading-pos (or first-heading-pos (point)))
24908 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
24909 txt (match-string 2 line))
24910 (org-ascii-level-start level txt umax lines))
24912 ((and org-export-with-tables
24913 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
24914 (if (not table-open)
24915 ;; New table starts
24916 (setq table-open t table-buffer nil))
24917 ;; Accumulate lines
24918 (setq table-buffer (cons line table-buffer))
24919 (when (or (not lines)
24920 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
24921 (car lines))))
24922 (setq table-open nil
24923 table-buffer (nreverse table-buffer))
24924 (insert (mapconcat
24925 (lambda (x)
24926 (org-fix-indentation x org-ascii-current-indentation))
24927 (org-format-table-ascii table-buffer)
24928 "\n") "\n")))
24930 (setq line (org-fix-indentation line org-ascii-current-indentation))
24931 (if (and org-export-with-fixed-width
24932 (string-match "^\\([ \t]*\\)\\(:\\)" line))
24933 (setq line (replace-match "\\1" nil nil line)))
24934 (insert line "\n"))))
24936 (normal-mode)
24938 ;; insert the table of contents
24939 (when thetoc
24940 (goto-char (point-min))
24941 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
24942 (progn
24943 (goto-char (match-beginning 0))
24944 (replace-match ""))
24945 (goto-char first-heading-pos))
24946 (mapc 'insert thetoc)
24947 (or (looking-at "[ \t]*\n[ \t]*\n")
24948 (insert "\n\n")))
24950 ;; Convert whitespace place holders
24951 (goto-char (point-min))
24952 (let (beg end)
24953 (while (setq beg (next-single-property-change (point) 'org-whitespace))
24954 (setq end (next-single-property-change beg 'org-whitespace))
24955 (goto-char beg)
24956 (delete-region beg end)
24957 (insert (make-string (- end beg) ?\ ))))
24959 (save-buffer)
24960 ;; remove display and invisible chars
24961 (let (beg end)
24962 (goto-char (point-min))
24963 (while (setq beg (next-single-property-change (point) 'display))
24964 (setq end (next-single-property-change beg 'display))
24965 (delete-region beg end)
24966 (goto-char beg)
24967 (insert "=>"))
24968 (goto-char (point-min))
24969 (while (setq beg (next-single-property-change (point) 'org-cwidth))
24970 (setq end (next-single-property-change beg 'org-cwidth))
24971 (delete-region beg end)
24972 (goto-char beg)))
24973 (goto-char (point-min))))
24975 (defun org-export-ascii-clean-string ()
24976 "Do extra work for ASCII export"
24977 (goto-char (point-min))
24978 (while (re-search-forward org-verbatim-re nil t)
24979 (goto-char (match-end 2))
24980 (backward-delete-char 1) (insert "'")
24981 (goto-char (match-beginning 2))
24982 (delete-char 1) (insert "`")
24983 (goto-char (match-end 2))))
24985 (defun org-search-todo-below (line lines level)
24986 "Search the subtree below LINE for any TODO entries."
24987 (let ((rest (cdr (memq line lines)))
24988 (re org-todo-line-regexp)
24989 line lv todo)
24990 (catch 'exit
24991 (while (setq line (pop rest))
24992 (if (string-match re line)
24993 (progn
24994 (setq lv (- (match-end 1) (match-beginning 1))
24995 todo (and (match-beginning 2)
24996 (not (member (match-string 2 line)
24997 org-done-keywords))))
24998 ; TODO, not DONE
24999 (if (<= lv level) (throw 'exit nil))
25000 (if todo (throw 'exit t))))))))
25002 (defun org-html-expand-for-ascii (line)
25003 "Handle quoted HTML for ASCII export."
25004 (if org-export-html-expand
25005 (while (string-match "@<[^<>\n]*>" line)
25006 ;; We just remove the tags for now.
25007 (setq line (replace-match "" nil nil line))))
25008 line)
25010 (defun org-insert-centered (s &optional underline)
25011 "Insert the string S centered and underline it with character UNDERLINE."
25012 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25013 (insert (make-string ind ?\ ) s "\n")
25014 (if underline
25015 (insert (make-string ind ?\ )
25016 (make-string (string-width s) underline)
25017 "\n"))))
25019 (defun org-ascii-level-start (level title umax &optional lines)
25020 "Insert a new level in ASCII export."
25021 (let (char (n (- level umax 1)) (ind 0))
25022 (if (> level umax)
25023 (progn
25024 (insert (make-string (* 2 n) ?\ )
25025 (char-to-string (nth (% n (length org-export-ascii-bullets))
25026 org-export-ascii-bullets))
25027 " " title "\n")
25028 ;; find the indentation of the next non-empty line
25029 (catch 'stop
25030 (while lines
25031 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25032 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25033 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25034 (pop lines)))
25035 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25036 (if (or (not (equal (char-before) ?\n))
25037 (not (equal (char-before (1- (point))) ?\n)))
25038 (insert "\n"))
25039 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25040 (unless org-export-with-tags
25041 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25042 (setq title (replace-match "" t t title))))
25043 (if org-export-with-section-numbers
25044 (setq title (concat (org-section-number level) " " title)))
25045 (insert title "\n" (make-string (string-width title) char) "\n")
25046 (setq org-ascii-current-indentation '(0 . 0)))))
25048 (defun org-export-visible (type arg)
25049 "Create a copy of the visible part of the current buffer, and export it.
25050 The copy is created in a temporary buffer and removed after use.
25051 TYPE is the final key (as a string) that also select the export command in
25052 the `C-c C-e' export dispatcher.
25053 As a special case, if the you type SPC at the prompt, the temporary
25054 org-mode file will not be removed but presented to you so that you can
25055 continue to use it. The prefix arg ARG is passed through to the exporting
25056 command."
25057 (interactive
25058 (list (progn
25059 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25060 (read-char-exclusive))
25061 current-prefix-arg))
25062 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25063 (error "Invalid export key"))
25064 (let* ((binding (cdr (assoc type
25065 '((?a . org-export-as-ascii)
25066 (?\C-a . org-export-as-ascii)
25067 (?b . org-export-as-html-and-open)
25068 (?\C-b . org-export-as-html-and-open)
25069 (?h . org-export-as-html)
25070 (?H . org-export-as-html-to-buffer)
25071 (?R . org-export-region-as-html)
25072 (?x . org-export-as-xoxo)))))
25073 (keepp (equal type ?\ ))
25074 (file buffer-file-name)
25075 (buffer (get-buffer-create "*Org Export Visible*"))
25076 s e)
25077 ;; Need to hack the drawers here.
25078 (save-excursion
25079 (goto-char (point-min))
25080 (while (re-search-forward org-drawer-regexp nil t)
25081 (goto-char (match-beginning 1))
25082 (or (org-invisible-p) (org-flag-drawer nil))))
25083 (with-current-buffer buffer (erase-buffer))
25084 (save-excursion
25085 (setq s (goto-char (point-min)))
25086 (while (not (= (point) (point-max)))
25087 (goto-char (org-find-invisible))
25088 (append-to-buffer buffer s (point))
25089 (setq s (goto-char (org-find-visible))))
25090 (org-cycle-hide-drawers 'all)
25091 (goto-char (point-min))
25092 (unless keepp
25093 ;; Copy all comment lines to the end, to make sure #+ settings are
25094 ;; still available for the second export step. Kind of a hack, but
25095 ;; does do the trick.
25096 (if (looking-at "#[^\r\n]*")
25097 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25098 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25099 (append-to-buffer buffer (1+ (match-beginning 0))
25100 (min (point-max) (1+ (match-end 0))))))
25101 (set-buffer buffer)
25102 (let ((buffer-file-name file)
25103 (org-inhibit-startup t))
25104 (org-mode)
25105 (show-all)
25106 (unless keepp (funcall binding arg))))
25107 (if (not keepp)
25108 (kill-buffer buffer)
25109 (switch-to-buffer-other-window buffer)
25110 (goto-char (point-min)))))
25112 (defun org-find-visible ()
25113 (let ((s (point)))
25114 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25115 (get-char-property s 'invisible)))
25117 (defun org-find-invisible ()
25118 (let ((s (point)))
25119 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25120 (not (get-char-property s 'invisible))))
25123 ;;; HTML export
25125 (defun org-get-current-options ()
25126 "Return a string with current options as keyword options.
25127 Does include HTML export options as well as TODO and CATEGORY stuff."
25128 (format
25129 "#+TITLE: %s
25130 #+AUTHOR: %s
25131 #+EMAIL: %s
25132 #+LANGUAGE: %s
25133 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25134 #+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
25135 #+CATEGORY: %s
25136 #+SEQ_TODO: %s
25137 #+TYP_TODO: %s
25138 #+PRIORITIES: %c %c %c
25139 #+DRAWERS: %s
25140 #+STARTUP: %s %s %s %s %s
25141 #+TAGS: %s
25142 #+ARCHIVE: %s
25143 #+LINK: %s
25145 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25146 org-export-headline-levels
25147 org-export-with-section-numbers
25148 org-export-with-toc
25149 org-export-preserve-breaks
25150 org-export-html-expand
25151 org-export-with-fixed-width
25152 org-export-with-tables
25153 org-export-with-sub-superscripts
25154 org-export-with-special-strings
25155 org-export-with-footnotes
25156 org-export-with-emphasize
25157 org-export-with-TeX-macros
25158 org-export-with-LaTeX-fragments
25159 org-export-skip-text-before-1st-heading
25160 org-export-with-drawers
25161 org-export-with-tags
25162 (file-name-nondirectory buffer-file-name)
25163 "TODO FEEDBACK VERIFY DONE"
25164 "Me Jason Marie DONE"
25165 org-highest-priority org-lowest-priority org-default-priority
25166 (mapconcat 'identity org-drawers " ")
25167 (cdr (assoc org-startup-folded
25168 '((nil . "showall") (t . "overview") (content . "content"))))
25169 (if org-odd-levels-only "odd" "oddeven")
25170 (if org-hide-leading-stars "hidestars" "showstars")
25171 (if org-startup-align-all-tables "align" "noalign")
25172 (cond ((eq org-log-done t) "logdone")
25173 ((equal org-log-done 'note) "lognotedone")
25174 ((not org-log-done) "nologdone"))
25175 (or (mapconcat (lambda (x)
25176 (cond
25177 ((equal '(:startgroup) x) "{")
25178 ((equal '(:endgroup) x) "}")
25179 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25180 (t (car x))))
25181 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25182 org-archive-location
25183 "org file:~/org/%s.org"
25186 (defun org-insert-export-options-template ()
25187 "Insert into the buffer a template with information for exporting."
25188 (interactive)
25189 (if (not (bolp)) (newline))
25190 (let ((s (org-get-current-options)))
25191 (and (string-match "#\\+CATEGORY" s)
25192 (setq s (substring s 0 (match-beginning 0))))
25193 (insert s)))
25195 (defun org-toggle-fixed-width-section (arg)
25196 "Toggle the fixed-width export.
25197 If there is no active region, the QUOTE keyword at the current headline is
25198 inserted or removed. When present, it causes the text between this headline
25199 and the next to be exported as fixed-width text, and unmodified.
25200 If there is an active region, this command adds or removes a colon as the
25201 first character of this line. If the first character of a line is a colon,
25202 this line is also exported in fixed-width font."
25203 (interactive "P")
25204 (let* ((cc 0)
25205 (regionp (org-region-active-p))
25206 (beg (if regionp (region-beginning) (point)))
25207 (end (if regionp (region-end)))
25208 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25209 (case-fold-search nil)
25210 (re "[ \t]*\\(:\\)")
25211 off)
25212 (if regionp
25213 (save-excursion
25214 (goto-char beg)
25215 (setq cc (current-column))
25216 (beginning-of-line 1)
25217 (setq off (looking-at re))
25218 (while (> nlines 0)
25219 (setq nlines (1- nlines))
25220 (beginning-of-line 1)
25221 (cond
25222 (arg
25223 (move-to-column cc t)
25224 (insert ":\n")
25225 (forward-line -1))
25226 ((and off (looking-at re))
25227 (replace-match "" t t nil 1))
25228 ((not off) (move-to-column cc t) (insert ":")))
25229 (forward-line 1)))
25230 (save-excursion
25231 (org-back-to-heading)
25232 (if (looking-at (concat outline-regexp
25233 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25234 (replace-match "" t t nil 1)
25235 (if (looking-at outline-regexp)
25236 (progn
25237 (goto-char (match-end 0))
25238 (insert org-quote-string " "))))))))
25240 (defun org-export-as-html-and-open (arg)
25241 "Export the outline as HTML and immediately open it with a browser.
25242 If there is an active region, export only the region.
25243 The prefix ARG specifies how many levels of the outline should become
25244 headlines. The default is 3. Lower levels will become bulleted lists."
25245 (interactive "P")
25246 (org-export-as-html arg 'hidden)
25247 (org-open-file buffer-file-name))
25249 (defun org-export-as-html-batch ()
25250 "Call `org-export-as-html', may be used in batch processing as
25251 emacs --batch
25252 --load=$HOME/lib/emacs/org.el
25253 --eval \"(setq org-export-headline-levels 2)\"
25254 --visit=MyFile --funcall org-export-as-html-batch"
25255 (org-export-as-html org-export-headline-levels 'hidden))
25257 (defun org-export-as-html-to-buffer (arg)
25258 "Call `org-exort-as-html` with output to a temporary buffer.
25259 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25260 (interactive "P")
25261 (org-export-as-html arg nil nil "*Org HTML Export*")
25262 (switch-to-buffer-other-window "*Org HTML Export*"))
25264 (defun org-replace-region-by-html (beg end)
25265 "Assume the current region has org-mode syntax, and convert it to HTML.
25266 This can be used in any buffer. For example, you could write an
25267 itemized list in org-mode syntax in an HTML buffer and then use this
25268 command to convert it."
25269 (interactive "r")
25270 (let (reg html buf pop-up-frames)
25271 (save-window-excursion
25272 (if (org-mode-p)
25273 (setq html (org-export-region-as-html
25274 beg end t 'string))
25275 (setq reg (buffer-substring beg end)
25276 buf (get-buffer-create "*Org tmp*"))
25277 (with-current-buffer buf
25278 (erase-buffer)
25279 (insert reg)
25280 (org-mode)
25281 (setq html (org-export-region-as-html
25282 (point-min) (point-max) t 'string)))
25283 (kill-buffer buf)))
25284 (delete-region beg end)
25285 (insert html)))
25287 (defun org-export-region-as-html (beg end &optional body-only buffer)
25288 "Convert region from BEG to END in org-mode buffer to HTML.
25289 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25290 contents, and only produce the region of converted text, useful for
25291 cut-and-paste operations.
25292 If BUFFER is a buffer or a string, use/create that buffer as a target
25293 of the converted HTML. If BUFFER is the symbol `string', return the
25294 produced HTML as a string and leave not buffer behind. For example,
25295 a Lisp program could call this function in the following way:
25297 (setq html (org-export-region-as-html beg end t 'string))
25299 When called interactively, the output buffer is selected, and shown
25300 in a window. A non-interactive call will only retunr the buffer."
25301 (interactive "r\nP")
25302 (when (interactive-p)
25303 (setq buffer "*Org HTML Export*"))
25304 (let ((transient-mark-mode t) (zmacs-regions t)
25305 rtn)
25306 (goto-char end)
25307 (set-mark (point)) ;; to activate the region
25308 (goto-char beg)
25309 (setq rtn (org-export-as-html
25310 nil nil nil
25311 buffer body-only))
25312 (if (fboundp 'deactivate-mark) (deactivate-mark))
25313 (if (and (interactive-p) (bufferp rtn))
25314 (switch-to-buffer-other-window rtn)
25315 rtn)))
25317 (defvar html-table-tag nil) ; dynamically scoped into this.
25318 (defun org-export-as-html (arg &optional hidden ext-plist
25319 to-buffer body-only pub-dir)
25320 "Export the outline as a pretty HTML file.
25321 If there is an active region, export only the region. The prefix
25322 ARG specifies how many levels of the outline should become
25323 headlines. The default is 3. Lower levels will become bulleted
25324 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25325 EXT-PLIST is a property list with external parameters overriding
25326 org-mode's default settings, but still inferior to file-local
25327 settings. When TO-BUFFER is non-nil, create a buffer with that
25328 name and export to that buffer. If TO-BUFFER is the symbol
25329 `string', don't leave any buffer behind but just return the
25330 resulting HTML as a string. When BODY-ONLY is set, don't produce
25331 the file header and footer, simply return the content of
25332 <body>...</body>, without even the body tags themselves. When
25333 PUB-DIR is set, use this as the publishing directory."
25334 (interactive "P")
25336 ;; Make sure we have a file name when we need it.
25337 (when (and (not (or to-buffer body-only))
25338 (not buffer-file-name))
25339 (if (buffer-base-buffer)
25340 (org-set-local 'buffer-file-name
25341 (with-current-buffer (buffer-base-buffer)
25342 buffer-file-name))
25343 (error "Need a file name to be able to export.")))
25345 (message "Exporting...")
25346 (setq-default org-todo-line-regexp org-todo-line-regexp)
25347 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25348 (setq-default org-done-keywords org-done-keywords)
25349 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25350 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25351 ext-plist
25352 (org-infile-export-plist)))
25354 (style (plist-get opt-plist :style))
25355 (html-extension (plist-get opt-plist :html-extension))
25356 (link-validate (plist-get opt-plist :link-validation-function))
25357 valid thetoc have-headings first-heading-pos
25358 (odd org-odd-levels-only)
25359 (region-p (org-region-active-p))
25360 (subtree-p
25361 (when region-p
25362 (save-excursion
25363 (goto-char (region-beginning))
25364 (and (org-at-heading-p)
25365 (>= (org-end-of-subtree t t) (region-end))))))
25366 ;; The following two are dynamically scoped into other
25367 ;; routines below.
25368 (org-current-export-dir
25369 (or pub-dir (org-export-directory :html opt-plist)))
25370 (org-current-export-file buffer-file-name)
25371 (level 0) (line "") (origline "") txt todo
25372 (umax nil)
25373 (umax-toc nil)
25374 (filename (if to-buffer nil
25375 (expand-file-name
25376 (concat
25377 (file-name-sans-extension
25378 (or (and subtree-p
25379 (org-entry-get (region-beginning)
25380 "EXPORT_FILE_NAME" t))
25381 (file-name-nondirectory buffer-file-name)))
25382 "." html-extension)
25383 (file-name-as-directory
25384 (or pub-dir (org-export-directory :html opt-plist))))))
25385 (current-dir (if buffer-file-name
25386 (file-name-directory buffer-file-name)
25387 default-directory))
25388 (buffer (if to-buffer
25389 (cond
25390 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25391 (t (get-buffer-create to-buffer)))
25392 (find-file-noselect filename)))
25393 (org-levels-open (make-vector org-level-max nil))
25394 (date (plist-get opt-plist :date))
25395 (author (plist-get opt-plist :author))
25396 (title (or (and subtree-p (org-export-get-title-from-subtree))
25397 (plist-get opt-plist :title)
25398 (and (not
25399 (plist-get opt-plist :skip-before-1st-heading))
25400 (org-export-grab-title-from-buffer))
25401 (and buffer-file-name
25402 (file-name-sans-extension
25403 (file-name-nondirectory buffer-file-name)))
25404 "UNTITLED"))
25405 (html-table-tag (plist-get opt-plist :html-table-tag))
25406 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25407 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25408 (inquote nil)
25409 (infixed nil)
25410 (in-local-list nil)
25411 (local-list-num nil)
25412 (local-list-indent nil)
25413 (llt org-plain-list-ordered-item-terminator)
25414 (email (plist-get opt-plist :email))
25415 (language (plist-get opt-plist :language))
25416 (lang-words nil)
25417 (target-alist nil) tg
25418 (head-count 0) cnt
25419 (start 0)
25420 (coding-system (and (boundp 'buffer-file-coding-system)
25421 buffer-file-coding-system))
25422 (coding-system-for-write (or org-export-html-coding-system
25423 coding-system))
25424 (save-buffer-coding-system (or org-export-html-coding-system
25425 coding-system))
25426 (charset (and coding-system-for-write
25427 (fboundp 'coding-system-get)
25428 (coding-system-get coding-system-for-write
25429 'mime-charset)))
25430 (region
25431 (buffer-substring
25432 (if region-p (region-beginning) (point-min))
25433 (if region-p (region-end) (point-max))))
25434 (lines
25435 (org-split-string
25436 (org-cleaned-string-for-export
25437 region
25438 :emph-multiline t
25439 :for-html t
25440 :skip-before-1st-heading
25441 (plist-get opt-plist :skip-before-1st-heading)
25442 :drawers (plist-get opt-plist :drawers)
25443 :archived-trees
25444 (plist-get opt-plist :archived-trees)
25445 :add-text
25446 (plist-get opt-plist :text)
25447 :LaTeX-fragments
25448 (plist-get opt-plist :LaTeX-fragments))
25449 "[\r\n]"))
25450 table-open type
25451 table-buffer table-orig-buffer
25452 ind start-is-num starter didclose
25453 rpl path desc descp desc1 desc2 link
25456 (let ((inhibit-read-only t))
25457 (org-unmodified
25458 (remove-text-properties (point-min) (point-max)
25459 '(:org-license-to-kill t))))
25461 (message "Exporting...")
25463 (setq org-min-level (org-get-min-level lines))
25464 (setq org-last-level org-min-level)
25465 (org-init-section-numbers)
25467 (cond
25468 ((and date (string-match "%" date))
25469 (setq date (format-time-string date (current-time))))
25470 (date)
25471 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25473 ;; Get the language-dependent settings
25474 (setq lang-words (or (assoc language org-export-language-setup)
25475 (assoc "en" org-export-language-setup)))
25477 ;; Switch to the output buffer
25478 (set-buffer buffer)
25479 (let ((inhibit-read-only t)) (erase-buffer))
25480 (fundamental-mode)
25482 (and (fboundp 'set-buffer-file-coding-system)
25483 (set-buffer-file-coding-system coding-system-for-write))
25485 (let ((case-fold-search nil)
25486 (org-odd-levels-only odd))
25487 ;; create local variables for all options, to make sure all called
25488 ;; functions get the correct information
25489 (mapc (lambda (x)
25490 (set (make-local-variable (cdr x))
25491 (plist-get opt-plist (car x))))
25492 org-export-plist-vars)
25493 (setq umax (if arg (prefix-numeric-value arg)
25494 org-export-headline-levels))
25495 (setq umax-toc (if (integerp org-export-with-toc)
25496 (min org-export-with-toc umax)
25497 umax))
25498 (unless body-only
25499 ;; File header
25500 (insert (format
25501 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25502 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25503 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25504 lang=\"%s\" xml:lang=\"%s\">
25505 <head>
25506 <title>%s</title>
25507 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25508 <meta name=\"generator\" content=\"Org-mode\"/>
25509 <meta name=\"generated\" content=\"%s\"/>
25510 <meta name=\"author\" content=\"%s\"/>
25512 </head><body>
25514 language language (org-html-expand title)
25515 (or charset "iso-8859-1") date author style))
25517 (insert (or (plist-get opt-plist :preamble) ""))
25519 (when (plist-get opt-plist :auto-preamble)
25520 (if title (insert (format org-export-html-title-format
25521 (org-html-expand title))))))
25523 (if (and org-export-with-toc (not body-only))
25524 (progn
25525 (push (format "<h%d>%s</h%d>\n"
25526 org-export-html-toplevel-hlevel
25527 (nth 3 lang-words)
25528 org-export-html-toplevel-hlevel)
25529 thetoc)
25530 (push "<ul>\n<li>" thetoc)
25531 (setq lines
25532 (mapcar '(lambda (line)
25533 (if (string-match org-todo-line-regexp line)
25534 ;; This is a headline
25535 (progn
25536 (setq have-headings t)
25537 (setq level (- (match-end 1) (match-beginning 1))
25538 level (org-tr-level level)
25539 txt (save-match-data
25540 (org-html-expand
25541 (org-export-cleanup-toc-line
25542 (match-string 3 line))))
25543 todo
25544 (or (and org-export-mark-todo-in-toc
25545 (match-beginning 2)
25546 (not (member (match-string 2 line)
25547 org-done-keywords)))
25548 ; TODO, not DONE
25549 (and org-export-mark-todo-in-toc
25550 (= level umax-toc)
25551 (org-search-todo-below
25552 line lines level))))
25553 (if (string-match
25554 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25555 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25556 (if (string-match quote-re0 txt)
25557 (setq txt (replace-match "" t t txt)))
25558 (if org-export-with-section-numbers
25559 (setq txt (concat (org-section-number level)
25560 " " txt)))
25561 (if (<= level (max umax umax-toc))
25562 (setq head-count (+ head-count 1)))
25563 (if (<= level umax-toc)
25564 (progn
25565 (if (> level org-last-level)
25566 (progn
25567 (setq cnt (- level org-last-level))
25568 (while (>= (setq cnt (1- cnt)) 0)
25569 (push "\n<ul>\n<li>" thetoc))
25570 (push "\n" thetoc)))
25571 (if (< level org-last-level)
25572 (progn
25573 (setq cnt (- org-last-level level))
25574 (while (>= (setq cnt (1- cnt)) 0)
25575 (push "</li>\n</ul>" thetoc))
25576 (push "\n" thetoc)))
25577 ;; Check for targets
25578 (while (string-match org-target-regexp line)
25579 (setq tg (match-string 1 line)
25580 line (replace-match
25581 (concat "@<span class=\"target\">" tg "@</span> ")
25582 t t line))
25583 (push (cons (org-solidify-link-text tg)
25584 (format "sec-%d" head-count))
25585 target-alist))
25586 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25587 (setq txt (replace-match "" t t txt)))
25588 (push
25589 (format
25590 (if todo
25591 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25592 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25593 head-count txt) thetoc)
25595 (setq org-last-level level))
25597 line)
25598 lines))
25599 (while (> org-last-level (1- org-min-level))
25600 (setq org-last-level (1- org-last-level))
25601 (push "</li>\n</ul>\n" thetoc))
25602 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25604 (setq head-count 0)
25605 (org-init-section-numbers)
25607 (while (setq line (pop lines) origline line)
25608 (catch 'nextline
25610 ;; end of quote section?
25611 (when (and inquote (string-match "^\\*+ " line))
25612 (insert "</pre>\n")
25613 (setq inquote nil))
25614 ;; inside a quote section?
25615 (when inquote
25616 (insert (org-html-protect line) "\n")
25617 (throw 'nextline nil))
25619 ;; verbatim lines
25620 (when (and org-export-with-fixed-width
25621 (string-match "^[ \t]*:\\(.*\\)" line))
25622 (when (not infixed)
25623 (setq infixed t)
25624 (insert "<pre>\n"))
25625 (insert (org-html-protect (match-string 1 line)) "\n")
25626 (when (and lines
25627 (not (string-match "^[ \t]*\\(:.*\\)"
25628 (car lines))))
25629 (setq infixed nil)
25630 (insert "</pre>\n"))
25631 (throw 'nextline nil))
25633 ;; Protected HTML
25634 (when (get-text-property 0 'org-protected line)
25635 (let (par)
25636 (when (re-search-backward
25637 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25638 (setq par (match-string 1))
25639 (replace-match "\\2\n"))
25640 (insert line "\n")
25641 (while (and lines
25642 (or (= (length (car lines)) 0)
25643 (get-text-property 0 'org-protected (car lines))))
25644 (insert (pop lines) "\n"))
25645 (and par (insert "<p>\n")))
25646 (throw 'nextline nil))
25648 ;; Horizontal line
25649 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25650 (insert "\n<hr/>\n")
25651 (throw 'nextline nil))
25653 ;; make targets to anchors
25654 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25655 (cond
25656 ((match-end 2)
25657 (setq line (replace-match
25658 (concat "@<a name=\""
25659 (org-solidify-link-text (match-string 1 line))
25660 "\">\\nbsp@</a>")
25661 t t line)))
25662 ((and org-export-with-toc (equal (string-to-char line) ?*))
25663 (setq line (replace-match
25664 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25665 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25666 t t line)))
25668 (setq line (replace-match
25669 (concat "@<a name=\""
25670 (org-solidify-link-text (match-string 1 line))
25671 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25672 t t line)))))
25674 (setq line (org-html-handle-time-stamps line))
25676 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25677 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25678 ;; Also handle sub_superscripts and checkboxes
25679 (or (string-match org-table-hline-regexp line)
25680 (setq line (org-html-expand line)))
25682 ;; Format the links
25683 (setq start 0)
25684 (while (string-match org-bracket-link-analytic-regexp line start)
25685 (setq start (match-beginning 0))
25686 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25687 (setq path (match-string 3 line))
25688 (setq desc1 (if (match-end 5) (match-string 5 line))
25689 desc2 (if (match-end 2) (concat type ":" path) path)
25690 descp (and desc1 (not (equal desc1 desc2)))
25691 desc (or desc1 desc2))
25692 ;; Make an image out of the description if that is so wanted
25693 (when (and descp (org-file-image-p desc))
25694 (save-match-data
25695 (if (string-match "^file:" desc)
25696 (setq desc (substring desc (match-end 0)))))
25697 (setq desc (concat "<img src=\"" desc "\"/>")))
25698 ;; FIXME: do we need to unescape here somewhere?
25699 (cond
25700 ((equal type "internal")
25701 (setq rpl
25702 (concat
25703 "<a href=\"#"
25704 (org-solidify-link-text
25705 (save-match-data (org-link-unescape path)) target-alist)
25706 "\">" desc "</a>")))
25707 ((member type '("http" "https"))
25708 ;; standard URL, just check if we need to inline an image
25709 (if (and (or (eq t org-export-html-inline-images)
25710 (and org-export-html-inline-images (not descp)))
25711 (org-file-image-p path))
25712 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25713 (setq link (concat type ":" path))
25714 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25715 ((member type '("ftp" "mailto" "news"))
25716 ;; standard URL
25717 (setq link (concat type ":" path))
25718 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25719 ((string= type "file")
25720 ;; FILE link
25721 (let* ((filename path)
25722 (abs-p (file-name-absolute-p filename))
25723 thefile file-is-image-p search)
25724 (save-match-data
25725 (if (string-match "::\\(.*\\)" filename)
25726 (setq search (match-string 1 filename)
25727 filename (replace-match "" t nil filename)))
25728 (setq valid
25729 (if (functionp link-validate)
25730 (funcall link-validate filename current-dir)
25732 (setq file-is-image-p (org-file-image-p filename))
25733 (setq thefile (if abs-p (expand-file-name filename) filename))
25734 (when (and org-export-html-link-org-files-as-html
25735 (string-match "\\.org$" thefile))
25736 (setq thefile (concat (substring thefile 0
25737 (match-beginning 0))
25738 "." html-extension))
25739 (if (and search
25740 ;; make sure this is can be used as target search
25741 (not (string-match "^[0-9]*$" search))
25742 (not (string-match "^\\*" search))
25743 (not (string-match "^/.*/$" search)))
25744 (setq thefile (concat thefile "#"
25745 (org-solidify-link-text
25746 (org-link-unescape search)))))
25747 (when (string-match "^file:" desc)
25748 (setq desc (replace-match "" t t desc))
25749 (if (string-match "\\.org$" desc)
25750 (setq desc (replace-match "" t t desc))))))
25751 (setq rpl (if (and file-is-image-p
25752 (or (eq t org-export-html-inline-images)
25753 (and org-export-html-inline-images
25754 (not descp))))
25755 (concat "<img src=\"" thefile "\"/>")
25756 (concat "<a href=\"" thefile "\">" desc "</a>")))
25757 (if (not valid) (setq rpl desc))))
25758 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25759 (setq rpl (concat "<i>&lt;" type ":"
25760 (save-match-data (org-link-unescape path))
25761 "&gt;</i>"))))
25762 (setq line (replace-match rpl t t line)
25763 start (+ start (length rpl))))
25765 ;; TODO items
25766 (if (and (string-match org-todo-line-regexp line)
25767 (match-beginning 2))
25769 (setq line
25770 (concat (substring line 0 (match-beginning 2))
25771 "<span class=\""
25772 (if (member (match-string 2 line)
25773 org-done-keywords)
25774 "done" "todo")
25775 "\">" (match-string 2 line)
25776 "</span>" (substring line (match-end 2)))))
25778 ;; Does this contain a reference to a footnote?
25779 (when org-export-with-footnotes
25780 (setq start 0)
25781 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25782 (if (get-text-property (match-beginning 2) 'org-protected line)
25783 (setq start (match-end 2))
25784 (let ((n (match-string 2 line)))
25785 (setq line
25786 (replace-match
25787 (format
25788 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25789 (match-string 1 line) n n n)
25790 t t line))))))
25792 (cond
25793 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25794 ;; This is a headline
25795 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25796 txt (match-string 2 line))
25797 (if (string-match quote-re0 txt)
25798 (setq txt (replace-match "" t t txt)))
25799 (if (<= level (max umax umax-toc))
25800 (setq head-count (+ head-count 1)))
25801 (when in-local-list
25802 ;; Close any local lists before inserting a new header line
25803 (while local-list-num
25804 (org-close-li)
25805 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25806 (pop local-list-num))
25807 (setq local-list-indent nil
25808 in-local-list nil))
25809 (setq first-heading-pos (or first-heading-pos (point)))
25810 (org-html-level-start level txt umax
25811 (and org-export-with-toc (<= level umax))
25812 head-count)
25813 ;; QUOTES
25814 (when (string-match quote-re line)
25815 (insert "<pre>")
25816 (setq inquote t)))
25818 ((and org-export-with-tables
25819 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25820 (if (not table-open)
25821 ;; New table starts
25822 (setq table-open t table-buffer nil table-orig-buffer nil))
25823 ;; Accumulate lines
25824 (setq table-buffer (cons line table-buffer)
25825 table-orig-buffer (cons origline table-orig-buffer))
25826 (when (or (not lines)
25827 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25828 (car lines))))
25829 (setq table-open nil
25830 table-buffer (nreverse table-buffer)
25831 table-orig-buffer (nreverse table-orig-buffer))
25832 (org-close-par-maybe)
25833 (insert (org-format-table-html table-buffer table-orig-buffer))))
25835 ;; Normal lines
25836 (when (string-match
25837 (cond
25838 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25839 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25840 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25841 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25842 line)
25843 (setq ind (org-get-string-indentation line)
25844 start-is-num (match-beginning 4)
25845 starter (if (match-beginning 2)
25846 (substring (match-string 2 line) 0 -1))
25847 line (substring line (match-beginning 5)))
25848 (unless (string-match "[^ \t]" line)
25849 ;; empty line. Pretend indentation is large.
25850 (setq ind (if org-empty-line-terminates-plain-lists
25852 (1+ (or (car local-list-indent) 1)))))
25853 (setq didclose nil)
25854 (while (and in-local-list
25855 (or (and (= ind (car local-list-indent))
25856 (not starter))
25857 (< ind (car local-list-indent))))
25858 (setq didclose t)
25859 (org-close-li)
25860 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25861 (pop local-list-num) (pop local-list-indent)
25862 (setq in-local-list local-list-indent))
25863 (cond
25864 ((and starter
25865 (or (not in-local-list)
25866 (> ind (car local-list-indent))))
25867 ;; Start new (level of) list
25868 (org-close-par-maybe)
25869 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
25870 (push start-is-num local-list-num)
25871 (push ind local-list-indent)
25872 (setq in-local-list t))
25873 (starter
25874 ;; continue current list
25875 (org-close-li)
25876 (insert "<li>\n"))
25877 (didclose
25878 ;; we did close a list, normal text follows: need <p>
25879 (org-open-par)))
25880 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
25881 (setq line
25882 (replace-match
25883 (if (equal (match-string 1 line) "X")
25884 "<b>[X]</b>"
25885 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
25886 t t line))))
25888 ;; Empty lines start a new paragraph. If hand-formatted lists
25889 ;; are not fully interpreted, lines starting with "-", "+", "*"
25890 ;; also start a new paragraph.
25891 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
25893 ;; Is this the start of a footnote?
25894 (when org-export-with-footnotes
25895 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
25896 (org-close-par-maybe)
25897 (let ((n (match-string 1 line)))
25898 (setq line (replace-match
25899 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
25901 ;; Check if the line break needs to be conserved
25902 (cond
25903 ((string-match "\\\\\\\\[ \t]*$" line)
25904 (setq line (replace-match "<br/>" t t line)))
25905 (org-export-preserve-breaks
25906 (setq line (concat line "<br/>"))))
25908 (insert line "\n")))))
25910 ;; Properly close all local lists and other lists
25911 (when inquote (insert "</pre>\n"))
25912 (when in-local-list
25913 ;; Close any local lists before inserting a new header line
25914 (while local-list-num
25915 (org-close-li)
25916 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
25917 (pop local-list-num))
25918 (setq local-list-indent nil
25919 in-local-list nil))
25920 (org-html-level-start 1 nil umax
25921 (and org-export-with-toc (<= level umax))
25922 head-count)
25924 (unless body-only
25925 (when (plist-get opt-plist :auto-postamble)
25926 (insert "<div id=\"postamble\">")
25927 (when (and org-export-author-info author)
25928 (insert "<p class=\"author\"> "
25929 (nth 1 lang-words) ": " author "\n")
25930 (when email
25931 (if (listp (split-string email ",+ *"))
25932 (mapc (lambda(e)
25933 (insert "<a href=\"mailto:" e "\">&lt;"
25934 e "&gt;</a>\n"))
25935 (split-string email ",+ *"))
25936 (insert "<a href=\"mailto:" email "\">&lt;"
25937 email "&gt;</a>\n")))
25938 (insert "</p>\n"))
25939 (when (and date org-export-time-stamp-file)
25940 (insert "<p class=\"date\"> "
25941 (nth 2 lang-words) ": "
25942 date "</p>\n"))
25943 (insert "</div>"))
25945 (if org-export-html-with-timestamp
25946 (insert org-export-html-html-helper-timestamp))
25947 (insert (or (plist-get opt-plist :postamble) ""))
25948 (insert "</body>\n</html>\n"))
25950 (normal-mode)
25951 (if (eq major-mode default-major-mode) (html-mode))
25953 ;; insert the table of contents
25954 (goto-char (point-min))
25955 (when thetoc
25956 (if (or (re-search-forward
25957 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
25958 (re-search-forward
25959 "\\[TABLE-OF-CONTENTS\\]" nil t))
25960 (progn
25961 (goto-char (match-beginning 0))
25962 (replace-match ""))
25963 (goto-char first-heading-pos)
25964 (when (looking-at "\\s-*</p>")
25965 (goto-char (match-end 0))
25966 (insert "\n")))
25967 (insert "<div id=\"table-of-contents\">\n")
25968 (mapc 'insert thetoc)
25969 (insert "</div>\n"))
25970 ;; remove empty paragraphs and lists
25971 (goto-char (point-min))
25972 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
25973 (replace-match ""))
25974 (goto-char (point-min))
25975 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
25976 (replace-match ""))
25977 (goto-char (point-min))
25978 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
25979 (replace-match ""))
25980 ;; Convert whitespace place holders
25981 (goto-char (point-min))
25982 (let (beg end n)
25983 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25984 (setq n (get-text-property beg 'org-whitespace)
25985 end (next-single-property-change beg 'org-whitespace))
25986 (goto-char beg)
25987 (delete-region beg end)
25988 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
25989 (make-string n ?x)))))
25991 (or to-buffer (progn (save-buffer) (kill-buffer (current-buffer))))
25992 (goto-char (point-min))
25993 (message "Exporting... done")
25994 (if (eq to-buffer 'string)
25995 (prog1 (buffer-substring (point-min) (point-max))
25996 (kill-buffer (current-buffer)))
25997 (current-buffer)))))
25999 (defvar org-table-colgroup-info nil)
26000 (defun org-format-table-ascii (lines)
26001 "Format a table for ascii export."
26002 (if (stringp lines)
26003 (setq lines (org-split-string lines "\n")))
26004 (if (not (string-match "^[ \t]*|" (car lines)))
26005 ;; Table made by table.el - test for spanning
26006 lines
26008 ;; A normal org table
26009 ;; Get rid of hlines at beginning and end
26010 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26011 (setq lines (nreverse lines))
26012 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26013 (setq lines (nreverse lines))
26014 (when org-export-table-remove-special-lines
26015 ;; Check if the table has a marking column. If yes remove the
26016 ;; column and the special lines
26017 (setq lines (org-table-clean-before-export lines)))
26018 ;; Get rid of the vertical lines except for grouping
26019 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26020 rtn line vl1 start)
26021 (while (setq line (pop lines))
26022 (if (string-match org-table-hline-regexp line)
26023 (and (string-match "|\\(.*\\)|" line)
26024 (setq line (replace-match " \\1" t nil line)))
26025 (setq start 0 vl1 vl)
26026 (while (string-match "|" line start)
26027 (setq start (match-end 0))
26028 (or (pop vl1) (setq line (replace-match " " t t line)))))
26029 (push line rtn))
26030 (nreverse rtn))))
26032 (defun org-colgroup-info-to-vline-list (info)
26033 (let (vl new last)
26034 (while info
26035 (setq last new new (pop info))
26036 (if (or (memq last '(:end :startend))
26037 (memq new '(:start :startend)))
26038 (push t vl)
26039 (push nil vl)))
26040 (setq vl (nreverse vl))
26041 (and vl (setcar vl nil))
26042 vl))
26044 (defun org-format-table-html (lines olines)
26045 "Find out which HTML converter to use and return the HTML code."
26046 (if (stringp lines)
26047 (setq lines (org-split-string lines "\n")))
26048 (if (string-match "^[ \t]*|" (car lines))
26049 ;; A normal org table
26050 (org-format-org-table-html lines)
26051 ;; Table made by table.el - test for spanning
26052 (let* ((hlines (delq nil (mapcar
26053 (lambda (x)
26054 (if (string-match "^[ \t]*\\+-" x) x
26055 nil))
26056 lines)))
26057 (first (car hlines))
26058 (ll (and (string-match "\\S-+" first)
26059 (match-string 0 first)))
26060 (re (concat "^[ \t]*" (regexp-quote ll)))
26061 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26062 hlines))))
26063 (if (and (not spanning)
26064 (not org-export-prefer-native-exporter-for-tables))
26065 ;; We can use my own converter with HTML conversions
26066 (org-format-table-table-html lines)
26067 ;; Need to use the code generator in table.el, with the original text.
26068 (org-format-table-table-html-using-table-generate-source olines)))))
26070 (defun org-format-org-table-html (lines &optional splice)
26071 "Format a table into HTML."
26072 ;; Get rid of hlines at beginning and end
26073 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26074 (setq lines (nreverse lines))
26075 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26076 (setq lines (nreverse lines))
26077 (when org-export-table-remove-special-lines
26078 ;; Check if the table has a marking column. If yes remove the
26079 ;; column and the special lines
26080 (setq lines (org-table-clean-before-export lines)))
26082 (let ((head (and org-export-highlight-first-table-line
26083 (delq nil (mapcar
26084 (lambda (x) (string-match "^[ \t]*|-" x))
26085 (cdr lines)))))
26086 (nlines 0) fnum i
26087 tbopen line fields html gr colgropen)
26088 (if splice (setq head nil))
26089 (unless splice (push (if head "<thead>" "<tbody>") html))
26090 (setq tbopen t)
26091 (while (setq line (pop lines))
26092 (catch 'next-line
26093 (if (string-match "^[ \t]*|-" line)
26094 (progn
26095 (unless splice
26096 (push (if head "</thead>" "</tbody>") html)
26097 (if lines (push "<tbody>" html) (setq tbopen nil)))
26098 (setq head nil) ;; head ends here, first time around
26099 ;; ignore this line
26100 (throw 'next-line t)))
26101 ;; Break the line into fields
26102 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26103 (unless fnum (setq fnum (make-vector (length fields) 0)))
26104 (setq nlines (1+ nlines) i -1)
26105 (push (concat "<tr>"
26106 (mapconcat
26107 (lambda (x)
26108 (setq i (1+ i))
26109 (if (and (< i nlines)
26110 (string-match org-table-number-regexp x))
26111 (incf (aref fnum i)))
26112 (if head
26113 (concat (car org-export-table-header-tags) x
26114 (cdr org-export-table-header-tags))
26115 (concat (car org-export-table-data-tags) x
26116 (cdr org-export-table-data-tags))))
26117 fields "")
26118 "</tr>")
26119 html)))
26120 (unless splice (if tbopen (push "</tbody>" html)))
26121 (unless splice (push "</table>\n" html))
26122 (setq html (nreverse html))
26123 (unless splice
26124 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26125 (push (mapconcat
26126 (lambda (x)
26127 (setq gr (pop org-table-colgroup-info))
26128 (format "%s<col align=\"%s\"></col>%s"
26129 (if (memq gr '(:start :startend))
26130 (prog1
26131 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26132 (setq colgropen t))
26134 (if (> (/ (float x) nlines) org-table-number-fraction)
26135 "right" "left")
26136 (if (memq gr '(:end :startend))
26137 (progn (setq colgropen nil) "</colgroup>")
26138 "")))
26139 fnum "")
26140 html)
26141 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26142 (push html-table-tag html))
26143 (concat (mapconcat 'identity html "\n") "\n")))
26145 (defun org-table-clean-before-export (lines)
26146 "Check if the table has a marking column.
26147 If yes remove the column and the special lines."
26148 (setq org-table-colgroup-info nil)
26149 (if (memq nil
26150 (mapcar
26151 (lambda (x) (or (string-match "^[ \t]*|-" x)
26152 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26153 lines))
26154 (progn
26155 (setq org-table-clean-did-remove-column nil)
26156 (delq nil
26157 (mapcar
26158 (lambda (x)
26159 (cond
26160 ((string-match "^[ \t]*| */ *|" x)
26161 (setq org-table-colgroup-info
26162 (mapcar (lambda (x)
26163 (cond ((member x '("<" "&lt;")) :start)
26164 ((member x '(">" "&gt;")) :end)
26165 ((member x '("<>" "&lt;&gt;")) :startend)
26166 (t nil)))
26167 (org-split-string x "[ \t]*|[ \t]*")))
26168 nil)
26169 (t x)))
26170 lines)))
26171 (setq org-table-clean-did-remove-column t)
26172 (delq nil
26173 (mapcar
26174 (lambda (x)
26175 (cond
26176 ((string-match "^[ \t]*| */ *|" x)
26177 (setq org-table-colgroup-info
26178 (mapcar (lambda (x)
26179 (cond ((member x '("<" "&lt;")) :start)
26180 ((member x '(">" "&gt;")) :end)
26181 ((member x '("<>" "&lt;&gt;")) :startend)
26182 (t nil)))
26183 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26184 nil)
26185 ((string-match "^[ \t]*| *[!_^/] *|" x)
26186 nil) ; ignore this line
26187 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26188 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26189 ;; remove the first column
26190 (replace-match "\\1|" t nil x))))
26191 lines))))
26193 (defun org-format-table-table-html (lines)
26194 "Format a table generated by table.el into HTML.
26195 This conversion does *not* use `table-generate-source' from table.el.
26196 This has the advantage that Org-mode's HTML conversions can be used.
26197 But it has the disadvantage, that no cell- or row-spanning is allowed."
26198 (let (line field-buffer
26199 (head org-export-highlight-first-table-line)
26200 fields html empty)
26201 (setq html (concat html-table-tag "\n"))
26202 (while (setq line (pop lines))
26203 (setq empty "&nbsp;")
26204 (catch 'next-line
26205 (if (string-match "^[ \t]*\\+-" line)
26206 (progn
26207 (if field-buffer
26208 (progn
26209 (setq
26210 html
26211 (concat
26212 html
26213 "<tr>"
26214 (mapconcat
26215 (lambda (x)
26216 (if (equal x "") (setq x empty))
26217 (if head
26218 (concat (car org-export-table-header-tags) x
26219 (cdr org-export-table-header-tags))
26220 (concat (car org-export-table-data-tags) x
26221 (cdr org-export-table-data-tags))))
26222 field-buffer "\n")
26223 "</tr>\n"))
26224 (setq head nil)
26225 (setq field-buffer nil)))
26226 ;; Ignore this line
26227 (throw 'next-line t)))
26228 ;; Break the line into fields and store the fields
26229 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26230 (if field-buffer
26231 (setq field-buffer (mapcar
26232 (lambda (x)
26233 (concat x "<br/>" (pop fields)))
26234 field-buffer))
26235 (setq field-buffer fields))))
26236 (setq html (concat html "</table>\n"))
26237 html))
26239 (defun org-format-table-table-html-using-table-generate-source (lines)
26240 "Format a table into html, using `table-generate-source' from table.el.
26241 This has the advantage that cell- or row-spanning is allowed.
26242 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26243 (require 'table)
26244 (with-current-buffer (get-buffer-create " org-tmp1 ")
26245 (erase-buffer)
26246 (insert (mapconcat 'identity lines "\n"))
26247 (goto-char (point-min))
26248 (if (not (re-search-forward "|[^+]" nil t))
26249 (error "Error processing table"))
26250 (table-recognize-table)
26251 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26252 (table-generate-source 'html " org-tmp2 ")
26253 (set-buffer " org-tmp2 ")
26254 (buffer-substring (point-min) (point-max))))
26256 (defun org-html-handle-time-stamps (s)
26257 "Format time stamps in string S, or remove them."
26258 (catch 'exit
26259 (let (r b)
26260 (while (string-match org-maybe-keyword-time-regexp s)
26261 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26262 ;; never export CLOCK
26263 (throw 'exit ""))
26264 (or b (setq b (substring s 0 (match-beginning 0))))
26265 (if (not org-export-with-timestamps)
26266 (setq r (concat r (substring s 0 (match-beginning 0)))
26267 s (substring s (match-end 0)))
26268 (setq r (concat
26269 r (substring s 0 (match-beginning 0))
26270 (if (match-end 1)
26271 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26272 (match-string 1 s)))
26273 (format " @<span class=\"timestamp\">%s@</span>"
26274 (substring
26275 (org-translate-time (match-string 3 s)) 1 -1)))
26276 s (substring s (match-end 0)))))
26277 ;; Line break if line started and ended with time stamp stuff
26278 (if (not r)
26280 (setq r (concat r s))
26281 (unless (string-match "\\S-" (concat b s))
26282 (setq r (concat r "@<br/>")))
26283 r))))
26285 (defun org-html-protect (s)
26286 ;; convert & to &amp;, < to &lt; and > to &gt;
26287 (let ((start 0))
26288 (while (string-match "&" s start)
26289 (setq s (replace-match "&amp;" t t s)
26290 start (1+ (match-beginning 0))))
26291 (while (string-match "<" s)
26292 (setq s (replace-match "&lt;" t t s)))
26293 (while (string-match ">" s)
26294 (setq s (replace-match "&gt;" t t s))))
26297 (defun org-export-cleanup-toc-line (s)
26298 "Remove tags and time staps from lines going into the toc."
26299 (when (memq org-export-with-tags '(not-in-toc nil))
26300 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26301 (setq s (replace-match "" t t s))))
26302 (when org-export-remove-timestamps-from-toc
26303 (while (string-match org-maybe-keyword-time-regexp s)
26304 (setq s (replace-match "" t t s))))
26305 (while (string-match org-bracket-link-regexp s)
26306 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26307 t t s)))
26310 (defun org-html-expand (string)
26311 "Prepare STRING for HTML export. Applies all active conversions.
26312 If there are links in the string, don't modify these."
26313 (let* ((re (concat org-bracket-link-regexp "\\|"
26314 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26315 m s l res)
26316 (while (setq m (string-match re string))
26317 (setq s (substring string 0 m)
26318 l (match-string 0 string)
26319 string (substring string (match-end 0)))
26320 (push (org-html-do-expand s) res)
26321 (push l res))
26322 (push (org-html-do-expand string) res)
26323 (apply 'concat (nreverse res))))
26325 (defun org-html-do-expand (s)
26326 "Apply all active conversions to translate special ASCII to HTML."
26327 (setq s (org-html-protect s))
26328 (if org-export-html-expand
26329 (let ((start 0))
26330 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26331 (setq s (replace-match "<\\1>" t nil s)))))
26332 (if org-export-with-emphasize
26333 (setq s (org-export-html-convert-emphasize s)))
26334 (if org-export-with-special-strings
26335 (setq s (org-export-html-convert-special-strings s)))
26336 (if org-export-with-sub-superscripts
26337 (setq s (org-export-html-convert-sub-super s)))
26338 (if org-export-with-TeX-macros
26339 (let ((start 0) wd ass)
26340 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26341 (if (get-text-property (match-beginning 0) 'org-protected s)
26342 (setq start (match-end 0))
26343 (setq wd (match-string 1 s))
26344 (if (setq ass (assoc wd org-html-entities))
26345 (setq s (replace-match (or (cdr ass)
26346 (concat "&" (car ass) ";"))
26347 t t s))
26348 (setq start (+ start (length wd))))))))
26351 (defun org-create-multibrace-regexp (left right n)
26352 "Create a regular expression which will match a balanced sexp.
26353 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26354 as single character strings.
26355 The regexp returned will match the entire expression including the
26356 delimiters. It will also define a single group which contains the
26357 match except for the outermost delimiters. The maximum depth of
26358 stacked delimiters is N. Escaping delimiters is not possible."
26359 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26360 (or "\\|")
26361 (re nothing)
26362 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26363 (while (> n 1)
26364 (setq n (1- n)
26365 re (concat re or next)
26366 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26367 (concat left "\\(" re "\\)" right)))
26369 (defvar org-match-substring-regexp
26370 (concat
26371 "\\([^\\]\\)\\([_^]\\)\\("
26372 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26373 "\\|"
26374 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26375 "\\|"
26376 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26377 "The regular expression matching a sub- or superscript.")
26379 (defvar org-match-substring-with-braces-regexp
26380 (concat
26381 "\\([^\\]\\)\\([_^]\\)\\("
26382 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26383 "\\)")
26384 "The regular expression matching a sub- or superscript, forcing braces.")
26386 (defconst org-export-html-special-string-regexps
26387 '(("\\\\-" . "&shy;")
26388 ("---\\([^-]\\)" . "&mdash;\\1")
26389 ("--\\([^-]\\)" . "&ndash;\\1")
26390 ("\\.\\.\\." . "&hellip;"))
26391 "Regular expressions for special string conversion.")
26393 (defun org-export-html-convert-special-strings (string)
26394 "Convert special characters in STRING to HTML."
26395 (let ((all org-export-html-special-string-regexps)
26396 e a re rpl start)
26397 (while (setq a (pop all))
26398 (setq re (car a) rpl (cdr a) start 0)
26399 (while (string-match re string start)
26400 (if (get-text-property (match-beginning 0) 'org-protected string)
26401 (setq start (match-end 0))
26402 (setq string (replace-match rpl t nil string)))))
26403 string))
26405 (defun org-export-html-convert-sub-super (string)
26406 "Convert sub- and superscripts in STRING to HTML."
26407 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26408 (while (string-match org-match-substring-regexp string s)
26409 (cond
26410 ((and requireb (match-end 8)) (setq s (match-end 2)))
26411 ((get-text-property (match-beginning 2) 'org-protected string)
26412 (setq s (match-end 2)))
26414 (setq s (match-end 1)
26415 key (if (string= (match-string 2 string) "_") "sub" "sup")
26416 c (or (match-string 8 string)
26417 (match-string 6 string)
26418 (match-string 5 string))
26419 string (replace-match
26420 (concat (match-string 1 string)
26421 "<" key ">" c "</" key ">")
26422 t t string)))))
26423 (while (string-match "\\\\\\([_^]\\)" string)
26424 (setq string (replace-match (match-string 1 string) t t string)))
26425 string))
26427 (defun org-export-html-convert-emphasize (string)
26428 "Apply emphasis."
26429 (let ((s 0) rpl)
26430 (while (string-match org-emph-re string s)
26431 (if (not (equal
26432 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26433 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26434 (setq s (match-beginning 0)
26436 (concat
26437 (match-string 1 string)
26438 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26439 (match-string 4 string)
26440 (nth 3 (assoc (match-string 3 string)
26441 org-emphasis-alist))
26442 (match-string 5 string))
26443 string (replace-match rpl t t string)
26444 s (+ s (- (length rpl) 2)))
26445 (setq s (1+ s))))
26446 string))
26448 (defvar org-par-open nil)
26449 (defun org-open-par ()
26450 "Insert <p>, but first close previous paragraph if any."
26451 (org-close-par-maybe)
26452 (insert "\n<p>")
26453 (setq org-par-open t))
26454 (defun org-close-par-maybe ()
26455 "Close paragraph if there is one open."
26456 (when org-par-open
26457 (insert "</p>")
26458 (setq org-par-open nil)))
26459 (defun org-close-li ()
26460 "Close <li> if necessary."
26461 (org-close-par-maybe)
26462 (insert "</li>\n"))
26464 (defvar body-only) ; dynamically scoped into this.
26465 (defun org-html-level-start (level title umax with-toc head-count)
26466 "Insert a new level in HTML export.
26467 When TITLE is nil, just close all open levels."
26468 (org-close-par-maybe)
26469 (let ((l org-level-max))
26470 (while (>= l level)
26471 (if (aref org-levels-open (1- l))
26472 (progn
26473 (org-html-level-close l umax)
26474 (aset org-levels-open (1- l) nil)))
26475 (setq l (1- l)))
26476 (when title
26477 ;; If title is nil, this means this function is called to close
26478 ;; all levels, so the rest is done only if title is given
26479 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26480 (setq title (replace-match
26481 (if org-export-with-tags
26482 (save-match-data
26483 (concat
26484 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26485 (mapconcat 'identity (org-split-string
26486 (match-string 1 title) ":")
26487 "&nbsp;")
26488 "</span>"))
26490 t t title)))
26491 (if (> level umax)
26492 (progn
26493 (if (aref org-levels-open (1- level))
26494 (progn
26495 (org-close-li)
26496 (insert "<li>" title "<br/>\n"))
26497 (aset org-levels-open (1- level) t)
26498 (org-close-par-maybe)
26499 (insert "<ul>\n<li>" title "<br/>\n")))
26500 (aset org-levels-open (1- level) t)
26501 (if (and org-export-with-section-numbers (not body-only))
26502 (setq title (concat (org-section-number level) " " title)))
26503 (setq level (+ level org-export-html-toplevel-hlevel -1))
26504 (if with-toc
26505 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26506 level level head-count title level))
26507 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26508 (org-open-par)))))
26510 (defun org-html-level-close (level max-outline-level)
26511 "Terminate one level in HTML export."
26512 (if (<= level max-outline-level)
26513 (insert "</div>\n")
26514 (org-close-li)
26515 (insert "</ul>\n")))
26517 ;;; iCalendar export
26519 ;;;###autoload
26520 (defun org-export-icalendar-this-file ()
26521 "Export current file as an iCalendar file.
26522 The iCalendar file will be located in the same directory as the Org-mode
26523 file, but with extension `.ics'."
26524 (interactive)
26525 (org-export-icalendar nil buffer-file-name))
26527 ;;;###autoload
26528 (defun org-export-icalendar-all-agenda-files ()
26529 "Export all files in `org-agenda-files' to iCalendar .ics files.
26530 Each iCalendar file will be located in the same directory as the Org-mode
26531 file, but with extension `.ics'."
26532 (interactive)
26533 (apply 'org-export-icalendar nil (org-agenda-files t)))
26535 ;;;###autoload
26536 (defun org-export-icalendar-combine-agenda-files ()
26537 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26538 The file is stored under the name `org-combined-agenda-icalendar-file'."
26539 (interactive)
26540 (apply 'org-export-icalendar t (org-agenda-files t)))
26542 (defun org-export-icalendar (combine &rest files)
26543 "Create iCalendar files for all elements of FILES.
26544 If COMBINE is non-nil, combine all calendar entries into a single large
26545 file and store it under the name `org-combined-agenda-icalendar-file'."
26546 (save-excursion
26547 (org-prepare-agenda-buffers files)
26548 (let* ((dir (org-export-directory
26549 :ical (list :publishing-directory
26550 org-export-publishing-directory)))
26551 file ical-file ical-buffer category started org-agenda-new-buffers)
26553 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26554 (when combine
26555 (setq ical-file
26556 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26557 org-combined-agenda-icalendar-file
26558 (expand-file-name org-combined-agenda-icalendar-file dir))
26559 ical-buffer (org-get-agenda-file-buffer ical-file))
26560 (set-buffer ical-buffer) (erase-buffer))
26561 (while (setq file (pop files))
26562 (catch 'nextfile
26563 (org-check-agenda-file file)
26564 (set-buffer (org-get-agenda-file-buffer file))
26565 (unless combine
26566 (setq ical-file (concat (file-name-as-directory dir)
26567 (file-name-sans-extension
26568 (file-name-nondirectory buffer-file-name))
26569 ".ics"))
26570 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26571 (with-current-buffer ical-buffer (erase-buffer)))
26572 (setq category (or org-category
26573 (file-name-sans-extension
26574 (file-name-nondirectory buffer-file-name))))
26575 (if (symbolp category) (setq category (symbol-name category)))
26576 (let ((standard-output ical-buffer))
26577 (if combine
26578 (and (not started) (setq started t)
26579 (org-start-icalendar-file org-icalendar-combined-name))
26580 (org-start-icalendar-file category))
26581 (org-print-icalendar-entries combine)
26582 (when (or (and combine (not files)) (not combine))
26583 (org-finish-icalendar-file)
26584 (set-buffer ical-buffer)
26585 (save-buffer)
26586 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26587 (org-release-buffers org-agenda-new-buffers))))
26589 (defvar org-after-save-iCalendar-file-hook nil
26590 "Hook run after an iCalendar file has been saved.
26591 The iCalendar buffer is still current when this hook is run.
26592 A good way to use this is to tell a desktop calenndar application to re-read
26593 the iCalendar file.")
26595 (defun org-print-icalendar-entries (&optional combine)
26596 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26597 When COMBINE is non nil, add the category to each line."
26598 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26599 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26600 (dts (org-ical-ts-to-string
26601 (format-time-string (cdr org-time-stamp-formats) (current-time))
26602 "DTSTART"))
26603 hd ts ts2 state status (inc t) pos b sexp rrule
26604 scheduledp deadlinep tmp pri category entry location summary desc
26605 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26606 (org-refresh-category-properties)
26607 (save-excursion
26608 (goto-char (point-min))
26609 (while (re-search-forward re1 nil t)
26610 (catch :skip
26611 (org-agenda-skip)
26612 (setq pos (match-beginning 0)
26613 ts (match-string 0)
26614 inc t
26615 hd (org-get-heading)
26616 summary (org-icalendar-cleanup-string
26617 (org-entry-get nil "SUMMARY"))
26618 desc (org-icalendar-cleanup-string
26619 (or (org-entry-get nil "DESCRIPTION")
26620 (and org-icalendar-include-body (org-get-entry)))
26621 t org-icalendar-include-body)
26622 location (org-icalendar-cleanup-string
26623 (org-entry-get nil "LOCATION"))
26624 category (org-get-category))
26625 (if (looking-at re2)
26626 (progn
26627 (goto-char (match-end 0))
26628 (setq ts2 (match-string 1) inc nil))
26629 (setq tmp (buffer-substring (max (point-min)
26630 (- pos org-ds-keyword-length))
26631 pos)
26632 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26633 (progn
26634 (setq inc nil)
26635 (replace-match "\\1" t nil ts))
26637 deadlinep (string-match org-deadline-regexp tmp)
26638 scheduledp (string-match org-scheduled-regexp tmp)
26639 ;; donep (org-entry-is-done-p)
26641 (if (or (string-match org-tr-regexp hd)
26642 (string-match org-ts-regexp hd))
26643 (setq hd (replace-match "" t t hd)))
26644 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26645 (setq rrule
26646 (concat "\nRRULE:FREQ="
26647 (cdr (assoc
26648 (match-string 2 ts)
26649 '(("d" . "DAILY")("w" . "WEEKLY")
26650 ("m" . "MONTHLY")("y" . "YEARLY"))))
26651 ";INTERVAL=" (match-string 1 ts)))
26652 (setq rrule ""))
26653 (setq summary (or summary hd))
26654 (if (string-match org-bracket-link-regexp summary)
26655 (setq summary
26656 (replace-match (if (match-end 3)
26657 (match-string 3 summary)
26658 (match-string 1 summary))
26659 t t summary)))
26660 (if deadlinep (setq summary (concat "DL: " summary)))
26661 (if scheduledp (setq summary (concat "S: " summary)))
26662 (if (string-match "\\`<%%" ts)
26663 (with-current-buffer sexp-buffer
26664 (insert (substring ts 1 -1) " " summary "\n"))
26665 (princ (format "BEGIN:VEVENT
26667 %s%s
26668 SUMMARY:%s%s%s
26669 CATEGORIES:%s
26670 END:VEVENT\n"
26671 (org-ical-ts-to-string ts "DTSTART")
26672 (org-ical-ts-to-string ts2 "DTEND" inc)
26673 rrule summary
26674 (if (and desc (string-match "\\S-" desc))
26675 (concat "\nDESCRIPTION: " desc) "")
26676 (if (and location (string-match "\\S-" location))
26677 (concat "\nLOCATION: " location) "")
26678 category)))))
26680 (when (and org-icalendar-include-sexps
26681 (condition-case nil (require 'icalendar) (error nil))
26682 (fboundp 'icalendar-export-region))
26683 ;; Get all the literal sexps
26684 (goto-char (point-min))
26685 (while (re-search-forward "^&?%%(" nil t)
26686 (catch :skip
26687 (org-agenda-skip)
26688 (setq b (match-beginning 0))
26689 (goto-char (1- (match-end 0)))
26690 (forward-sexp 1)
26691 (end-of-line 1)
26692 (setq sexp (buffer-substring b (point)))
26693 (with-current-buffer sexp-buffer
26694 (insert sexp "\n"))
26695 (princ (org-diary-to-ical-string sexp-buffer)))))
26697 (when org-icalendar-include-todo
26698 (goto-char (point-min))
26699 (while (re-search-forward org-todo-line-regexp nil t)
26700 (catch :skip
26701 (org-agenda-skip)
26702 (setq state (match-string 2))
26703 (setq status (if (member state org-done-keywords)
26704 "COMPLETED" "NEEDS-ACTION"))
26705 (when (and state
26706 (or (not (member state org-done-keywords))
26707 (eq org-icalendar-include-todo 'all))
26708 (not (member org-archive-tag (org-get-tags-at)))
26710 (setq hd (match-string 3)
26711 summary (org-icalendar-cleanup-string
26712 (org-entry-get nil "SUMMARY"))
26713 desc (org-icalendar-cleanup-string
26714 (or (org-entry-get nil "DESCRIPTION")
26715 (and org-icalendar-include-body (org-get-entry)))
26716 t org-icalendar-include-body)
26717 location (org-icalendar-cleanup-string
26718 (org-entry-get nil "LOCATION")))
26719 (if (string-match org-bracket-link-regexp hd)
26720 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26721 (match-string 1 hd))
26722 t t hd)))
26723 (if (string-match org-priority-regexp hd)
26724 (setq pri (string-to-char (match-string 2 hd))
26725 hd (concat (substring hd 0 (match-beginning 1))
26726 (substring hd (match-end 1))))
26727 (setq pri org-default-priority))
26728 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26729 (- org-lowest-priority org-highest-priority))))))
26731 (princ (format "BEGIN:VTODO
26733 SUMMARY:%s%s%s
26734 CATEGORIES:%s
26735 SEQUENCE:1
26736 PRIORITY:%d
26737 STATUS:%s
26738 END:VTODO\n"
26740 (or summary hd)
26741 (if (and location (string-match "\\S-" location))
26742 (concat "\nLOCATION: " location) "")
26743 (if (and desc (string-match "\\S-" desc))
26744 (concat "\nDESCRIPTION: " desc) "")
26745 category pri status)))))))))
26747 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26748 "Take out stuff and quote what needs to be quoted.
26749 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26750 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26751 characters."
26752 (if (not s)
26754 (when is-body
26755 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26756 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26757 (while (string-match re s) (setq s (replace-match "" t t s)))
26758 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26759 (let ((start 0))
26760 (while (string-match "\\([,;\\]\\)" s start)
26761 (setq start (+ (match-beginning 0) 2)
26762 s (replace-match "\\\\\\1" nil nil s))))
26763 (when is-body
26764 (while (string-match "[ \t]*\n[ \t]*" s)
26765 (setq s (replace-match "\\n" t t s))))
26766 (setq s (org-trim s))
26767 (if is-body
26768 (if maxlength
26769 (if (and (numberp maxlength)
26770 (> (length s) maxlength))
26771 (setq s (substring s 0 maxlength)))))
26774 (defun org-get-entry ()
26775 "Clean-up description string."
26776 (save-excursion
26777 (org-back-to-heading t)
26778 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26780 (defun org-start-icalendar-file (name)
26781 "Start an iCalendar file by inserting the header."
26782 (let ((user user-full-name)
26783 (name (or name "unknown"))
26784 (timezone (cadr (current-time-zone))))
26785 (princ
26786 (format "BEGIN:VCALENDAR
26787 VERSION:2.0
26788 X-WR-CALNAME:%s
26789 PRODID:-//%s//Emacs with Org-mode//EN
26790 X-WR-TIMEZONE:%s
26791 CALSCALE:GREGORIAN\n" name user timezone))))
26793 (defun org-finish-icalendar-file ()
26794 "Finish an iCalendar file by inserting the END statement."
26795 (princ "END:VCALENDAR\n"))
26797 (defun org-ical-ts-to-string (s keyword &optional inc)
26798 "Take a time string S and convert it to iCalendar format.
26799 KEYWORD is added in front, to make a complete line like DTSTART....
26800 When INC is non-nil, increase the hour by two (if time string contains
26801 a time), or the day by one (if it does not contain a time)."
26802 (let ((t1 (org-parse-time-string s 'nodefault))
26803 t2 fmt have-time time)
26804 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26805 (setq t2 t1 have-time t)
26806 (setq t2 (org-parse-time-string s)))
26807 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26808 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26809 (when inc
26810 (if have-time
26811 (if org-agenda-default-appointment-duration
26812 (setq mi (+ org-agenda-default-appointment-duration mi))
26813 (setq h (+ 2 h)))
26814 (setq d (1+ d))))
26815 (setq time (encode-time s mi h d m y)))
26816 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26817 (concat keyword (format-time-string fmt time))))
26819 ;;; XOXO export
26821 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26822 (with-current-buffer buffer
26823 (apply 'insert output)))
26824 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26826 (defun org-export-as-xoxo (&optional buffer)
26827 "Export the org buffer as XOXO.
26828 The XOXO buffer is named *xoxo-<source buffer name>*"
26829 (interactive (list (current-buffer)))
26830 ;; A quickie abstraction
26832 ;; Output everything as XOXO
26833 (with-current-buffer (get-buffer buffer)
26834 (let* ((pos (point))
26835 (opt-plist (org-combine-plists (org-default-export-plist)
26836 (org-infile-export-plist)))
26837 (filename (concat (file-name-as-directory
26838 (org-export-directory :xoxo opt-plist))
26839 (file-name-sans-extension
26840 (file-name-nondirectory buffer-file-name))
26841 ".html"))
26842 (out (find-file-noselect filename))
26843 (last-level 1)
26844 (hanging-li nil))
26845 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26846 ;; Check the output buffer is empty.
26847 (with-current-buffer out (erase-buffer))
26848 ;; Kick off the output
26849 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26850 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26851 (let* ((hd (match-string-no-properties 1))
26852 (level (length hd))
26853 (text (concat
26854 (match-string-no-properties 2)
26855 (save-excursion
26856 (goto-char (match-end 0))
26857 (let ((str ""))
26858 (catch 'loop
26859 (while 't
26860 (forward-line)
26861 (if (looking-at "^[ \t]\\(.*\\)")
26862 (setq str (concat str (match-string-no-properties 1)))
26863 (throw 'loop str)))))))))
26865 ;; Handle level rendering
26866 (cond
26867 ((> level last-level)
26868 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
26870 ((< level last-level)
26871 (dotimes (- (- last-level level) 1)
26872 (if hanging-li
26873 (org-export-as-xoxo-insert-into out "</li>\n"))
26874 (org-export-as-xoxo-insert-into out "</ol>\n"))
26875 (when hanging-li
26876 (org-export-as-xoxo-insert-into out "</li>\n")
26877 (setq hanging-li nil)))
26879 ((equal level last-level)
26880 (if hanging-li
26881 (org-export-as-xoxo-insert-into out "</li>\n")))
26884 (setq last-level level)
26886 ;; And output the new li
26887 (setq hanging-li 't)
26888 (if (equal ?+ (elt text 0))
26889 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
26890 (org-export-as-xoxo-insert-into out "<li>" text))))
26892 ;; Finally finish off the ol
26893 (dotimes (- last-level 1)
26894 (if hanging-li
26895 (org-export-as-xoxo-insert-into out "</li>\n"))
26896 (org-export-as-xoxo-insert-into out "</ol>\n"))
26898 (goto-char pos)
26899 ;; Finish the buffer off and clean it up.
26900 (switch-to-buffer-other-window out)
26901 (indent-region (point-min) (point-max) nil)
26902 (save-buffer)
26903 (goto-char (point-min))
26907 ;;;; Key bindings
26909 ;; Make `C-c C-x' a prefix key
26910 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
26912 ;; TAB key with modifiers
26913 (org-defkey org-mode-map "\C-i" 'org-cycle)
26914 (org-defkey org-mode-map [(tab)] 'org-cycle)
26915 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
26916 (org-defkey org-mode-map [(meta tab)] 'org-complete)
26917 (org-defkey org-mode-map "\M-\t" 'org-complete)
26918 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
26919 ;; The following line is necessary under Suse GNU/Linux
26920 (unless (featurep 'xemacs)
26921 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
26922 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
26923 (define-key org-mode-map [backtab] 'org-shifttab)
26925 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
26926 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
26927 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
26929 ;; Cursor keys with modifiers
26930 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
26931 (org-defkey org-mode-map [(meta right)] 'org-metaright)
26932 (org-defkey org-mode-map [(meta up)] 'org-metaup)
26933 (org-defkey org-mode-map [(meta down)] 'org-metadown)
26935 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
26936 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
26937 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
26938 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
26940 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
26941 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
26942 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
26943 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
26945 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
26946 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
26948 ;;; Extra keys for tty access.
26949 ;; We only set them when really needed because otherwise the
26950 ;; menus don't show the simple keys
26952 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
26953 (not window-system))
26954 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
26955 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
26956 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
26957 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
26958 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
26959 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
26960 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
26961 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
26962 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
26963 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
26964 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
26965 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
26966 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
26967 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
26968 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
26969 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
26970 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
26971 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
26972 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
26973 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
26974 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
26975 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
26977 ;; All the other keys
26979 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
26980 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
26981 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
26982 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
26983 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
26984 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
26985 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
26986 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
26987 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
26988 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
26989 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
26990 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
26991 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
26992 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
26993 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
26994 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
26995 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
26996 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
26997 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
26998 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
26999 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27000 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27001 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27002 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27003 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27004 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27005 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27006 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27007 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27008 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27009 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27010 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27011 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27012 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27013 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27014 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27015 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27016 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27017 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27018 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27019 (org-defkey org-mode-map "\C-c^" 'org-sort)
27020 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27021 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27022 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27023 (org-defkey org-mode-map "\C-m" 'org-return)
27024 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27025 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27026 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27027 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27028 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27029 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27030 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27031 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27032 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27033 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27034 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27035 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27036 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27037 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27038 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27039 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27041 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27042 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27043 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27044 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27046 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27047 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27048 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27049 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27050 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27051 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27052 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27053 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27054 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27055 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27056 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27057 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27059 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27061 (when (featurep 'xemacs)
27062 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27064 (defsubst org-table-p () (org-at-table-p))
27066 (defun org-self-insert-command (N)
27067 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27068 If the cursor is in a table looking at whitespace, the whitespace is
27069 overwritten, and the table is not marked as requiring realignment."
27070 (interactive "p")
27071 (if (and (org-table-p)
27072 (progn
27073 ;; check if we blank the field, and if that triggers align
27074 (and org-table-auto-blank-field
27075 (member last-command
27076 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27077 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27078 ;; got extra space, this field does not determine column width
27079 (let (org-table-may-need-update) (org-table-blank-field))
27080 ;; no extra space, this field may determine column width
27081 (org-table-blank-field)))
27083 (eq N 1)
27084 (looking-at "[^|\n]* |"))
27085 (let (org-table-may-need-update)
27086 (goto-char (1- (match-end 0)))
27087 (delete-backward-char 1)
27088 (goto-char (match-beginning 0))
27089 (self-insert-command N))
27090 (setq org-table-may-need-update t)
27091 (self-insert-command N)
27092 (org-fix-tags-on-the-fly)))
27094 (defun org-fix-tags-on-the-fly ()
27095 (when (and (equal (char-after (point-at-bol)) ?*)
27096 (org-on-heading-p))
27097 (org-align-tags-here org-tags-column)))
27099 (defun org-delete-backward-char (N)
27100 "Like `delete-backward-char', insert whitespace at field end in tables.
27101 When deleting backwards, in tables this function will insert whitespace in
27102 front of the next \"|\" separator, to keep the table aligned. The table will
27103 still be marked for re-alignment if the field did fill the entire column,
27104 because, in this case the deletion might narrow the column."
27105 (interactive "p")
27106 (if (and (org-table-p)
27107 (eq N 1)
27108 (string-match "|" (buffer-substring (point-at-bol) (point)))
27109 (looking-at ".*?|"))
27110 (let ((pos (point))
27111 (noalign (looking-at "[^|\n\r]* |"))
27112 (c org-table-may-need-update))
27113 (backward-delete-char N)
27114 (skip-chars-forward "^|")
27115 (insert " ")
27116 (goto-char (1- pos))
27117 ;; noalign: if there were two spaces at the end, this field
27118 ;; does not determine the width of the column.
27119 (if noalign (setq org-table-may-need-update c)))
27120 (backward-delete-char N)
27121 (org-fix-tags-on-the-fly)))
27123 (defun org-delete-char (N)
27124 "Like `delete-char', but insert whitespace at field end in tables.
27125 When deleting characters, in tables this function will insert whitespace in
27126 front of the next \"|\" separator, to keep the table aligned. The table will
27127 still be marked for re-alignment if the field did fill the entire column,
27128 because, in this case the deletion might narrow the column."
27129 (interactive "p")
27130 (if (and (org-table-p)
27131 (not (bolp))
27132 (not (= (char-after) ?|))
27133 (eq N 1))
27134 (if (looking-at ".*?|")
27135 (let ((pos (point))
27136 (noalign (looking-at "[^|\n\r]* |"))
27137 (c org-table-may-need-update))
27138 (replace-match (concat
27139 (substring (match-string 0) 1 -1)
27140 " |"))
27141 (goto-char pos)
27142 ;; noalign: if there were two spaces at the end, this field
27143 ;; does not determine the width of the column.
27144 (if noalign (setq org-table-may-need-update c)))
27145 (delete-char N))
27146 (delete-char N)
27147 (org-fix-tags-on-the-fly)))
27149 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27150 (put 'org-self-insert-command 'delete-selection t)
27151 (put 'orgtbl-self-insert-command 'delete-selection t)
27152 (put 'org-delete-char 'delete-selection 'supersede)
27153 (put 'org-delete-backward-char 'delete-selection 'supersede)
27155 ;; Make `flyspell-mode' delay after some commands
27156 (put 'org-self-insert-command 'flyspell-delayed t)
27157 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27158 (put 'org-delete-char 'flyspell-delayed t)
27159 (put 'org-delete-backward-char 'flyspell-delayed t)
27161 ;; Make pabbrev-mode expand after org-mode commands
27162 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27163 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27165 ;; How to do this: Measure non-white length of current string
27166 ;; If equal to column width, we should realign.
27168 (defun org-remap (map &rest commands)
27169 "In MAP, remap the functions given in COMMANDS.
27170 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27171 (let (new old)
27172 (while commands
27173 (setq old (pop commands) new (pop commands))
27174 (if (fboundp 'command-remapping)
27175 (org-defkey map (vector 'remap old) new)
27176 (substitute-key-definition old new map global-map)))))
27178 (when (eq org-enable-table-editor 'optimized)
27179 ;; If the user wants maximum table support, we need to hijack
27180 ;; some standard editing functions
27181 (org-remap org-mode-map
27182 'self-insert-command 'org-self-insert-command
27183 'delete-char 'org-delete-char
27184 'delete-backward-char 'org-delete-backward-char)
27185 (org-defkey org-mode-map "|" 'org-force-self-insert))
27187 (defun org-shiftcursor-error ()
27188 "Throw an error because Shift-Cursor command was applied in wrong context."
27189 (error "This command is active in special context like tables, headlines or timestamps"))
27191 (defun org-shifttab (&optional arg)
27192 "Global visibility cycling or move to previous table field.
27193 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27194 on context.
27195 See the individual commands for more information."
27196 (interactive "P")
27197 (cond
27198 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27199 (arg (message "Content view to level: ")
27200 (org-content (prefix-numeric-value arg))
27201 (setq org-cycle-global-status 'overview))
27202 (t (call-interactively 'org-global-cycle))))
27204 (defun org-shiftmetaleft ()
27205 "Promote subtree or delete table column.
27206 Calls `org-promote-subtree', `org-outdent-item',
27207 or `org-table-delete-column', depending on context.
27208 See the individual commands for more information."
27209 (interactive)
27210 (cond
27211 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27212 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27213 ((org-at-item-p) (call-interactively 'org-outdent-item))
27214 (t (org-shiftcursor-error))))
27216 (defun org-shiftmetaright ()
27217 "Demote subtree or insert table column.
27218 Calls `org-demote-subtree', `org-indent-item',
27219 or `org-table-insert-column', depending on context.
27220 See the individual commands for more information."
27221 (interactive)
27222 (cond
27223 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27224 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27225 ((org-at-item-p) (call-interactively 'org-indent-item))
27226 (t (org-shiftcursor-error))))
27228 (defun org-shiftmetaup (&optional arg)
27229 "Move subtree up or kill table row.
27230 Calls `org-move-subtree-up' or `org-table-kill-row' or
27231 `org-move-item-up' depending on context. See the individual commands
27232 for more information."
27233 (interactive "P")
27234 (cond
27235 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27236 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27237 ((org-at-item-p) (call-interactively 'org-move-item-up))
27238 (t (org-shiftcursor-error))))
27239 (defun org-shiftmetadown (&optional arg)
27240 "Move subtree down or insert table row.
27241 Calls `org-move-subtree-down' or `org-table-insert-row' or
27242 `org-move-item-down', depending on context. See the individual
27243 commands for more information."
27244 (interactive "P")
27245 (cond
27246 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27247 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27248 ((org-at-item-p) (call-interactively 'org-move-item-down))
27249 (t (org-shiftcursor-error))))
27251 (defun org-metaleft (&optional arg)
27252 "Promote heading or move table column to left.
27253 Calls `org-do-promote' or `org-table-move-column', depending on context.
27254 With no specific context, calls the Emacs default `backward-word'.
27255 See the individual commands for more information."
27256 (interactive "P")
27257 (cond
27258 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27259 ((or (org-on-heading-p) (org-region-active-p))
27260 (call-interactively 'org-do-promote))
27261 ((org-at-item-p) (call-interactively 'org-outdent-item))
27262 (t (call-interactively 'backward-word))))
27264 (defun org-metaright (&optional arg)
27265 "Demote subtree or move table column to right.
27266 Calls `org-do-demote' or `org-table-move-column', depending on context.
27267 With no specific context, calls the Emacs default `forward-word'.
27268 See the individual commands for more information."
27269 (interactive "P")
27270 (cond
27271 ((org-at-table-p) (call-interactively 'org-table-move-column))
27272 ((or (org-on-heading-p) (org-region-active-p))
27273 (call-interactively 'org-do-demote))
27274 ((org-at-item-p) (call-interactively 'org-indent-item))
27275 (t (call-interactively 'forward-word))))
27277 (defun org-metaup (&optional arg)
27278 "Move subtree up or move table row up.
27279 Calls `org-move-subtree-up' or `org-table-move-row' or
27280 `org-move-item-up', depending on context. See the individual commands
27281 for more information."
27282 (interactive "P")
27283 (cond
27284 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27285 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27286 ((org-at-item-p) (call-interactively 'org-move-item-up))
27287 (t (transpose-lines 1) (beginning-of-line -1))))
27289 (defun org-metadown (&optional arg)
27290 "Move subtree down or move table row down.
27291 Calls `org-move-subtree-down' or `org-table-move-row' or
27292 `org-move-item-down', depending on context. See the individual
27293 commands for more information."
27294 (interactive "P")
27295 (cond
27296 ((org-at-table-p) (call-interactively 'org-table-move-row))
27297 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27298 ((org-at-item-p) (call-interactively 'org-move-item-down))
27299 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27301 (defun org-shiftup (&optional arg)
27302 "Increase item in timestamp or increase priority of current headline.
27303 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27304 depending on context. See the individual commands for more information."
27305 (interactive "P")
27306 (cond
27307 ((org-at-timestamp-p t)
27308 (call-interactively (if org-edit-timestamp-down-means-later
27309 'org-timestamp-down 'org-timestamp-up)))
27310 ((org-on-heading-p) (call-interactively 'org-priority-up))
27311 ((org-at-item-p) (call-interactively 'org-previous-item))
27312 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27314 (defun org-shiftdown (&optional arg)
27315 "Decrease item in timestamp or decrease priority of current headline.
27316 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27317 depending on context. See the individual commands for more information."
27318 (interactive "P")
27319 (cond
27320 ((org-at-timestamp-p t)
27321 (call-interactively (if org-edit-timestamp-down-means-later
27322 'org-timestamp-up 'org-timestamp-down)))
27323 ((org-on-heading-p) (call-interactively 'org-priority-down))
27324 (t (call-interactively 'org-next-item))))
27326 (defun org-shiftright ()
27327 "Next TODO keyword or timestamp one day later, depending on context."
27328 (interactive)
27329 (cond
27330 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27331 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27332 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27333 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27334 (t (org-shiftcursor-error))))
27336 (defun org-shiftleft ()
27337 "Previous TODO keyword or timestamp one day earlier, depending on context."
27338 (interactive)
27339 (cond
27340 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27341 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27342 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27343 ((org-at-property-p)
27344 (call-interactively 'org-property-previous-allowed-value))
27345 (t (org-shiftcursor-error))))
27347 (defun org-shiftcontrolright ()
27348 "Switch to next TODO set."
27349 (interactive)
27350 (cond
27351 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27352 (t (org-shiftcursor-error))))
27354 (defun org-shiftcontrolleft ()
27355 "Switch to previous TODO set."
27356 (interactive)
27357 (cond
27358 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27359 (t (org-shiftcursor-error))))
27361 (defun org-ctrl-c-ret ()
27362 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27363 (interactive)
27364 (cond
27365 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27366 (t (call-interactively 'org-insert-heading))))
27368 (defun org-copy-special ()
27369 "Copy region in table or copy current subtree.
27370 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27371 See the individual commands for more information."
27372 (interactive)
27373 (call-interactively
27374 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27376 (defun org-cut-special ()
27377 "Cut region in table or cut current subtree.
27378 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27379 See the individual commands for more information."
27380 (interactive)
27381 (call-interactively
27382 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27384 (defun org-paste-special (arg)
27385 "Paste rectangular region into table, or past subtree relative to level.
27386 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27387 See the individual commands for more information."
27388 (interactive "P")
27389 (if (org-at-table-p)
27390 (org-table-paste-rectangle)
27391 (org-paste-subtree arg)))
27393 (defun org-ctrl-c-ctrl-c (&optional arg)
27394 "Set tags in headline, or update according to changed information at point.
27396 This command does many different things, depending on context:
27398 - If the cursor is in a headline, prompt for tags and insert them
27399 into the current line, aligned to `org-tags-column'. When called
27400 with prefix arg, realign all tags in the current buffer.
27402 - If the cursor is in one of the special #+KEYWORD lines, this
27403 triggers scanning the buffer for these lines and updating the
27404 information.
27406 - If the cursor is inside a table, realign the table. This command
27407 works even if the automatic table editor has been turned off.
27409 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27410 the entire table.
27412 - If the cursor is a the beginning of a dynamic block, update it.
27414 - If the cursor is inside a table created by the table.el package,
27415 activate that table.
27417 - If the current buffer is a remember buffer, close note and file it.
27418 with a prefix argument, file it without further interaction to the default
27419 location.
27421 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27422 links in this buffer.
27424 - If the cursor is on a numbered item in a plain list, renumber the
27425 ordered list.
27427 - If the cursor is on a checkbox, toggle it."
27428 (interactive "P")
27429 (let ((org-enable-table-editor t))
27430 (cond
27431 ((or org-clock-overlays
27432 org-occur-highlights
27433 org-latex-fragment-image-overlays)
27434 (org-remove-clock-overlays)
27435 (org-remove-occur-highlights)
27436 (org-remove-latex-fragment-image-overlays)
27437 (message "Temporary highlights/overlays removed from current buffer"))
27438 ((and (local-variable-p 'org-finish-function (current-buffer))
27439 (fboundp org-finish-function))
27440 (funcall org-finish-function))
27441 ((org-at-property-p)
27442 (call-interactively 'org-property-action))
27443 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27444 ((org-on-heading-p) (call-interactively 'org-set-tags))
27445 ((org-at-table.el-p)
27446 (require 'table)
27447 (beginning-of-line 1)
27448 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27449 (call-interactively 'table-recognize-table))
27450 ((org-at-table-p)
27451 (org-table-maybe-eval-formula)
27452 (if arg
27453 (call-interactively 'org-table-recalculate)
27454 (org-table-maybe-recalculate-line))
27455 (call-interactively 'org-table-align))
27456 ((org-at-item-checkbox-p)
27457 (call-interactively 'org-toggle-checkbox))
27458 ((org-at-item-p)
27459 (call-interactively 'org-maybe-renumber-ordered-list))
27460 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27461 ;; Dynamic block
27462 (beginning-of-line 1)
27463 (org-update-dblock))
27464 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27465 (cond
27466 ((equal (match-string 1) "TBLFM")
27467 ;; Recalculate the table before this line
27468 (save-excursion
27469 (beginning-of-line 1)
27470 (skip-chars-backward " \r\n\t")
27471 (if (org-at-table-p)
27472 (org-call-with-arg 'org-table-recalculate t))))
27474 (call-interactively 'org-mode-restart))))
27475 (t (error "C-c C-c can do nothing useful at this location.")))))
27477 (defun org-mode-restart ()
27478 "Restart Org-mode, to scan again for special lines.
27479 Also updates the keyword regular expressions."
27480 (interactive)
27481 (let ((org-inhibit-startup t)) (org-mode))
27482 (message "Org-mode restarted to refresh keyword and special line setup"))
27484 (defun org-kill-note-or-show-branches ()
27485 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27486 (interactive)
27487 (if (not org-finish-function)
27488 (call-interactively 'show-branches)
27489 (let ((org-note-abort t))
27490 (funcall org-finish-function))))
27492 (defun org-return (&optional indent)
27493 "Goto next table row or insert a newline.
27494 Calls `org-table-next-row' or `newline', depending on context.
27495 See the individual commands for more information."
27496 (interactive)
27497 (cond
27498 ((bobp) (if indent (newline-and-indent) (newline)))
27499 ((and (org-at-heading-p)
27500 (looking-at
27501 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27502 (org-show-entry)
27503 (end-of-line 1)
27504 (newline))
27505 ((org-at-table-p)
27506 (org-table-justify-field-maybe)
27507 (call-interactively 'org-table-next-row))
27508 (t (if indent (newline-and-indent) (newline)))))
27510 (defun org-return-indent ()
27511 "Goto next table row or insert a newline and indent.
27512 Calls `org-table-next-row' or `newline-and-indent', depending on
27513 context. See the individual commands for more information."
27514 (interactive)
27515 (org-return t))
27517 (defun org-ctrl-c-star ()
27518 "Compute table, or change heading status of lines.
27519 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27520 depending on context. This will also turn a plain list item or a normal
27521 line into a subheading."
27522 (interactive)
27523 (cond
27524 ((org-at-table-p)
27525 (call-interactively 'org-table-recalculate))
27526 ((org-region-active-p)
27527 ;; Convert all lines in region to list items
27528 (call-interactively 'org-toggle-region-headings))
27529 ((org-on-heading-p)
27530 (org-toggle-region-headings (point-at-bol)
27531 (min (1+ (point-at-eol)) (point-max))))
27532 ((org-at-item-p)
27533 ;; Convert to heading
27534 ;; FIXME: not yet implemented
27536 (t (org-toggle-region-headings (point-at-bol)
27537 (min (1+ (point-at-eol)) (point-max))))))
27539 (defun org-ctrl-c-minus ()
27540 "Insert separator line in table or modify bullet status of line.
27541 Also turns a plain line or a region of lines into list items.
27542 Calls `org-table-insert-hline', `org-toggle-region-items', or
27543 `org-cycle-list-bullet', depending on context."
27544 (interactive)
27545 (cond
27546 ((org-at-table-p)
27547 (call-interactively 'org-table-insert-hline))
27548 ((org-on-heading-p)
27549 ;; Convert to item
27550 (save-excursion
27551 (beginning-of-line 1)
27552 (if (looking-at "\\*+ ")
27553 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27554 ((org-region-active-p)
27555 ;; Convert all lines in region to list items
27556 (call-interactively 'org-toggle-region-items))
27557 ((org-in-item-p)
27558 (call-interactively 'org-cycle-list-bullet))
27559 (t (org-toggle-region-items (point-at-bol)
27560 (min (1+ (point-at-eol)) (point-max))))))
27562 (defun org-toggle-region-items (beg end)
27563 "Convert all lines in region to list items.
27564 If the first line is already an item, convert all list items in the region
27565 to normal lines."
27566 (interactive "r")
27567 (let (l2 l)
27568 (save-excursion
27569 (goto-char end)
27570 (setq l2 (org-current-line))
27571 (goto-char beg)
27572 (beginning-of-line 1)
27573 (setq l (1- (org-current-line)))
27574 (if (org-at-item-p)
27575 ;; We already have items, de-itemize
27576 (while (< (setq l (1+ l)) l2)
27577 (when (org-at-item-p)
27578 (goto-char (match-beginning 2))
27579 (delete-region (match-beginning 2) (match-end 2))
27580 (and (looking-at "[ \t]+") (replace-match "")))
27581 (beginning-of-line 2))
27582 (while (< (setq l (1+ l)) l2)
27583 (unless (org-at-item-p)
27584 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27585 (replace-match "\\1- \\2")))
27586 (beginning-of-line 2))))))
27588 (defun org-toggle-region-headings (beg end)
27589 "Convert all lines in region to list items.
27590 If the first line is already an item, convert all list items in the region
27591 to normal lines."
27592 (interactive "r")
27593 (let (l2 l)
27594 (save-excursion
27595 (goto-char end)
27596 (setq l2 (org-current-line))
27597 (goto-char beg)
27598 (beginning-of-line 1)
27599 (setq l (1- (org-current-line)))
27600 (if (org-on-heading-p)
27601 ;; We already have headlines, de-star them
27602 (while (< (setq l (1+ l)) l2)
27603 (when (org-on-heading-p t)
27604 (and (looking-at outline-regexp) (replace-match "")))
27605 (beginning-of-line 2))
27606 (let* ((stars (save-excursion
27607 (re-search-backward org-complex-heading-regexp nil t)
27608 (or (match-string 1) "*")))
27609 (add-stars (if org-odd-levels-only "**" "*"))
27610 (rpl (concat stars add-stars " \\2")))
27611 (while (< (setq l (1+ l)) l2)
27612 (unless (org-on-heading-p)
27613 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27614 (replace-match rpl)))
27615 (beginning-of-line 2)))))))
27617 (defun org-meta-return (&optional arg)
27618 "Insert a new heading or wrap a region in a table.
27619 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27620 See the individual commands for more information."
27621 (interactive "P")
27622 (cond
27623 ((org-at-table-p)
27624 (call-interactively 'org-table-wrap-region))
27625 (t (call-interactively 'org-insert-heading))))
27627 ;;; Menu entries
27629 ;; Define the Org-mode menus
27630 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27631 '("Tbl"
27632 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27633 ["Next Field" org-cycle (org-at-table-p)]
27634 ["Previous Field" org-shifttab (org-at-table-p)]
27635 ["Next Row" org-return (org-at-table-p)]
27636 "--"
27637 ["Blank Field" org-table-blank-field (org-at-table-p)]
27638 ["Edit Field" org-table-edit-field (org-at-table-p)]
27639 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27640 "--"
27641 ("Column"
27642 ["Move Column Left" org-metaleft (org-at-table-p)]
27643 ["Move Column Right" org-metaright (org-at-table-p)]
27644 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27645 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27646 ("Row"
27647 ["Move Row Up" org-metaup (org-at-table-p)]
27648 ["Move Row Down" org-metadown (org-at-table-p)]
27649 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27650 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27651 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27652 "--"
27653 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27654 ("Rectangle"
27655 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27656 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27657 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27658 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27659 "--"
27660 ("Calculate"
27661 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27662 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27663 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27664 "--"
27665 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27666 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27667 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27668 "--"
27669 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27670 "--"
27671 ["Sum Column/Rectangle" org-table-sum
27672 (or (org-at-table-p) (org-region-active-p))]
27673 ["Which Column?" org-table-current-column (org-at-table-p)])
27674 ["Debug Formulas"
27675 org-table-toggle-formula-debugger
27676 :style toggle :selected org-table-formula-debug]
27677 ["Show Col/Row Numbers"
27678 org-table-toggle-coordinate-overlays
27679 :style toggle :selected org-table-overlay-coordinates]
27680 "--"
27681 ["Create" org-table-create (and (not (org-at-table-p))
27682 org-enable-table-editor)]
27683 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27684 ["Import from File" org-table-import (not (org-at-table-p))]
27685 ["Export to File" org-table-export (org-at-table-p)]
27686 "--"
27687 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27689 (easy-menu-define org-org-menu org-mode-map "Org menu"
27690 '("Org"
27691 ("Show/Hide"
27692 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27693 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27694 ["Sparse Tree" org-occur t]
27695 ["Reveal Context" org-reveal t]
27696 ["Show All" show-all t]
27697 "--"
27698 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27699 "--"
27700 ["New Heading" org-insert-heading t]
27701 ("Navigate Headings"
27702 ["Up" outline-up-heading t]
27703 ["Next" outline-next-visible-heading t]
27704 ["Previous" outline-previous-visible-heading t]
27705 ["Next Same Level" outline-forward-same-level t]
27706 ["Previous Same Level" outline-backward-same-level t]
27707 "--"
27708 ["Jump" org-goto t])
27709 ("Edit Structure"
27710 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27711 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27712 "--"
27713 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27714 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27715 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27716 "--"
27717 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27718 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27719 ["Demote Heading" org-metaright (not (org-at-table-p))]
27720 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27721 "--"
27722 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27723 "--"
27724 ["Convert to odd levels" org-convert-to-odd-levels t]
27725 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27726 ("Editing"
27727 ["Emphasis..." org-emphasize t])
27728 ("Archive"
27729 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27730 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27731 ; :active t :keys "C-u C-c C-x C-a"]
27732 ["Sparse trees open ARCHIVE trees"
27733 (setq org-sparse-tree-open-archived-trees
27734 (not org-sparse-tree-open-archived-trees))
27735 :style toggle :selected org-sparse-tree-open-archived-trees]
27736 ["Cycling opens ARCHIVE trees"
27737 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27738 :style toggle :selected org-cycle-open-archived-trees]
27739 ["Agenda includes ARCHIVE trees"
27740 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27741 :style toggle :selected (not org-agenda-skip-archived-trees)]
27742 "--"
27743 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27744 ; ["Check and Move Children" (org-archive-subtree '(4))
27745 ; :active t :keys "C-u C-c C-x C-s"]
27747 "--"
27748 ("TODO Lists"
27749 ["TODO/DONE/-" org-todo t]
27750 ("Select keyword"
27751 ["Next keyword" org-shiftright (org-on-heading-p)]
27752 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27753 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27754 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27755 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27756 ["Show TODO Tree" org-show-todo-tree t]
27757 ["Global TODO list" org-todo-list t]
27758 "--"
27759 ["Set Priority" org-priority t]
27760 ["Priority Up" org-shiftup t]
27761 ["Priority Down" org-shiftdown t])
27762 ("TAGS and Properties"
27763 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27764 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27765 "--"
27766 ["Set property" 'org-set-property t]
27767 ["Column view of properties" org-columns t]
27768 ["Insert Column View DBlock" org-insert-columns-dblock t])
27769 ("Dates and Scheduling"
27770 ["Timestamp" org-time-stamp t]
27771 ["Timestamp (inactive)" org-time-stamp-inactive t]
27772 ("Change Date"
27773 ["1 Day Later" org-shiftright t]
27774 ["1 Day Earlier" org-shiftleft t]
27775 ["1 ... Later" org-shiftup t]
27776 ["1 ... Earlier" org-shiftdown t])
27777 ["Compute Time Range" org-evaluate-time-range t]
27778 ["Schedule Item" org-schedule t]
27779 ["Deadline" org-deadline t]
27780 "--"
27781 ["Custom time format" org-toggle-time-stamp-overlays
27782 :style radio :selected org-display-custom-times]
27783 "--"
27784 ["Goto Calendar" org-goto-calendar t]
27785 ["Date from Calendar" org-date-from-calendar t])
27786 ("Logging work"
27787 ["Clock in" org-clock-in t]
27788 ["Clock out" org-clock-out t]
27789 ["Clock cancel" org-clock-cancel t]
27790 ["Goto running clock" org-clock-goto t]
27791 ["Display times" org-clock-display t]
27792 ["Create clock table" org-clock-report t]
27793 "--"
27794 ["Record DONE time"
27795 (progn (setq org-log-done (not org-log-done))
27796 (message "Switching to %s will %s record a timestamp"
27797 (car org-done-keywords)
27798 (if org-log-done "automatically" "not")))
27799 :style toggle :selected org-log-done])
27800 "--"
27801 ["Agenda Command..." org-agenda t]
27802 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27803 ("File List for Agenda")
27804 ("Special views current file"
27805 ["TODO Tree" org-show-todo-tree t]
27806 ["Check Deadlines" org-check-deadlines t]
27807 ["Timeline" org-timeline t]
27808 ["Tags Tree" org-tags-sparse-tree t])
27809 "--"
27810 ("Hyperlinks"
27811 ["Store Link (Global)" org-store-link t]
27812 ["Insert Link" org-insert-link t]
27813 ["Follow Link" org-open-at-point t]
27814 "--"
27815 ["Next link" org-next-link t]
27816 ["Previous link" org-previous-link t]
27817 "--"
27818 ["Descriptive Links"
27819 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27820 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27821 ["Literal Links"
27822 (progn
27823 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27824 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27825 "--"
27826 ["Export/Publish..." org-export t]
27827 ("LaTeX"
27828 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27829 :selected org-cdlatex-mode]
27830 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27831 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27832 ["Modify math symbol" org-cdlatex-math-modify
27833 (org-inside-LaTeX-fragment-p)]
27834 ["Export LaTeX fragments as images"
27835 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27836 :style toggle :selected org-export-with-LaTeX-fragments])
27837 "--"
27838 ("Documentation"
27839 ["Show Version" org-version t]
27840 ["Info Documentation" org-info t])
27841 ("Customize"
27842 ["Browse Org Group" org-customize t]
27843 "--"
27844 ["Expand This Menu" org-create-customize-menu
27845 (fboundp 'customize-menu-create)])
27846 "--"
27847 ["Refresh setup" org-mode-restart t]
27850 (defun org-info (&optional node)
27851 "Read documentation for Org-mode in the info system.
27852 With optional NODE, go directly to that node."
27853 (interactive)
27854 (require 'info)
27855 (info (format "(org)%s" (or node ""))))
27857 (defun org-install-agenda-files-menu ()
27858 (let ((bl (buffer-list)))
27859 (save-excursion
27860 (while bl
27861 (set-buffer (pop bl))
27862 (if (org-mode-p) (setq bl nil)))
27863 (when (org-mode-p)
27864 (easy-menu-change
27865 '("Org") "File List for Agenda"
27866 (append
27867 (list
27868 ["Edit File List" (org-edit-agenda-file-list) t]
27869 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
27870 ["Remove Current File from List" org-remove-file t]
27871 ["Cycle through agenda files" org-cycle-agenda-files t]
27872 ["Occur in all agenda files" org-occur-in-agenda-files t]
27873 "--")
27874 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
27876 ;;;; Documentation
27878 (defun org-customize ()
27879 "Call the customize function with org as argument."
27880 (interactive)
27881 (customize-browse 'org))
27883 (defun org-create-customize-menu ()
27884 "Create a full customization menu for Org-mode, insert it into the menu."
27885 (interactive)
27886 (if (fboundp 'customize-menu-create)
27887 (progn
27888 (easy-menu-change
27889 '("Org") "Customize"
27890 `(["Browse Org group" org-customize t]
27891 "--"
27892 ,(customize-menu-create 'org)
27893 ["Set" Custom-set t]
27894 ["Save" Custom-save t]
27895 ["Reset to Current" Custom-reset-current t]
27896 ["Reset to Saved" Custom-reset-saved t]
27897 ["Reset to Standard Settings" Custom-reset-standard t]))
27898 (message "\"Org\"-menu now contains full customization menu"))
27899 (error "Cannot expand menu (outdated version of cus-edit.el)")))
27901 ;;;; Miscellaneous stuff
27904 ;;; Generally useful functions
27906 (defun org-context ()
27907 "Return a list of contexts of the current cursor position.
27908 If several contexts apply, all are returned.
27909 Each context entry is a list with a symbol naming the context, and
27910 two positions indicating start and end of the context. Possible
27911 contexts are:
27913 :headline anywhere in a headline
27914 :headline-stars on the leading stars in a headline
27915 :todo-keyword on a TODO keyword (including DONE) in a headline
27916 :tags on the TAGS in a headline
27917 :priority on the priority cookie in a headline
27918 :item on the first line of a plain list item
27919 :item-bullet on the bullet/number of a plain list item
27920 :checkbox on the checkbox in a plain list item
27921 :table in an org-mode table
27922 :table-special on a special filed in a table
27923 :table-table in a table.el table
27924 :link on a hyperlink
27925 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
27926 :target on a <<target>>
27927 :radio-target on a <<<radio-target>>>
27928 :latex-fragment on a LaTeX fragment
27929 :latex-preview on a LaTeX fragment with overlayed preview image
27931 This function expects the position to be visible because it uses font-lock
27932 faces as a help to recognize the following contexts: :table-special, :link,
27933 and :keyword."
27934 (let* ((f (get-text-property (point) 'face))
27935 (faces (if (listp f) f (list f)))
27936 (p (point)) clist o)
27937 ;; First the large context
27938 (cond
27939 ((org-on-heading-p t)
27940 (push (list :headline (point-at-bol) (point-at-eol)) clist)
27941 (when (progn
27942 (beginning-of-line 1)
27943 (looking-at org-todo-line-tags-regexp))
27944 (push (org-point-in-group p 1 :headline-stars) clist)
27945 (push (org-point-in-group p 2 :todo-keyword) clist)
27946 (push (org-point-in-group p 4 :tags) clist))
27947 (goto-char p)
27948 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
27949 (if (looking-at "\\[#[A-Z0-9]\\]")
27950 (push (org-point-in-group p 0 :priority) clist)))
27952 ((org-at-item-p)
27953 (push (org-point-in-group p 2 :item-bullet) clist)
27954 (push (list :item (point-at-bol)
27955 (save-excursion (org-end-of-item) (point)))
27956 clist)
27957 (and (org-at-item-checkbox-p)
27958 (push (org-point-in-group p 0 :checkbox) clist)))
27960 ((org-at-table-p)
27961 (push (list :table (org-table-begin) (org-table-end)) clist)
27962 (if (memq 'org-formula faces)
27963 (push (list :table-special
27964 (previous-single-property-change p 'face)
27965 (next-single-property-change p 'face)) clist)))
27966 ((org-at-table-p 'any)
27967 (push (list :table-table) clist)))
27968 (goto-char p)
27970 ;; Now the small context
27971 (cond
27972 ((org-at-timestamp-p)
27973 (push (org-point-in-group p 0 :timestamp) clist))
27974 ((memq 'org-link faces)
27975 (push (list :link
27976 (previous-single-property-change p 'face)
27977 (next-single-property-change p 'face)) clist))
27978 ((memq 'org-special-keyword faces)
27979 (push (list :keyword
27980 (previous-single-property-change p 'face)
27981 (next-single-property-change p 'face)) clist))
27982 ((org-on-target-p)
27983 (push (org-point-in-group p 0 :target) clist)
27984 (goto-char (1- (match-beginning 0)))
27985 (if (looking-at org-radio-target-regexp)
27986 (push (org-point-in-group p 0 :radio-target) clist))
27987 (goto-char p))
27988 ((setq o (car (delq nil
27989 (mapcar
27990 (lambda (x)
27991 (if (memq x org-latex-fragment-image-overlays) x))
27992 (org-overlays-at (point))))))
27993 (push (list :latex-fragment
27994 (org-overlay-start o) (org-overlay-end o)) clist)
27995 (push (list :latex-preview
27996 (org-overlay-start o) (org-overlay-end o)) clist))
27997 ((org-inside-LaTeX-fragment-p)
27998 ;; FIXME: positions wrong.
27999 (push (list :latex-fragment (point) (point)) clist)))
28001 (setq clist (nreverse (delq nil clist)))
28002 clist))
28004 ;; FIXME: Compare with at-regexp-p Do we need both?
28005 (defun org-in-regexp (re &optional nlines visually)
28006 "Check if point is inside a match of regexp.
28007 Normally only the current line is checked, but you can include NLINES extra
28008 lines both before and after point into the search.
28009 If VISUALLY is set, require that the cursor is not after the match but
28010 really on, so that the block visually is on the match."
28011 (catch 'exit
28012 (let ((pos (point))
28013 (eol (point-at-eol (+ 1 (or nlines 0))))
28014 (inc (if visually 1 0)))
28015 (save-excursion
28016 (beginning-of-line (- 1 (or nlines 0)))
28017 (while (re-search-forward re eol t)
28018 (if (and (<= (match-beginning 0) pos)
28019 (>= (+ inc (match-end 0)) pos))
28020 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28022 (defun org-at-regexp-p (regexp)
28023 "Is point inside a match of REGEXP in the current line?"
28024 (catch 'exit
28025 (save-excursion
28026 (let ((pos (point)) (end (point-at-eol)))
28027 (beginning-of-line 1)
28028 (while (re-search-forward regexp end t)
28029 (if (and (<= (match-beginning 0) pos)
28030 (>= (match-end 0) pos))
28031 (throw 'exit t)))
28032 nil))))
28034 (defun org-occur-in-agenda-files (regexp &optional nlines)
28035 "Call `multi-occur' with buffers for all agenda files."
28036 (interactive "sOrg-files matching: \np")
28037 (let* ((files (org-agenda-files))
28038 (tnames (mapcar 'file-truename files))
28039 (extra org-agenda-text-search-extra-files)
28041 (while (setq f (pop extra))
28042 (unless (member (file-truename f) tnames)
28043 (add-to-list 'files f 'append)
28044 (add-to-list 'tnames (file-truename f) 'append)))
28045 (multi-occur
28046 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28047 regexp)))
28049 (if (boundp 'occur-mode-find-occurrence-hook)
28050 ;; Emacs 23
28051 (add-hook 'occur-mode-find-occurrence-hook
28052 (lambda ()
28053 (when (org-mode-p)
28054 (org-reveal))))
28055 ;; Emacs 22
28056 (defadvice occur-mode-goto-occurrence
28057 (after org-occur-reveal activate)
28058 (and (org-mode-p) (org-reveal)))
28059 (defadvice occur-mode-goto-occurrence-other-window
28060 (after org-occur-reveal activate)
28061 (and (org-mode-p) (org-reveal)))
28062 (defadvice occur-mode-display-occurrence
28063 (after org-occur-reveal activate)
28064 (when (org-mode-p)
28065 (let ((pos (occur-mode-find-occurrence)))
28066 (with-current-buffer (marker-buffer pos)
28067 (save-excursion
28068 (goto-char pos)
28069 (org-reveal)))))))
28071 (defun org-uniquify (list)
28072 "Remove duplicate elements from LIST."
28073 (let (res)
28074 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28075 res))
28077 (defun org-delete-all (elts list)
28078 "Remove all elements in ELTS from LIST."
28079 (while elts
28080 (setq list (delete (pop elts) list)))
28081 list)
28083 (defun org-back-over-empty-lines ()
28084 "Move backwards over witespace, to the beginning of the first empty line.
28085 Returns the number o empty lines passed."
28086 (let ((pos (point)))
28087 (skip-chars-backward " \t\n\r")
28088 (beginning-of-line 2)
28089 (goto-char (min (point) pos))
28090 (count-lines (point) pos)))
28092 (defun org-skip-whitespace ()
28093 (skip-chars-forward " \t\n\r"))
28095 (defun org-point-in-group (point group &optional context)
28096 "Check if POINT is in match-group GROUP.
28097 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28098 match. If the match group does ot exist or point is not inside it,
28099 return nil."
28100 (and (match-beginning group)
28101 (>= point (match-beginning group))
28102 (<= point (match-end group))
28103 (if context
28104 (list context (match-beginning group) (match-end group))
28105 t)))
28107 (defun org-switch-to-buffer-other-window (&rest args)
28108 "Switch to buffer in a second window on the current frame.
28109 In particular, do not allow pop-up frames."
28110 (let (pop-up-frames special-display-buffer-names special-display-regexps
28111 special-display-function)
28112 (apply 'switch-to-buffer-other-window args)))
28114 (defun org-combine-plists (&rest plists)
28115 "Create a single property list from all plists in PLISTS.
28116 The process starts by copying the first list, and then setting properties
28117 from the other lists. Settings in the last list are the most significant
28118 ones and overrule settings in the other lists."
28119 (let ((rtn (copy-sequence (pop plists)))
28120 p v ls)
28121 (while plists
28122 (setq ls (pop plists))
28123 (while ls
28124 (setq p (pop ls) v (pop ls))
28125 (setq rtn (plist-put rtn p v))))
28126 rtn))
28128 (defun org-move-line-down (arg)
28129 "Move the current line down. With prefix argument, move it past ARG lines."
28130 (interactive "p")
28131 (let ((col (current-column))
28132 beg end pos)
28133 (beginning-of-line 1) (setq beg (point))
28134 (beginning-of-line 2) (setq end (point))
28135 (beginning-of-line (+ 1 arg))
28136 (setq pos (move-marker (make-marker) (point)))
28137 (insert (delete-and-extract-region beg end))
28138 (goto-char pos)
28139 (move-to-column col)))
28141 (defun org-move-line-up (arg)
28142 "Move the current line up. With prefix argument, move it past ARG lines."
28143 (interactive "p")
28144 (let ((col (current-column))
28145 beg end pos)
28146 (beginning-of-line 1) (setq beg (point))
28147 (beginning-of-line 2) (setq end (point))
28148 (beginning-of-line (- arg))
28149 (setq pos (move-marker (make-marker) (point)))
28150 (insert (delete-and-extract-region beg end))
28151 (goto-char pos)
28152 (move-to-column col)))
28154 (defun org-replace-escapes (string table)
28155 "Replace %-escapes in STRING with values in TABLE.
28156 TABLE is an association list with keys like \"%a\" and string values.
28157 The sequences in STRING may contain normal field width and padding information,
28158 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28159 so values can contain further %-escapes if they are define later in TABLE."
28160 (let ((case-fold-search nil)
28161 e re rpl)
28162 (while (setq e (pop table))
28163 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28164 (while (string-match re string)
28165 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28166 (cdr e)))
28167 (setq string (replace-match rpl t t string))))
28168 string))
28171 (defun org-sublist (list start end)
28172 "Return a section of LIST, from START to END.
28173 Counting starts at 1."
28174 (let (rtn (c start))
28175 (setq list (nthcdr (1- start) list))
28176 (while (and list (<= c end))
28177 (push (pop list) rtn)
28178 (setq c (1+ c)))
28179 (nreverse rtn)))
28181 (defun org-find-base-buffer-visiting (file)
28182 "Like `find-buffer-visiting' but alway return the base buffer and
28183 not an indirect buffer"
28184 (let ((buf (find-buffer-visiting file)))
28185 (if buf
28186 (or (buffer-base-buffer buf) buf)
28187 nil)))
28189 (defun org-image-file-name-regexp ()
28190 "Return regexp matching the file names of images."
28191 (if (fboundp 'image-file-name-regexp)
28192 (image-file-name-regexp)
28193 (let ((image-file-name-extensions
28194 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28195 "xbm" "xpm" "pbm" "pgm" "ppm")))
28196 (concat "\\."
28197 (regexp-opt (nconc (mapcar 'upcase
28198 image-file-name-extensions)
28199 image-file-name-extensions)
28201 "\\'"))))
28203 (defun org-file-image-p (file)
28204 "Return non-nil if FILE is an image."
28205 (save-match-data
28206 (string-match (org-image-file-name-regexp) file)))
28208 ;;; Paragraph filling stuff.
28209 ;; We want this to be just right, so use the full arsenal.
28211 (defun org-indent-line-function ()
28212 "Indent line like previous, but further if previous was headline or item."
28213 (interactive)
28214 (let* ((pos (point))
28215 (itemp (org-at-item-p))
28216 column bpos bcol tpos tcol bullet btype bullet-type)
28217 ;; Find the previous relevant line
28218 (beginning-of-line 1)
28219 (cond
28220 ((looking-at "#") (setq column 0))
28221 ((looking-at "\\*+ ") (setq column 0))
28223 (beginning-of-line 0)
28224 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28225 (beginning-of-line 0))
28226 (cond
28227 ((looking-at "\\*+[ \t]+")
28228 (goto-char (match-end 0))
28229 (setq column (current-column)))
28230 ((org-in-item-p)
28231 (org-beginning-of-item)
28232 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28233 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28234 (setq bpos (match-beginning 1) tpos (match-end 0)
28235 bcol (progn (goto-char bpos) (current-column))
28236 tcol (progn (goto-char tpos) (current-column))
28237 bullet (match-string 1)
28238 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28239 (if (not itemp)
28240 (setq column tcol)
28241 (goto-char pos)
28242 (beginning-of-line 1)
28243 (if (looking-at "\\S-")
28244 (progn
28245 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28246 (setq bullet (match-string 1)
28247 btype (if (string-match "[0-9]" bullet) "n" bullet))
28248 (setq column (if (equal btype bullet-type) bcol tcol)))
28249 (setq column (org-get-indentation)))))
28250 (t (setq column (org-get-indentation))))))
28251 (goto-char pos)
28252 (if (<= (current-column) (current-indentation))
28253 (indent-line-to column)
28254 (save-excursion (indent-line-to column)))
28255 (setq column (current-column))
28256 (beginning-of-line 1)
28257 (if (looking-at
28258 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28259 (replace-match (concat "\\1" (format org-property-format
28260 (match-string 2) (match-string 3)))
28261 t nil))
28262 (move-to-column column)))
28264 (defun org-set-autofill-regexps ()
28265 (interactive)
28266 ;; In the paragraph separator we include headlines, because filling
28267 ;; text in a line directly attached to a headline would otherwise
28268 ;; fill the headline as well.
28269 (org-set-local 'comment-start-skip "^#+[ \t]*")
28270 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28271 ;; The paragraph starter includes hand-formatted lists.
28272 (org-set-local 'paragraph-start
28273 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28274 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28275 ;; But only if the user has not turned off tables or fixed-width regions
28276 (org-set-local
28277 'auto-fill-inhibit-regexp
28278 (concat "\\*+ \\|#\\+"
28279 "\\|[ \t]*" org-keyword-time-regexp
28280 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28281 (concat
28282 "\\|[ \t]*["
28283 (if org-enable-table-editor "|" "")
28284 (if org-enable-fixed-width-editor ":" "")
28285 "]"))))
28286 ;; We use our own fill-paragraph function, to make sure that tables
28287 ;; and fixed-width regions are not wrapped. That function will pass
28288 ;; through to `fill-paragraph' when appropriate.
28289 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28290 ; Adaptive filling: To get full control, first make sure that
28291 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28292 (org-set-local 'adaptive-fill-regexp "\000")
28293 (org-set-local 'adaptive-fill-function
28294 'org-adaptive-fill-function)
28295 (org-set-local
28296 'align-mode-rules-list
28297 '((org-in-buffer-settings
28298 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28299 (modes . '(org-mode))))))
28301 (defun org-fill-paragraph (&optional justify)
28302 "Re-align a table, pass through to fill-paragraph if no table."
28303 (let ((table-p (org-at-table-p))
28304 (table.el-p (org-at-table.el-p)))
28305 (cond ((and (equal (char-after (point-at-bol)) ?*)
28306 (save-excursion (goto-char (point-at-bol))
28307 (looking-at outline-regexp)))
28308 t) ; skip headlines
28309 (table.el-p t) ; skip table.el tables
28310 (table-p (org-table-align) t) ; align org-mode tables
28311 (t nil)))) ; call paragraph-fill
28313 ;; For reference, this is the default value of adaptive-fill-regexp
28314 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28316 (defun org-adaptive-fill-function ()
28317 "Return a fill prefix for org-mode files.
28318 In particular, this makes sure hanging paragraphs for hand-formatted lists
28319 work correctly."
28320 (cond ((looking-at "#[ \t]+")
28321 (match-string 0))
28322 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28323 (save-excursion
28324 (goto-char (match-end 0))
28325 (make-string (current-column) ?\ )))
28326 (t nil)))
28328 ;;;; Functions extending outline functionality
28331 (defun org-beginning-of-line (&optional arg)
28332 "Go to the beginning of the current line. If that is invisible, continue
28333 to a visible line beginning. This makes the function of C-a more intuitive.
28334 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28335 first attempt, and only move to after the tags when the cursor is already
28336 beyond the end of the headline."
28337 (interactive "P")
28338 (let ((pos (point)))
28339 (beginning-of-line 1)
28340 (if (bobp)
28342 (backward-char 1)
28343 (if (org-invisible-p)
28344 (while (and (not (bobp)) (org-invisible-p))
28345 (backward-char 1)
28346 (beginning-of-line 1))
28347 (forward-char 1)))
28348 (when org-special-ctrl-a/e
28349 (cond
28350 ((and (looking-at org-todo-line-regexp)
28351 (= (char-after (match-end 1)) ?\ ))
28352 (goto-char
28353 (if (eq org-special-ctrl-a/e t)
28354 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28355 ((= pos (point)) (match-beginning 3))
28356 (t (point)))
28357 (cond ((> pos (point)) (point))
28358 ((not (eq last-command this-command)) (point))
28359 (t (match-beginning 3))))))
28360 ((org-at-item-p)
28361 (goto-char
28362 (if (eq org-special-ctrl-a/e t)
28363 (cond ((> pos (match-end 4)) (match-end 4))
28364 ((= pos (point)) (match-end 4))
28365 (t (point)))
28366 (cond ((> pos (point)) (point))
28367 ((not (eq last-command this-command)) (point))
28368 (t (match-end 4))))))))))
28370 (defun org-end-of-line (&optional arg)
28371 "Go to the end of the line.
28372 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28373 first attempt, and only move to after the tags when the cursor is already
28374 beyond the end of the headline."
28375 (interactive "P")
28376 (if (or (not org-special-ctrl-a/e)
28377 (not (org-on-heading-p)))
28378 (end-of-line arg)
28379 (let ((pos (point)))
28380 (beginning-of-line 1)
28381 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28382 (if (eq org-special-ctrl-a/e t)
28383 (if (or (< pos (match-beginning 1))
28384 (= pos (match-end 0)))
28385 (goto-char (match-beginning 1))
28386 (goto-char (match-end 0)))
28387 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28388 (goto-char (match-end 0))
28389 (goto-char (match-beginning 1))))
28390 (end-of-line arg)))))
28392 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28393 (define-key org-mode-map "\C-e" 'org-end-of-line)
28395 (defun org-kill-line (&optional arg)
28396 "Kill line, to tags or end of line."
28397 (interactive "P")
28398 (cond
28399 ((or (not org-special-ctrl-k)
28400 (bolp)
28401 (not (org-on-heading-p)))
28402 (call-interactively 'kill-line))
28403 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28404 (kill-region (point) (match-beginning 1))
28405 (org-set-tags nil t))
28406 (t (kill-region (point) (point-at-eol)))))
28408 (define-key org-mode-map "\C-k" 'org-kill-line)
28410 (defun org-invisible-p ()
28411 "Check if point is at a character currently not visible."
28412 ;; Early versions of noutline don't have `outline-invisible-p'.
28413 (if (fboundp 'outline-invisible-p)
28414 (outline-invisible-p)
28415 (get-char-property (point) 'invisible)))
28417 (defun org-invisible-p2 ()
28418 "Check if point is at a character currently not visible."
28419 (save-excursion
28420 (if (and (eolp) (not (bobp))) (backward-char 1))
28421 ;; Early versions of noutline don't have `outline-invisible-p'.
28422 (if (fboundp 'outline-invisible-p)
28423 (outline-invisible-p)
28424 (get-char-property (point) 'invisible))))
28426 (defalias 'org-back-to-heading 'outline-back-to-heading)
28427 (defalias 'org-on-heading-p 'outline-on-heading-p)
28428 (defalias 'org-at-heading-p 'outline-on-heading-p)
28429 (defun org-at-heading-or-item-p ()
28430 (or (org-on-heading-p) (org-at-item-p)))
28432 (defun org-on-target-p ()
28433 (or (org-in-regexp org-radio-target-regexp)
28434 (org-in-regexp org-target-regexp)))
28436 (defun org-up-heading-all (arg)
28437 "Move to the heading line of which the present line is a subheading.
28438 This function considers both visible and invisible heading lines.
28439 With argument, move up ARG levels."
28440 (if (fboundp 'outline-up-heading-all)
28441 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28442 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28444 (defun org-up-heading-safe ()
28445 "Move to the heading line of which the present line is a subheading.
28446 This version will not throw an error. It will return the level of the
28447 headline found, or nil if no higher level is found."
28448 (let ((pos (point)) start-level level
28449 (re (concat "^" outline-regexp)))
28450 (catch 'exit
28451 (outline-back-to-heading t)
28452 (setq start-level (funcall outline-level))
28453 (if (equal start-level 1) (throw 'exit nil))
28454 (while (re-search-backward re nil t)
28455 (setq level (funcall outline-level))
28456 (if (< level start-level) (throw 'exit level)))
28457 nil)))
28459 (defun org-first-sibling-p ()
28460 "Is this heading the first child of its parents?"
28461 (interactive)
28462 (let ((re (concat "^" outline-regexp))
28463 level l)
28464 (unless (org-at-heading-p t)
28465 (error "Not at a heading"))
28466 (setq level (funcall outline-level))
28467 (save-excursion
28468 (if (not (re-search-backward re nil t))
28470 (setq l (funcall outline-level))
28471 (< l level)))))
28473 (defun org-goto-sibling (&optional previous)
28474 "Goto the next sibling, even if it is invisible.
28475 When PREVIOUS is set, go to the previous sibling instead. Returns t
28476 when a sibling was found. When none is found, return nil and don't
28477 move point."
28478 (let ((fun (if previous 're-search-backward 're-search-forward))
28479 (pos (point))
28480 (re (concat "^" outline-regexp))
28481 level l)
28482 (when (condition-case nil (org-back-to-heading t) (error nil))
28483 (setq level (funcall outline-level))
28484 (catch 'exit
28485 (or previous (forward-char 1))
28486 (while (funcall fun re nil t)
28487 (setq l (funcall outline-level))
28488 (when (< l level) (goto-char pos) (throw 'exit nil))
28489 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28490 (goto-char pos)
28491 nil))))
28493 (defun org-show-siblings ()
28494 "Show all siblings of the current headline."
28495 (save-excursion
28496 (while (org-goto-sibling) (org-flag-heading nil)))
28497 (save-excursion
28498 (while (org-goto-sibling 'previous)
28499 (org-flag-heading nil))))
28501 (defun org-show-hidden-entry ()
28502 "Show an entry where even the heading is hidden."
28503 (save-excursion
28504 (org-show-entry)))
28506 (defun org-flag-heading (flag &optional entry)
28507 "Flag the current heading. FLAG non-nil means make invisible.
28508 When ENTRY is non-nil, show the entire entry."
28509 (save-excursion
28510 (org-back-to-heading t)
28511 ;; Check if we should show the entire entry
28512 (if entry
28513 (progn
28514 (org-show-entry)
28515 (save-excursion
28516 (and (outline-next-heading)
28517 (org-flag-heading nil))))
28518 (outline-flag-region (max (point-min) (1- (point)))
28519 (save-excursion (outline-end-of-heading) (point))
28520 flag))))
28522 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28523 ;; This is an exact copy of the original function, but it uses
28524 ;; `org-back-to-heading', to make it work also in invisible
28525 ;; trees. And is uses an invisible-OK argument.
28526 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28527 (org-back-to-heading invisible-OK)
28528 (let ((first t)
28529 (level (funcall outline-level)))
28530 (while (and (not (eobp))
28531 (or first (> (funcall outline-level) level)))
28532 (setq first nil)
28533 (outline-next-heading))
28534 (unless to-heading
28535 (if (memq (preceding-char) '(?\n ?\^M))
28536 (progn
28537 ;; Go to end of line before heading
28538 (forward-char -1)
28539 (if (memq (preceding-char) '(?\n ?\^M))
28540 ;; leave blank line before heading
28541 (forward-char -1))))))
28542 (point))
28544 (defun org-show-subtree ()
28545 "Show everything after this heading at deeper levels."
28546 (outline-flag-region
28547 (point)
28548 (save-excursion
28549 (outline-end-of-subtree) (outline-next-heading) (point))
28550 nil))
28552 (defun org-show-entry ()
28553 "Show the body directly following this heading.
28554 Show the heading too, if it is currently invisible."
28555 (interactive)
28556 (save-excursion
28557 (condition-case nil
28558 (progn
28559 (org-back-to-heading t)
28560 (outline-flag-region
28561 (max (point-min) (1- (point)))
28562 (save-excursion
28563 (re-search-forward
28564 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28565 (or (match-beginning 1) (point-max)))
28566 nil))
28567 (error nil))))
28569 (defun org-make-options-regexp (kwds)
28570 "Make a regular expression for keyword lines."
28571 (concat
28573 "#?[ \t]*\\+\\("
28574 (mapconcat 'regexp-quote kwds "\\|")
28575 "\\):[ \t]*"
28576 "\\(.+\\)"))
28578 ;; Make isearch reveal the necessary context
28579 (defun org-isearch-end ()
28580 "Reveal context after isearch exits."
28581 (when isearch-success ; only if search was successful
28582 (if (featurep 'xemacs)
28583 ;; Under XEmacs, the hook is run in the correct place,
28584 ;; we directly show the context.
28585 (org-show-context 'isearch)
28586 ;; In Emacs the hook runs *before* restoring the overlays.
28587 ;; So we have to use a one-time post-command-hook to do this.
28588 ;; (Emacs 22 has a special variable, see function `org-mode')
28589 (unless (and (boundp 'isearch-mode-end-hook-quit)
28590 isearch-mode-end-hook-quit)
28591 ;; Only when the isearch was not quitted.
28592 (org-add-hook 'post-command-hook 'org-isearch-post-command
28593 'append 'local)))))
28595 (defun org-isearch-post-command ()
28596 "Remove self from hook, and show context."
28597 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28598 (org-show-context 'isearch))
28601 ;;;; Integration with and fixes for other packages
28603 ;;; Imenu support
28605 (defvar org-imenu-markers nil
28606 "All markers currently used by Imenu.")
28607 (make-variable-buffer-local 'org-imenu-markers)
28609 (defun org-imenu-new-marker (&optional pos)
28610 "Return a new marker for use by Imenu, and remember the marker."
28611 (let ((m (make-marker)))
28612 (move-marker m (or pos (point)))
28613 (push m org-imenu-markers)
28616 (defun org-imenu-get-tree ()
28617 "Produce the index for Imenu."
28618 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28619 (setq org-imenu-markers nil)
28620 (let* ((n org-imenu-depth)
28621 (re (concat "^" outline-regexp))
28622 (subs (make-vector (1+ n) nil))
28623 (last-level 0)
28624 m tree level head)
28625 (save-excursion
28626 (save-restriction
28627 (widen)
28628 (goto-char (point-max))
28629 (while (re-search-backward re nil t)
28630 (setq level (org-reduced-level (funcall outline-level)))
28631 (when (<= level n)
28632 (looking-at org-complex-heading-regexp)
28633 (setq head (org-match-string-no-properties 4)
28634 m (org-imenu-new-marker))
28635 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28636 (if (>= level last-level)
28637 (push (cons head m) (aref subs level))
28638 (push (cons head (aref subs (1+ level))) (aref subs level))
28639 (loop for i from (1+ level) to n do (aset subs i nil)))
28640 (setq last-level level)))))
28641 (aref subs 1)))
28643 (eval-after-load "imenu"
28644 '(progn
28645 (add-hook 'imenu-after-jump-hook
28646 (lambda () (org-show-context 'org-goto)))))
28648 ;; Speedbar support
28650 (defun org-speedbar-set-agenda-restriction ()
28651 "Restrict future agenda commands to the location at point in speedbar.
28652 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28653 (interactive)
28654 (let (p m tp np dir txt w)
28655 (cond
28656 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28657 'org-imenu t))
28658 (setq m (get-text-property p 'org-imenu-marker))
28659 (save-excursion
28660 (save-restriction
28661 (set-buffer (marker-buffer m))
28662 (goto-char m)
28663 (org-agenda-set-restriction-lock 'subtree))))
28664 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28665 'speedbar-function 'speedbar-find-file))
28666 (setq tp (previous-single-property-change
28667 (1+ p) 'speedbar-function)
28668 np (next-single-property-change
28669 tp 'speedbar-function)
28670 dir (speedbar-line-directory)
28671 txt (buffer-substring-no-properties (or tp (point-min))
28672 (or np (point-max))))
28673 (save-excursion
28674 (save-restriction
28675 (set-buffer (find-file-noselect
28676 (let ((default-directory dir))
28677 (expand-file-name txt))))
28678 (unless (org-mode-p)
28679 (error "Cannot restrict to non-Org-mode file"))
28680 (org-agenda-set-restriction-lock 'file))))
28681 (t (error "Don't know how to restrict Org-mode's agenda")))
28682 (org-move-overlay org-speedbar-restriction-lock-overlay
28683 (point-at-bol) (point-at-eol))
28684 (setq current-prefix-arg nil)
28685 (org-agenda-maybe-redo)))
28687 (eval-after-load "speedbar"
28688 '(progn
28689 (speedbar-add-supported-extension ".org")
28690 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28691 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28692 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28693 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28694 (add-hook 'speedbar-visiting-tag-hook
28695 (lambda () (org-show-context 'org-goto)))))
28698 ;;; Fixes and Hacks
28700 ;; Make flyspell not check words in links, to not mess up our keymap
28701 (defun org-mode-flyspell-verify ()
28702 "Don't let flyspell put overlays at active buttons."
28703 (not (get-text-property (point) 'keymap)))
28705 ;; Make `bookmark-jump' show the jump location if it was hidden.
28706 (eval-after-load "bookmark"
28707 '(if (boundp 'bookmark-after-jump-hook)
28708 ;; We can use the hook
28709 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28710 ;; Hook not available, use advice
28711 (defadvice bookmark-jump (after org-make-visible activate)
28712 "Make the position visible."
28713 (org-bookmark-jump-unhide))))
28715 (defun org-bookmark-jump-unhide ()
28716 "Unhide the current position, to show the bookmark location."
28717 (and (org-mode-p)
28718 (or (org-invisible-p)
28719 (save-excursion (goto-char (max (point-min) (1- (point))))
28720 (org-invisible-p)))
28721 (org-show-context 'bookmark-jump)))
28723 ;; Fix a bug in htmlize where there are text properties (face nil)
28724 (eval-after-load "htmlize"
28725 '(progn
28726 (defadvice htmlize-faces-in-buffer (after org-no-nil-faces activate)
28727 "Make sure there are no nil faces"
28728 (setq ad-return-value (delq nil ad-return-value)))))
28730 ;; Make session.el ignore our circular variable
28731 (eval-after-load "session"
28732 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28734 ;;;; Experimental code
28736 (defun org-closed-in-range ()
28737 "Sparse tree of items closed in a certain time range.
28738 Still experimental, may disappear in the future."
28739 (interactive)
28740 ;; Get the time interval from the user.
28741 (let* ((time1 (time-to-seconds
28742 (org-read-date nil 'to-time nil "Starting date: ")))
28743 (time2 (time-to-seconds
28744 (org-read-date nil 'to-time nil "End date:")))
28745 ;; callback function
28746 (callback (lambda ()
28747 (let ((time
28748 (time-to-seconds
28749 (apply 'encode-time
28750 (org-parse-time-string
28751 (match-string 1))))))
28752 ;; check if time in interval
28753 (and (>= time time1) (<= time time2))))))
28754 ;; make tree, check each match with the callback
28755 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28757 ;;;; Finish up
28759 (provide 'org)
28761 (run-hooks 'org-load-hook)
28763 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28764 ;;; org.el ends here