Applied Glenn Morris patch.
[org-mode.git] / org.el
blob4498a171583bf6a02148966fd20234605b09c556
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 (defcustom org-load-hook nil
155 "Hook that is run after org.el has been loaded."
156 :group 'org
157 :type 'hook)
159 (defcustom org-default-extensions '(org-irc)
160 "Extensions that should always be loaded together with org.el.
161 If the description starts with <A>, this means the extension
162 will be autoloaded when needed, preloading is not necessary."
163 :group 'org
164 :type
165 '(set :greedy t
166 (const :tag " Mouse support (org-mouse.el)" org-mouse)
167 (const :tag "<A> Publishing (org-publish.el)" org-publish)
168 (const :tag "<A> LaTeX export (org-export-latex.el)" org-export-latex)
169 (const :tag " IRC/ERC links (org-irc.el)" org-irc)
170 (const :tag " Apple Mail message links under OS X (org-mac-message.el)" org-mac-message)))
172 (defun org-load-default-extensions ()
173 "Load all extensions listed in `org-default-extensions'."
174 (mapc (lambda (ext)
175 (condition-case nil (require ext)
176 (error (message "Problems while trying to load feature `%s'" ext))))
177 org-default-extensions))
179 (eval-after-load "org" '(org-load-default-extensions))
181 ;; FIXME: Needs a separate group...
182 (defcustom org-completion-fallback-command 'hippie-expand
183 "The expansion command called by \\[org-complete] in normal context.
184 Normal means, no org-mode-specific context."
185 :group 'org
186 :type 'function)
188 (defgroup org-startup nil
189 "Options concerning startup of Org-mode."
190 :tag "Org Startup"
191 :group 'org)
193 (defcustom org-startup-folded t
194 "Non-nil means, entering Org-mode will switch to OVERVIEW.
195 This can also be configured on a per-file basis by adding one of
196 the following lines anywhere in the buffer:
198 #+STARTUP: fold
199 #+STARTUP: nofold
200 #+STARTUP: content"
201 :group 'org-startup
202 :type '(choice
203 (const :tag "nofold: show all" nil)
204 (const :tag "fold: overview" t)
205 (const :tag "content: all headlines" content)))
207 (defcustom org-startup-truncated t
208 "Non-nil means, entering Org-mode will set `truncate-lines'.
209 This is useful since some lines containing links can be very long and
210 uninteresting. Also tables look terrible when wrapped."
211 :group 'org-startup
212 :type 'boolean)
214 (defcustom org-startup-align-all-tables nil
215 "Non-nil means, align all tables when visiting a file.
216 This is useful when the column width in tables is forced with <N> cookies
217 in table fields. Such tables will look correct only after the first re-align.
218 This can also be configured on a per-file basis by adding one of
219 the following lines anywhere in the buffer:
220 #+STARTUP: align
221 #+STARTUP: noalign"
222 :group 'org-startup
223 :type 'boolean)
225 (defcustom org-insert-mode-line-in-empty-file nil
226 "Non-nil means insert the first line setting Org-mode in empty files.
227 When the function `org-mode' is called interactively in an empty file, this
228 normally means that the file name does not automatically trigger Org-mode.
229 To ensure that the file will always be in Org-mode in the future, a
230 line enforcing Org-mode will be inserted into the buffer, if this option
231 has been set."
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-replace-disputed-keys nil
236 "Non-nil means use alternative key bindings for some keys.
237 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
238 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
239 If you want to use Org-mode together with one of these other modes,
240 or more generally if you would like to move some Org-mode commands to
241 other keys, set this variable and configure the keys with the variable
242 `org-disputed-keys'.
244 This option is only relevant at load-time of Org-mode, and must be set
245 *before* org.el is loaded. Changing it requires a restart of Emacs to
246 become effective."
247 :group 'org-startup
248 :type 'boolean)
250 (if (fboundp 'defvaralias)
251 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
253 (defcustom org-disputed-keys
254 '(([(shift up)] . [(meta p)])
255 ([(shift down)] . [(meta n)])
256 ([(shift left)] . [(meta -)])
257 ([(shift right)] . [(meta +)])
258 ([(control shift right)] . [(meta shift +)])
259 ([(control shift left)] . [(meta shift -)]))
260 "Keys for which Org-mode and other modes compete.
261 This is an alist, cars are the default keys, second element specifies
262 the alternative to use when `org-replace-disputed-keys' is t.
264 Keys can be specified in any syntax supported by `define-key'.
265 The value of this option takes effect only at Org-mode's startup,
266 therefore you'll have to restart Emacs to apply it after changing."
267 :group 'org-startup
268 :type 'alist)
270 (defun org-key (key)
271 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
272 Or return the original if not disputed."
273 (if org-replace-disputed-keys
274 (let* ((nkey (key-description key))
275 (x (org-find-if (lambda (x)
276 (equal (key-description (car x)) nkey))
277 org-disputed-keys)))
278 (if x (cdr x) key))
279 key))
281 (defun org-find-if (predicate seq)
282 (catch 'exit
283 (while seq
284 (if (funcall predicate (car seq))
285 (throw 'exit (car seq))
286 (pop seq)))))
288 (defun org-defkey (keymap key def)
289 "Define a key, possibly translated, as returned by `org-key'."
290 (define-key keymap (org-key key) def))
292 (defcustom org-ellipsis nil
293 "The ellipsis to use in the Org-mode outline.
294 When nil, just use the standard three dots. When a string, use that instead,
295 When a face, use the standart 3 dots, but with the specified face.
296 The change affects only Org-mode (which will then use its own display table).
297 Changing this requires executing `M-x org-mode' in a buffer to become
298 effective."
299 :group 'org-startup
300 :type '(choice (const :tag "Default" nil)
301 (face :tag "Face" :value org-warning)
302 (string :tag "String" :value "...#")))
304 (defvar org-display-table nil
305 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
307 (defgroup org-keywords nil
308 "Keywords in Org-mode."
309 :tag "Org Keywords"
310 :group 'org)
312 (defcustom org-deadline-string "DEADLINE:"
313 "String to mark deadline entries.
314 A deadline is this string, followed by a time stamp. Should be a word,
315 terminated by a colon. You can insert a schedule keyword and
316 a timestamp with \\[org-deadline].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-scheduled-string "SCHEDULED:"
322 "String to mark scheduled TODO entries.
323 A schedule is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-schedule].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-closed-string "CLOSED:"
331 "String used as the prefix for timestamps logging closing a TODO entry."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-clock-string "CLOCK:"
336 "String used as prefix for timestamps clocking work hours on an item."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-comment-string "COMMENT"
341 "Entries starting with this keyword will never be exported.
342 An entry can be toggled between COMMENT and normal with
343 \\[org-toggle-comment].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-quote-string "QUOTE"
349 "Entries starting with this keyword will be exported in fixed-width font.
350 Quoting applies only to the text in the entry following the headline, and does
351 not extend beyond the next headline, even if that is lower level.
352 An entry can be toggled between QUOTE and normal with
353 \\[org-toggle-fixed-width-section]."
354 :group 'org-keywords
355 :type 'string)
357 (defconst org-repeat-re
358 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
359 "Regular expression for specifying repeated events.
360 After a match, group 1 contains the repeat expression.")
362 (defgroup org-structure nil
363 "Options concerning the general structure of Org-mode files."
364 :tag "Org Structure"
365 :group 'org)
367 (defgroup org-reveal-location nil
368 "Options about how to make context of a location visible."
369 :tag "Org Reveal Location"
370 :group 'org-structure)
372 (defconst org-context-choice
373 '(choice
374 (const :tag "Always" t)
375 (const :tag "Never" nil)
376 (repeat :greedy t :tag "Individual contexts"
377 (cons
378 (choice :tag "Context"
379 (const agenda)
380 (const org-goto)
381 (const occur-tree)
382 (const tags-tree)
383 (const link-search)
384 (const mark-goto)
385 (const bookmark-jump)
386 (const isearch)
387 (const default))
388 (boolean))))
389 "Contexts for the reveal options.")
391 (defcustom org-show-hierarchy-above '((default . t))
392 "Non-nil means, show full hierarchy when revealing a location.
393 Org-mode often shows locations in an org-mode file which might have
394 been invisible before. When this is set, the hierarchy of headings
395 above the exposed location is shown.
396 Turning this off for example for sparse trees makes them very compact.
397 Instead of t, this can also be an alist specifying this option for different
398 contexts. Valid contexts are
399 agenda when exposing an entry from the agenda
400 org-goto when using the command `org-goto' on key C-c C-j
401 occur-tree when using the command `org-occur' on key C-c /
402 tags-tree when constructing a sparse tree based on tags matches
403 link-search when exposing search matches associated with a link
404 mark-goto when exposing the jump goal of a mark
405 bookmark-jump when exposing a bookmark location
406 isearch when exiting from an incremental search
407 default default for all contexts not set explicitly"
408 :group 'org-reveal-location
409 :type org-context-choice)
411 (defcustom org-show-following-heading '((default . nil))
412 "Non-nil means, show following heading when revealing a location.
413 Org-mode often shows locations in an org-mode file which might have
414 been invisible before. When this is set, the heading following the
415 match is shown.
416 Turning this off for example for sparse trees makes them very compact,
417 but makes it harder to edit the location of the match. In such a case,
418 use the command \\[org-reveal] to show more context.
419 Instead of t, this can also be an alist specifying this option for different
420 contexts. See `org-show-hierarchy-above' for valid contexts."
421 :group 'org-reveal-location
422 :type org-context-choice)
424 (defcustom org-show-siblings '((default . nil) (isearch t))
425 "Non-nil means, show all sibling heading when revealing a location.
426 Org-mode often shows locations in an org-mode file which might have
427 been invisible before. When this is set, the sibling of the current entry
428 heading are all made visible. If `org-show-hierarchy-above' is t,
429 the same happens on each level of the hierarchy above the current entry.
431 By default this is on for the isearch context, off for all other contexts.
432 Turning this off for example for sparse trees makes them very compact,
433 but makes it harder to edit the location of the match. In such a case,
434 use the command \\[org-reveal] to show more context.
435 Instead of t, this can also be an alist specifying this option for different
436 contexts. See `org-show-hierarchy-above' for valid contexts."
437 :group 'org-reveal-location
438 :type org-context-choice)
440 (defcustom org-show-entry-below '((default . nil))
441 "Non-nil means, show the entry below a headline when revealing a location.
442 Org-mode often shows locations in an org-mode file which might have
443 been invisible before. When this is set, the text below the headline that is
444 exposed is also shown.
446 By default this is off for all contexts.
447 Instead of t, this can also be an alist specifying this option for different
448 contexts. See `org-show-hierarchy-above' for valid contexts."
449 :group 'org-reveal-location
450 :type org-context-choice)
452 (defgroup org-cycle nil
453 "Options concerning visibility cycling in Org-mode."
454 :tag "Org Cycle"
455 :group 'org-structure)
457 (defcustom org-drawers '("PROPERTIES" "CLOCK")
458 "Names of drawers. Drawers are not opened by cycling on the headline above.
459 Drawers only open with a TAB on the drawer line itself. A drawer looks like
460 this:
461 :DRAWERNAME:
462 .....
463 :END:
464 The drawer \"PROPERTIES\" is special for capturing properties through
465 the property API.
467 Drawers can be defined on the per-file basis with a line like:
469 #+DRAWERS: HIDDEN STATE PROPERTIES"
470 :group 'org-structure
471 :type '(repeat (string :tag "Drawer Name")))
473 (defcustom org-cycle-global-at-bob nil
474 "Cycle globally if cursor is at beginning of buffer and not at a headline.
475 This makes it possible to do global cycling without having to use S-TAB or
476 C-u TAB. For this special case to work, the first line of the buffer
477 must not be a headline - it may be empty ot some other text. When used in
478 this way, `org-cycle-hook' is disables temporarily, to make sure the
479 cursor stays at the beginning of the buffer.
480 When this option is nil, don't do anything special at the beginning
481 of the buffer."
482 :group 'org-cycle
483 :type 'boolean)
485 (defcustom org-cycle-emulate-tab t
486 "Where should `org-cycle' emulate TAB.
487 nil Never
488 white Only in completely white lines
489 whitestart Only at the beginning of lines, before the first non-white char
490 t Everywhere except in headlines
491 exc-hl-bol Everywhere except at the start of a headline
492 If TAB is used in a place where it does not emulate TAB, the current subtree
493 visibility is cycled."
494 :group 'org-cycle
495 :type '(choice (const :tag "Never" nil)
496 (const :tag "Only in completely white lines" white)
497 (const :tag "Before first char in a line" whitestart)
498 (const :tag "Everywhere except in headlines" t)
499 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
502 (defcustom org-cycle-separator-lines 2
503 "Number of empty lines needed to keep an empty line between collapsed trees.
504 If you leave an empty line between the end of a subtree and the following
505 headline, this empty line is hidden when the subtree is folded.
506 Org-mode will leave (exactly) one empty line visible if the number of
507 empty lines is equal or larger to the number given in this variable.
508 So the default 2 means, at least 2 empty lines after the end of a subtree
509 are needed to produce free space between a collapsed subtree and the
510 following headline.
512 Special case: when 0, never leave empty lines in collapsed view."
513 :group 'org-cycle
514 :type 'integer)
516 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
517 org-cycle-hide-drawers
518 org-cycle-show-empty-lines
519 org-optimize-window-after-visibility-change)
520 "Hook that is run after `org-cycle' has changed the buffer visibility.
521 The function(s) in this hook must accept a single argument which indicates
522 the new state that was set by the most recent `org-cycle' command. The
523 argument is a symbol. After a global state change, it can have the values
524 `overview', `content', or `all'. After a local state change, it can have
525 the values `folded', `children', or `subtree'."
526 :group 'org-cycle
527 :type 'hook)
529 (defgroup org-edit-structure nil
530 "Options concerning structure editing in Org-mode."
531 :tag "Org Edit Structure"
532 :group 'org-structure)
534 (defcustom org-odd-levels-only nil
535 "Non-nil means, skip even levels and only use odd levels for the outline.
536 This has the effect that two stars are being added/taken away in
537 promotion/demotion commands. It also influences how levels are
538 handled by the exporters.
539 Changing it requires restart of `font-lock-mode' to become effective
540 for fontification also in regions already fontified.
541 You may also set this on a per-file basis by adding one of the following
542 lines to the buffer:
544 #+STARTUP: odd
545 #+STARTUP: oddeven"
546 :group 'org-edit-structure
547 :group 'org-font-lock
548 :type 'boolean)
550 (defcustom org-adapt-indentation t
551 "Non-nil means, adapt indentation when promoting and demoting.
552 When this is set and the *entire* text in an entry is indented, the
553 indentation is increased by one space in a demotion command, and
554 decreased by one in a promotion command. If any line in the entry
555 body starts at column 0, indentation is not changed at all."
556 :group 'org-edit-structure
557 :type 'boolean)
559 (defcustom org-special-ctrl-a/e nil
560 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
561 When t, `C-a' will bring back the cursor to the beginning of the
562 headline text, i.e. after the stars and after a possible TODO keyword.
563 In an item, this will be the position after the bullet.
564 When the cursor is already at that position, another `C-a' will bring
565 it to the beginning of the line.
566 `C-e' will jump to the end of the headline, ignoring the presence of tags
567 in the headline. A second `C-e' will then jump to the true end of the
568 line, after any tags.
569 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
570 and only a directly following, identical keypress will bring the cursor
571 to the special positions."
572 :group 'org-edit-structure
573 :type '(choice
574 (const :tag "off" nil)
575 (const :tag "after bullet first" t)
576 (const :tag "border first" reversed)))
578 (if (fboundp 'defvaralias)
579 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
581 (defcustom org-special-ctrl-k nil
582 "Non-nil means `C-k' will behave specially in headlines.
583 When nil, `C-k' will call the default `kill-line' command.
584 When t, the following will happen while the cursor is in the headline:
586 - When the cursor is at the beginning of a headline, kill the entire
587 line and possible the folded subtree below the line.
588 - When in the middle of the headline text, kill the headline up to the tags.
589 - When after the headline text, kill the tags."
590 :group 'org-edit-structure
591 :type 'boolean)
593 (defcustom org-M-RET-may-split-line '((default . t))
594 "Non-nil means, M-RET will split the line at the cursor position.
595 When nil, it will go to the end of the line before making a
596 new line.
597 You may also set this option in a different way for different
598 contexts. Valid contexts are:
600 headline when creating a new headline
601 item when creating a new item
602 table in a table field
603 default the value to be used for all contexts not explicitly
604 customized"
605 :group 'org-structure
606 :group 'org-table
607 :type '(choice
608 (const :tag "Always" t)
609 (const :tag "Never" nil)
610 (repeat :greedy t :tag "Individual contexts"
611 (cons
612 (choice :tag "Context"
613 (const headline)
614 (const item)
615 (const table)
616 (const default))
617 (boolean)))))
620 (defcustom org-blank-before-new-entry '((heading . nil)
621 (plain-list-item . nil))
622 "Should `org-insert-heading' leave a blank line before new heading/item?
623 The value is an alist, with `heading' and `plain-list-item' as car,
624 and a boolean flag as cdr."
625 :group 'org-edit-structure
626 :type '(list
627 (cons (const heading) (boolean))
628 (cons (const plain-list-item) (boolean))))
630 (defcustom org-insert-heading-hook nil
631 "Hook being run after inserting a new heading."
632 :group 'org-edit-structure
633 :type 'hook)
635 (defcustom org-enable-fixed-width-editor t
636 "Non-nil means, lines starting with \":\" are treated as fixed-width.
637 This currently only means, they are never auto-wrapped.
638 When nil, such lines will be treated like ordinary lines.
639 See also the QUOTE keyword."
640 :group 'org-edit-structure
641 :type 'boolean)
643 (defcustom org-goto-auto-isearch t
644 "Non-nil means, typing characters in org-goto starts incremental search."
645 :group 'org-edit-structure
646 :type 'boolean)
648 (defgroup org-sparse-trees nil
649 "Options concerning sparse trees in Org-mode."
650 :tag "Org Sparse Trees"
651 :group 'org-structure)
653 (defcustom org-highlight-sparse-tree-matches t
654 "Non-nil means, highlight all matches that define a sparse tree.
655 The highlights will automatically disappear the next time the buffer is
656 changed by an edit command."
657 :group 'org-sparse-trees
658 :type 'boolean)
660 (defcustom org-remove-highlights-with-change t
661 "Non-nil means, any change to the buffer will remove temporary highlights.
662 Such highlights are created by `org-occur' and `org-clock-display'.
663 When nil, `C-c C-c needs to be used to get rid of the highlights.
664 The highlights created by `org-preview-latex-fragment' always need
665 `C-c C-c' to be removed."
666 :group 'org-sparse-trees
667 :group 'org-time
668 :type 'boolean)
671 (defcustom org-occur-hook '(org-first-headline-recenter)
672 "Hook that is run after `org-occur' has constructed a sparse tree.
673 This can be used to recenter the window to show as much of the structure
674 as possible."
675 :group 'org-sparse-trees
676 :type 'hook)
678 (defgroup org-plain-lists nil
679 "Options concerning plain lists in Org-mode."
680 :tag "Org Plain lists"
681 :group 'org-structure)
683 (defcustom org-cycle-include-plain-lists nil
684 "Non-nil means, include plain lists into visibility cycling.
685 This means that during cycling, plain list items will *temporarily* be
686 interpreted as outline headlines with a level given by 1000+i where i is the
687 indentation of the bullet. In all other operations, plain list items are
688 not seen as headlines. For example, you cannot assign a TODO keyword to
689 such an item."
690 :group 'org-plain-lists
691 :type 'boolean)
693 (defcustom org-plain-list-ordered-item-terminator t
694 "The character that makes a line with leading number an ordered list item.
695 Valid values are ?. and ?\). To get both terminators, use t. While
696 ?. may look nicer, it creates the danger that a line with leading
697 number may be incorrectly interpreted as an item. ?\) therefore is
698 the safe choice."
699 :group 'org-plain-lists
700 :type '(choice (const :tag "dot like in \"2.\"" ?.)
701 (const :tag "paren like in \"2)\"" ?\))
702 (const :tab "both" t)))
704 (defcustom org-auto-renumber-ordered-lists t
705 "Non-nil means, automatically renumber ordered plain lists.
706 Renumbering happens when the sequence have been changed with
707 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
708 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
709 :group 'org-plain-lists
710 :type 'boolean)
712 (defcustom org-provide-checkbox-statistics t
713 "Non-nil means, update checkbox statistics after insert and toggle.
714 When this is set, checkbox statistics is updated each time you either insert
715 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
716 with \\[org-ctrl-c-ctrl-c\\]."
717 :group 'org-plain-lists
718 :type 'boolean)
720 (defgroup org-archive nil
721 "Options concerning archiving in Org-mode."
722 :tag "Org Archive"
723 :group 'org-structure)
725 (defcustom org-archive-tag "ARCHIVE"
726 "The tag that marks a subtree as archived.
727 An archived subtree does not open during visibility cycling, and does
728 not contribute to the agenda listings.
729 After changing this, font-lock must be restarted in the relevant buffers to
730 get the proper fontification."
731 :group 'org-archive
732 :group 'org-keywords
733 :type 'string)
735 (defcustom org-agenda-skip-archived-trees t
736 "Non-nil means, the agenda will skip any items located in archived trees.
737 An archived tree is a tree marked with the tag ARCHIVE."
738 :group 'org-archive
739 :group 'org-agenda-skip
740 :type 'boolean)
742 (defcustom org-cycle-open-archived-trees nil
743 "Non-nil means, `org-cycle' will open archived trees.
744 An archived tree is a tree marked with the tag ARCHIVE.
745 When nil, archived trees will stay folded. You can still open them with
746 normal outline commands like `show-all', but not with the cycling commands."
747 :group 'org-archive
748 :group 'org-cycle
749 :type 'boolean)
751 (defcustom org-sparse-tree-open-archived-trees nil
752 "Non-nil means sparse tree construction shows matches in archived trees.
753 When nil, matches in these trees are highlighted, but the trees are kept in
754 collapsed state."
755 :group 'org-archive
756 :group 'org-sparse-trees
757 :type 'boolean)
759 (defcustom org-archive-location "%s_archive::"
760 "The location where subtrees should be archived.
761 This string consists of two parts, separated by a double-colon.
763 The first part is a file name - when omitted, archiving happens in the same
764 file. %s will be replaced by the current file name (without directory part).
765 Archiving to a different file is useful to keep archived entries from
766 contributing to the Org-mode Agenda.
768 The part after the double colon is a headline. The archived entries will be
769 filed under that headline. When omitted, the subtrees are simply filed away
770 at the end of the file, as top-level entries.
772 Here are a few examples:
773 \"%s_archive::\"
774 If the current file is Projects.org, archive in file
775 Projects.org_archive, as top-level trees. This is the default.
777 \"::* Archived Tasks\"
778 Archive in the current file, under the top-level headline
779 \"* Archived Tasks\".
781 \"~/org/archive.org::\"
782 Archive in file ~/org/archive.org (absolute path), as top-level trees.
784 \"basement::** Finished Tasks\"
785 Archive in file ./basement (relative path), as level 3 trees
786 below the level 2 heading \"** Finished Tasks\".
788 You may set this option on a per-file basis by adding to the buffer a
789 line like
791 #+ARCHIVE: basement::** Finished Tasks"
792 :group 'org-archive
793 :type 'string)
795 (defcustom org-archive-mark-done t
796 "Non-nil means, mark entries as DONE when they are moved to the archive file.
797 This can be a string to set the keyword to use. When t, Org-mode will
798 use the first keyword in its list that means done."
799 :group 'org-archive
800 :type '(choice
801 (const :tag "No" nil)
802 (const :tag "Yes" t)
803 (string :tag "Use this keyword")))
805 (defcustom org-archive-stamp-time t
806 "Non-nil means, add a time stamp to entries moved to an archive file.
807 This variable is obsolete and has no effect anymore, instead add ot remove
808 `time' from the variablle `org-archive-save-context-info'."
809 :group 'org-archive
810 :type 'boolean)
812 (defcustom org-archive-save-context-info '(time file olpath category todo itags)
813 "Parts of context info that should be stored as properties when archiving.
814 When a subtree is moved to an archive file, it looses information given by
815 context, like inherited tags, the category, and possibly also the TODO
816 state (depending on the variable `org-archive-mark-done').
817 This variable can be a list of any of the following symbols:
819 time The time of archiving.
820 file The file where the entry originates.
821 itags The local tags, in the headline of the subtree.
822 ltags The tags the subtree inherits from further up the hierarchy.
823 todo The pre-archive TODO state.
824 category The category, taken from file name or #+CATEGORY lines.
825 olpath The outline path to the item. These are all headlines above
826 the current item, separated by /, like a file path.
828 For each symbol present in the list, a property will be created in
829 the archived entry, with a prefix \"PRE_ARCHIVE_\", to remember this
830 information."
831 :group 'org-archive
832 :type '(set :greedy t
833 (const :tag "Time" time)
834 (const :tag "File" file)
835 (const :tag "Category" category)
836 (const :tag "TODO state" todo)
837 (const :tag "TODO state" priority)
838 (const :tag "Inherited tags" itags)
839 (const :tag "Outline path" olpath)
840 (const :tag "Local tags" ltags)))
842 (defgroup org-imenu-and-speedbar nil
843 "Options concerning imenu and speedbar in Org-mode."
844 :tag "Org Imenu and Speedbar"
845 :group 'org-structure)
847 (defcustom org-imenu-depth 2
848 "The maximum level for Imenu access to Org-mode headlines.
849 This also applied for speedbar access."
850 :group 'org-imenu-and-speedbar
851 :type 'number)
853 (defgroup org-table nil
854 "Options concerning tables in Org-mode."
855 :tag "Org Table"
856 :group 'org)
858 (defcustom org-enable-table-editor 'optimized
859 "Non-nil means, lines starting with \"|\" are handled by the table editor.
860 When nil, such lines will be treated like ordinary lines.
862 When equal to the symbol `optimized', the table editor will be optimized to
863 do the following:
864 - Automatic overwrite mode in front of whitespace in table fields.
865 This makes the structure of the table stay in tact as long as the edited
866 field does not exceed the column width.
867 - Minimize the number of realigns. Normally, the table is aligned each time
868 TAB or RET are pressed to move to another field. With optimization this
869 happens only if changes to a field might have changed the column width.
870 Optimization requires replacing the functions `self-insert-command',
871 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
872 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
873 very good at guessing when a re-align will be necessary, but you can always
874 force one with \\[org-ctrl-c-ctrl-c].
876 If you would like to use the optimized version in Org-mode, but the
877 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
879 This variable can be used to turn on and off the table editor during a session,
880 but in order to toggle optimization, a restart is required.
882 See also the variable `org-table-auto-blank-field'."
883 :group 'org-table
884 :type '(choice
885 (const :tag "off" nil)
886 (const :tag "on" t)
887 (const :tag "on, optimized" optimized)))
889 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
890 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
891 In the optimized version, the table editor takes over all simple keys that
892 normally just insert a character. In tables, the characters are inserted
893 in a way to minimize disturbing the table structure (i.e. in overwrite mode
894 for empty fields). Outside tables, the correct binding of the keys is
895 restored.
897 The default for this option is t if the optimized version is also used in
898 Org-mode. See the variable `org-enable-table-editor' for details. Changing
899 this variable requires a restart of Emacs to become effective."
900 :group 'org-table
901 :type 'boolean)
903 (defcustom orgtbl-radio-table-templates
904 '((latex-mode "% BEGIN RECEIVE ORGTBL %n
905 % END RECEIVE ORGTBL %n
906 \\begin{comment}
907 #+ORGTBL: SEND %n orgtbl-to-latex :splice nil :skip 0
908 | | |
909 \\end{comment}\n")
910 (texinfo-mode "@c BEGIN RECEIVE ORGTBL %n
911 @c END RECEIVE ORGTBL %n
912 @ignore
913 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
914 | | |
915 @end ignore\n")
916 (html-mode "<!-- BEGIN RECEIVE ORGTBL %n -->
917 <!-- END RECEIVE ORGTBL %n -->
918 <!--
919 #+ORGTBL: SEND %n orgtbl-to-html :splice nil :skip 0
920 | | |
921 -->\n"))
922 "Templates for radio tables in different major modes.
923 All occurrences of %n in a template will be replaced with the name of the
924 table, obtained by prompting the user."
925 :group 'org-table
926 :type '(repeat
927 (list (symbol :tag "Major mode")
928 (string :tag "Format"))))
930 (defgroup org-table-settings nil
931 "Settings for tables in Org-mode."
932 :tag "Org Table Settings"
933 :group 'org-table)
935 (defcustom org-table-default-size "5x2"
936 "The default size for newly created tables, Columns x Rows."
937 :group 'org-table-settings
938 :type 'string)
940 (defcustom org-table-number-regexp
941 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%:]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$"
942 "Regular expression for recognizing numbers in table columns.
943 If a table column contains mostly numbers, it will be aligned to the
944 right. If not, it will be aligned to the left.
946 The default value of this option is a regular expression which allows
947 anything which looks remotely like a number as used in scientific
948 context. For example, all of the following will be considered a
949 number:
950 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
952 Other options offered by the customize interface are more restrictive."
953 :group 'org-table-settings
954 :type '(choice
955 (const :tag "Positive Integers"
956 "^[0-9]+$")
957 (const :tag "Integers"
958 "^[-+]?[0-9]+$")
959 (const :tag "Floating Point Numbers"
960 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
961 (const :tag "Floating Point Number or Integer"
962 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
963 (const :tag "Exponential, Floating point, Integer"
964 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
965 (const :tag "Very General Number-Like, including hex"
966 "^\\([<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*\\|\\(0[xX]\\)[0-9a-fA-F]+\\|nan\\)$")
967 (string :tag "Regexp:")))
969 (defcustom org-table-number-fraction 0.5
970 "Fraction of numbers in a column required to make the column align right.
971 In a column all non-white fields are considered. If at least this
972 fraction of fields is matched by `org-table-number-fraction',
973 alignment to the right border applies."
974 :group 'org-table-settings
975 :type 'number)
977 (defgroup org-table-editing nil
978 "Behavior of tables during editing in Org-mode."
979 :tag "Org Table Editing"
980 :group 'org-table)
982 (defcustom org-table-automatic-realign t
983 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
984 When nil, aligning is only done with \\[org-table-align], or after column
985 removal/insertion."
986 :group 'org-table-editing
987 :type 'boolean)
989 (defcustom org-table-auto-blank-field t
990 "Non-nil means, automatically blank table field when starting to type into it.
991 This only happens when typing immediately after a field motion
992 command (TAB, S-TAB or RET).
993 Only relevant when `org-enable-table-editor' is equal to `optimized'."
994 :group 'org-table-editing
995 :type 'boolean)
997 (defcustom org-table-tab-jumps-over-hlines t
998 "Non-nil means, tab in the last column of a table with jump over a hline.
999 If a horizontal separator line is following the current line,
1000 `org-table-next-field' can either create a new row before that line, or jump
1001 over the line. When this option is nil, a new line will be created before
1002 this line."
1003 :group 'org-table-editing
1004 :type 'boolean)
1006 (defcustom org-table-tab-recognizes-table.el t
1007 "Non-nil means, TAB will automatically notice a table.el table.
1008 When it sees such a table, it moves point into it and - if necessary -
1009 calls `table-recognize-table'."
1010 :group 'org-table-editing
1011 :type 'boolean)
1013 (defgroup org-table-calculation nil
1014 "Options concerning tables in Org-mode."
1015 :tag "Org Table Calculation"
1016 :group 'org-table)
1018 (defcustom org-table-use-standard-references t
1019 "Should org-mode work with table refrences like B3 instead of @3$2?
1020 Possible values are:
1021 nil never use them
1022 from accept as input, do not present for editing
1023 t: accept as input and present for editing"
1024 :group 'org-table-calculation
1025 :type '(choice
1026 (const :tag "Never, don't even check unser input for them" nil)
1027 (const :tag "Always, both as user input, and when editing" t)
1028 (const :tag "Convert user input, don't offer during editing" 'from)))
1030 (defcustom org-table-copy-increment t
1031 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1032 :group 'org-table-calculation
1033 :type 'boolean)
1035 (defcustom org-calc-default-modes
1036 '(calc-internal-prec 12
1037 calc-float-format (float 5)
1038 calc-angle-mode deg
1039 calc-prefer-frac nil
1040 calc-symbolic-mode nil
1041 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1042 calc-display-working-message t
1044 "List with Calc mode settings for use in calc-eval for table formulas.
1045 The list must contain alternating symbols (Calc modes variables and values).
1046 Don't remove any of the default settings, just change the values. Org-mode
1047 relies on the variables to be present in the list."
1048 :group 'org-table-calculation
1049 :type 'plist)
1051 (defcustom org-table-formula-evaluate-inline t
1052 "Non-nil means, TAB and RET evaluate a formula in current table field.
1053 If the current field starts with an equal sign, it is assumed to be a formula
1054 which should be evaluated as described in the manual and in the documentation
1055 string of the command `org-table-eval-formula'. This feature requires the
1056 Emacs calc package.
1057 When this variable is nil, formula calculation is only available through
1058 the command \\[org-table-eval-formula]."
1059 :group 'org-table-calculation
1060 :type 'boolean)
1062 (defcustom org-table-formula-use-constants t
1063 "Non-nil means, interpret constants in formulas in tables.
1064 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1065 by the value given in `org-table-formula-constants', or by a value obtained
1066 from the `constants.el' package."
1067 :group 'org-table-calculation
1068 :type 'boolean)
1070 (defcustom org-table-formula-constants nil
1071 "Alist with constant names and values, for use in table formulas.
1072 The car of each element is a name of a constant, without the `$' before it.
1073 The cdr is the value as a string. For example, if you'd like to use the
1074 speed of light in a formula, you would configure
1076 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1078 and then use it in an equation like `$1*$c'.
1080 Constants can also be defined on a per-file basis using a line like
1082 #+CONSTANTS: c=299792458. pi=3.14 eps=2.4e-6"
1083 :group 'org-table-calculation
1084 :type '(repeat
1085 (cons (string :tag "name")
1086 (string :tag "value"))))
1088 (defvar org-table-formula-constants-local nil
1089 "Local version of `org-table-formula-constants'.")
1090 (make-variable-buffer-local 'org-table-formula-constants-local)
1092 (defcustom org-table-allow-automatic-line-recalculation t
1093 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1094 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1095 :group 'org-table-calculation
1096 :type 'boolean)
1098 (defgroup org-link nil
1099 "Options concerning links in Org-mode."
1100 :tag "Org Link"
1101 :group 'org)
1103 (defvar org-link-abbrev-alist-local nil
1104 "Buffer-local version of `org-link-abbrev-alist', which see.
1105 The value of this is taken from the #+LINK lines.")
1106 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1108 (defcustom org-link-abbrev-alist nil
1109 "Alist of link abbreviations.
1110 The car of each element is a string, to be replaced at the start of a link.
1111 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1112 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1114 [[linkkey:tag][description]]
1116 If REPLACE is a string, the tag will simply be appended to create the link.
1117 If the string contains \"%s\", the tag will be inserted there.
1119 REPLACE may also be a function that will be called with the tag as the
1120 only argument to create the link, which should be returned as a string.
1122 See the manual for examples."
1123 :group 'org-link
1124 :type 'alist)
1126 (defcustom org-descriptive-links t
1127 "Non-nil means, hide link part and only show description of bracket links.
1128 Bracket links are like [[link][descritpion]]. This variable sets the initial
1129 state in new org-mode buffers. The setting can then be toggled on a
1130 per-buffer basis from the Org->Hyperlinks menu."
1131 :group 'org-link
1132 :type 'boolean)
1134 (defcustom org-link-file-path-type 'adaptive
1135 "How the path name in file links should be stored.
1136 Valid values are:
1138 relative Relative to the current directory, i.e. the directory of the file
1139 into which the link is being inserted.
1140 absolute Absolute path, if possible with ~ for home directory.
1141 noabbrev Absolute path, no abbreviation of home directory.
1142 adaptive Use relative path for files in the current directory and sub-
1143 directories of it. For other files, use an absolute path."
1144 :group 'org-link
1145 :type '(choice
1146 (const relative)
1147 (const absolute)
1148 (const noabbrev)
1149 (const adaptive)))
1151 (defcustom org-activate-links '(bracket angle plain radio tag date)
1152 "Types of links that should be activated in Org-mode files.
1153 This is a list of symbols, each leading to the activation of a certain link
1154 type. In principle, it does not hurt to turn on most link types - there may
1155 be a small gain when turning off unused link types. The types are:
1157 bracket The recommended [[link][description]] or [[link]] links with hiding.
1158 angular Links in angular brackes that may contain whitespace like
1159 <bbdb:Carsten Dominik>.
1160 plain Plain links in normal text, no whitespace, like http://google.com.
1161 radio Text that is matched by a radio target, see manual for details.
1162 tag Tag settings in a headline (link to tag search).
1163 date Time stamps (link to calendar).
1165 Changing this variable requires a restart of Emacs to become effective."
1166 :group 'org-link
1167 :type '(set (const :tag "Double bracket links (new style)" bracket)
1168 (const :tag "Angular bracket links (old style)" angular)
1169 (const :tag "Plain text links" plain)
1170 (const :tag "Radio target matches" radio)
1171 (const :tag "Tags" tag)
1172 (const :tag "Timestamps" date)))
1174 (defgroup org-link-store nil
1175 "Options concerning storing links in Org-mode"
1176 :tag "Org Store Link"
1177 :group 'org-link)
1179 (defcustom org-email-link-description-format "Email %c: %.30s"
1180 "Format of the description part of a link to an email or usenet message.
1181 The following %-excapes will be replaced by corresponding information:
1183 %F full \"From\" field
1184 %f name, taken from \"From\" field, address if no name
1185 %T full \"To\" field
1186 %t first name in \"To\" field, address if no name
1187 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
1188 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1189 %s subject
1190 %m message-id.
1192 You may use normal field width specification between the % and the letter.
1193 This is for example useful to limit the length of the subject.
1195 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1196 :group 'org-link-store
1197 :type 'string)
1199 (defcustom org-from-is-user-regexp
1200 (let (r1 r2)
1201 (when (and user-mail-address (not (string= user-mail-address "")))
1202 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1203 (when (and user-full-name (not (string= user-full-name "")))
1204 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1205 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1206 "Regexp mached against the \"From:\" header of an email or usenet message.
1207 It should match if the message is from the user him/herself."
1208 :group 'org-link-store
1209 :type 'regexp)
1211 (defcustom org-context-in-file-links t
1212 "Non-nil means, file links from `org-store-link' contain context.
1213 A search string will be added to the file name with :: as separator and
1214 used to find the context when the link is activated by the command
1215 `org-open-at-point'.
1216 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1217 negates this setting for the duration of the command."
1218 :group 'org-link-store
1219 :type 'boolean)
1221 (defcustom org-keep-stored-link-after-insertion nil
1222 "Non-nil means, keep link in list for entire session.
1224 The command `org-store-link' adds a link pointing to the current
1225 location to an internal list. These links accumulate during a session.
1226 The command `org-insert-link' can be used to insert links into any
1227 Org-mode file (offering completion for all stored links). When this
1228 option is nil, every link which has been inserted once using \\[org-insert-link]
1229 will be removed from the list, to make completing the unused links
1230 more efficient."
1231 :group 'org-link-store
1232 :type 'boolean)
1234 (defcustom org-usenet-links-prefer-google nil
1235 "Non-nil means, `org-store-link' will create web links to Google groups.
1236 When nil, Gnus will be used for such links.
1237 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1238 negates this setting for the duration of the command."
1239 :group 'org-link-store
1240 :type 'boolean)
1242 (defgroup org-link-follow nil
1243 "Options concerning following links in Org-mode"
1244 :tag "Org Follow Link"
1245 :group 'org-link)
1247 (defcustom org-follow-link-hook nil
1248 "Hook that is run after a link has been followed."
1249 :group 'org-link-follow
1250 :type 'hook)
1252 (defcustom org-tab-follows-link nil
1253 "Non-nil means, on links TAB will follow the link.
1254 Needs to be set before org.el is loaded."
1255 :group 'org-link-follow
1256 :type 'boolean)
1258 (defcustom org-return-follows-link nil
1259 "Non-nil means, on links RET will follow the link.
1260 Needs to be set before org.el is loaded."
1261 :group 'org-link-follow
1262 :type 'boolean)
1264 (defcustom org-mouse-1-follows-link
1265 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1266 "Non-nil means, mouse-1 on a link will follow the link.
1267 A longer mouse click will still set point. Does not work on XEmacs.
1268 Needs to be set before org.el is loaded."
1269 :group 'org-link-follow
1270 :type 'boolean)
1272 (defcustom org-mark-ring-length 4
1273 "Number of different positions to be recorded in the ring
1274 Changing this requires a restart of Emacs to work correctly."
1275 :group 'org-link-follow
1276 :type 'interger)
1278 (defcustom org-link-frame-setup
1279 '((vm . vm-visit-folder-other-frame)
1280 (gnus . gnus-other-frame)
1281 (file . find-file-other-window))
1282 "Setup the frame configuration for following links.
1283 When following a link with Emacs, it may often be useful to display
1284 this link in another window or frame. This variable can be used to
1285 set this up for the different types of links.
1286 For VM, use any of
1287 `vm-visit-folder'
1288 `vm-visit-folder-other-frame'
1289 For Gnus, use any of
1290 `gnus'
1291 `gnus-other-frame'
1292 For FILE, use any of
1293 `find-file'
1294 `find-file-other-window'
1295 `find-file-other-frame'
1296 For the calendar, use the variable `calendar-setup'.
1297 For BBDB, it is currently only possible to display the matches in
1298 another window."
1299 :group 'org-link-follow
1300 :type '(list
1301 (cons (const vm)
1302 (choice
1303 (const vm-visit-folder)
1304 (const vm-visit-folder-other-window)
1305 (const vm-visit-folder-other-frame)))
1306 (cons (const gnus)
1307 (choice
1308 (const gnus)
1309 (const gnus-other-frame)))
1310 (cons (const file)
1311 (choice
1312 (const find-file)
1313 (const find-file-other-window)
1314 (const find-file-other-frame)))))
1316 (defcustom org-display-internal-link-with-indirect-buffer nil
1317 "Non-nil means, use indirect buffer to display infile links.
1318 Activating internal links (from one location in a file to another location
1319 in the same file) normally just jumps to the location. When the link is
1320 activated with a C-u prefix (or with mouse-3), the link is displayed in
1321 another window. When this option is set, the other window actually displays
1322 an indirect buffer clone of the current buffer, to avoid any visibility
1323 changes to the current buffer."
1324 :group 'org-link-follow
1325 :type 'boolean)
1327 (defcustom org-open-non-existing-files nil
1328 "Non-nil means, `org-open-file' will open non-existing files.
1329 When nil, an error will be generated."
1330 :group 'org-link-follow
1331 :type 'boolean)
1333 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1334 "Function and arguments to call for following mailto links.
1335 This is a list with the first element being a lisp function, and the
1336 remaining elements being arguments to the function. In string arguments,
1337 %a will be replaced by the address, and %s will be replaced by the subject
1338 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1339 :group 'org-link-follow
1340 :type '(choice
1341 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1342 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1343 (const :tag "message-mail" (message-mail "%a" "%s"))
1344 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1346 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1347 "Non-nil means, ask for confirmation before executing shell links.
1348 Shell links can be dangerous: just think about a link
1350 [[shell:rm -rf ~/*][Google Search]]
1352 This link would show up in your Org-mode document as \"Google Search\",
1353 but really it would remove your entire home directory.
1354 Therefore we advise against setting this variable to nil.
1355 Just change it to `y-or-n-p' of you want to confirm with a
1356 single keystroke rather than having to type \"yes\"."
1357 :group 'org-link-follow
1358 :type '(choice
1359 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1360 (const :tag "with y-or-n (faster)" y-or-n-p)
1361 (const :tag "no confirmation (dangerous)" nil)))
1363 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1364 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1365 Elisp links can be dangerous: just think about a link
1367 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1369 This link would show up in your Org-mode document as \"Google Search\",
1370 but really it would remove your entire home directory.
1371 Therefore we advise against setting this variable to nil.
1372 Just change it to `y-or-n-p' of you want to confirm with a
1373 single keystroke rather than having to type \"yes\"."
1374 :group 'org-link-follow
1375 :type '(choice
1376 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1377 (const :tag "with y-or-n (faster)" y-or-n-p)
1378 (const :tag "no confirmation (dangerous)" nil)))
1380 (defconst org-file-apps-defaults-gnu
1381 '((remote . emacs)
1382 (t . mailcap))
1383 "Default file applications on a UNIX or GNU/Linux system.
1384 See `org-file-apps'.")
1386 (defconst org-file-apps-defaults-macosx
1387 '((remote . emacs)
1388 (t . "open %s")
1389 ("ps" . "gv %s")
1390 ("ps.gz" . "gv %s")
1391 ("eps" . "gv %s")
1392 ("eps.gz" . "gv %s")
1393 ("dvi" . "xdvi %s")
1394 ("fig" . "xfig %s"))
1395 "Default file applications on a MacOS X system.
1396 The system \"open\" is known as a default, but we use X11 applications
1397 for some files for which the OS does not have a good default.
1398 See `org-file-apps'.")
1400 (defconst org-file-apps-defaults-windowsnt
1401 (list
1402 '(remote . emacs)
1403 (cons t
1404 (list (if (featurep 'xemacs)
1405 'mswindows-shell-execute
1406 'w32-shell-execute)
1407 "open" 'file)))
1408 "Default file applications on a Windows NT system.
1409 The system \"open\" is used for most files.
1410 See `org-file-apps'.")
1412 (defcustom org-file-apps
1414 ("txt" . emacs)
1415 ("tex" . emacs)
1416 ("ltx" . emacs)
1417 ("org" . emacs)
1418 ("el" . emacs)
1419 ("bib" . emacs)
1421 "External applications for opening `file:path' items in a document.
1422 Org-mode uses system defaults for different file types, but
1423 you can use this variable to set the application for a given file
1424 extension. The entries in this list are cons cells where the car identifies
1425 files and the cdr the corresponding command. Possible values for the
1426 file identifier are
1427 \"ext\" A string identifying an extension
1428 `directory' Matches a directory
1429 `remote' Matches a remote file, accessible through tramp or efs.
1430 Remote files most likely should be visited through Emacs
1431 because external applications cannot handle such paths.
1432 t Default for all remaining files
1434 Possible values for the command are:
1435 `emacs' The file will be visited by the current Emacs process.
1436 `default' Use the default application for this file type.
1437 string A command to be executed by a shell; %s will be replaced
1438 by the path to the file.
1439 sexp A Lisp form which will be evaluated. The file path will
1440 be available in the Lisp variable `file'.
1441 For more examples, see the system specific constants
1442 `org-file-apps-defaults-macosx'
1443 `org-file-apps-defaults-windowsnt'
1444 `org-file-apps-defaults-gnu'."
1445 :group 'org-link-follow
1446 :type '(repeat
1447 (cons (choice :value ""
1448 (string :tag "Extension")
1449 (const :tag "Default for unrecognized files" t)
1450 (const :tag "Remote file" remote)
1451 (const :tag "Links to a directory" directory))
1452 (choice :value ""
1453 (const :tag "Visit with Emacs" emacs)
1454 (const :tag "Use system default" default)
1455 (string :tag "Command")
1456 (sexp :tag "Lisp form")))))
1458 (defcustom org-mhe-search-all-folders nil
1459 "Non-nil means, that the search for the mh-message will be extended to
1460 all folders if the message cannot be found in the folder given in the link.
1461 Searching all folders is very efficient with one of the search engines
1462 supported by MH-E, but will be slow with pick."
1463 :group 'org-link-follow
1464 :type 'boolean)
1466 (defgroup org-remember nil
1467 "Options concerning interaction with remember.el."
1468 :tag "Org Remember"
1469 :group 'org)
1471 (defcustom org-directory "~/org"
1472 "Directory with org files.
1473 This directory will be used as default to prompt for org files.
1474 Used by the hooks for remember.el."
1475 :group 'org-remember
1476 :type 'directory)
1478 (defcustom org-default-notes-file "~/.notes"
1479 "Default target for storing notes.
1480 Used by the hooks for remember.el. This can be a string, or nil to mean
1481 the value of `remember-data-file'.
1482 You can set this on a per-template basis with the variable
1483 `org-remember-templates'."
1484 :group 'org-remember
1485 :type '(choice
1486 (const :tag "Default from remember-data-file" nil)
1487 file))
1489 (defcustom org-remember-store-without-prompt t
1490 "Non-nil means, `C-c C-c' stores remember note without further promts.
1491 In this case, you need `C-u C-c C-c' to get the prompts for
1492 note file and headline.
1493 When this variable is nil, `C-c C-c' give you the prompts, and
1494 `C-u C-c C-c' trigger the fasttrack."
1495 :group 'org-remember
1496 :type 'boolean)
1498 (defcustom org-remember-interactive-interface 'refile
1499 "The interface to be used for interactive filing of remember notes.
1500 This is only used when the interactive mode for selecting a filing
1501 location is used (see the variable `org-remember-store-without-prompt').
1502 Allowed vaues are:
1503 outline The interface shows an outline of the relevant file
1504 and the correct heading is found by moving through
1505 the outline or by searching with incremental search.
1506 outline-path-completion Headlines in the current buffer are offered via
1507 completion.
1508 refile Use the refile interface, and offer headlines,
1509 possibly from different buffers."
1510 :group 'org-remember
1511 :type '(choice
1512 (const :tag "Refile" refile)
1513 (const :tag "Outline" outline)
1514 (const :tag "Outline-path-completion" outline-path-completion)))
1516 (defcustom org-goto-interface 'outline
1517 "The default interface to be used for `org-goto'.
1518 Allowed vaues are:
1519 outline The interface shows an outline of the relevant file
1520 and the correct heading is found by moving through
1521 the outline or by searching with incremental search.
1522 outline-path-completion Headlines in the current buffer are offered via
1523 completion."
1524 :group 'org-remember ; FIXME: different group for org-goto and org-refile
1525 :type '(choice
1526 (const :tag "Outline" outline)
1527 (const :tag "Outline-path-completion" outline-path-completion)))
1529 (defcustom org-remember-default-headline ""
1530 "The headline that should be the default location in the notes file.
1531 When filing remember notes, the cursor will start at that position.
1532 You can set this on a per-template basis with the variable
1533 `org-remember-templates'."
1534 :group 'org-remember
1535 :type 'string)
1537 (defcustom org-remember-templates nil
1538 "Templates for the creation of remember buffers.
1539 When nil, just let remember make the buffer.
1540 When not nil, this is a list of 5-element lists. In each entry, the first
1541 element is the name of the template, which should be a single short word.
1542 The second element is a character, a unique key to select this template.
1543 The third element is the template. The fourth element is optional and can
1544 specify a destination file for remember items created with this template.
1545 The default file is given by `org-default-notes-file'. An optional fifth
1546 element can specify the headline in that file that should be offered
1547 first when the user is asked to file the entry. The default headline is
1548 given in the variable `org-remember-default-headline'.
1550 An optional sixth element can specify the context in which the user should
1551 be able to select this template. If this element is a list of major modes,
1552 the template will only be available while invoking `org-remember' from a
1553 buffer in one of these modes. If it is a function, the template will only
1554 be selected if the function returns `t'. A value of `t' means select
1555 this template in any context. When the element is `nil', the template
1556 will be selected by default, i.e. when all contextual checks failed.
1558 The template specifies the structure of the remember buffer. It should have
1559 a first line starting with a star, to act as the org-mode headline.
1560 Furthermore, the following %-escapes will be replaced with content:
1562 %^{prompt} Prompt the user for a string and replace this sequence with it.
1563 A default value and a completion table ca be specified like this:
1564 %^{prompt|default|completion2|completion3|...}
1565 %t time stamp, date only
1566 %T time stamp with date and time
1567 %u, %U like the above, but inactive time stamps
1568 %^t like %t, but prompt for date. Similarly %^T, %^u, %^U
1569 You may define a prompt like %^{Please specify birthday}t
1570 %n user name (taken from `user-full-name')
1571 %a annotation, normally the link created with org-store-link
1572 %i initial content, the region active. If %i is indented,
1573 the entire inserted text will be indented as well.
1574 %c content of the clipboard, or current kill ring head
1575 %^g prompt for tags, with completion on tags in target file
1576 %^G prompt for tags, with completion all tags in all agenda files
1577 %:keyword specific information for certain link types, see below
1578 %[pathname] insert the contents of the file given by `pathname'
1579 %(sexp) evaluate elisp `(sexp)' and replace with the result
1580 %! Store this note immediately after filling the template
1582 %? After completing the template, position cursor here.
1584 Apart from these general escapes, you can access information specific to the
1585 link type that is created. For example, calling `remember' in emails or gnus
1586 will record the author and the subject of the message, which you can access
1587 with %:author and %:subject, respectively. Here is a complete list of what
1588 is recorded for each link type.
1590 Link type | Available information
1591 -------------------+------------------------------------------------------
1592 bbdb | %:type %:name %:company
1593 vm, wl, mh, rmail | %:type %:subject %:message-id
1594 | %:from %:fromname %:fromaddress
1595 | %:to %:toname %:toaddress
1596 | %:fromto (either \"to NAME\" or \"from NAME\")
1597 gnus | %:group, for messages also all email fields
1598 w3, w3m | %:type %:url
1599 info | %:type %:file %:node
1600 calendar | %:type %:date"
1601 :group 'org-remember
1602 :get (lambda (var) ; Make sure all entries have at least 5 elements
1603 (mapcar (lambda (x)
1604 (if (not (stringp (car x))) (setq x (cons "" x)))
1605 (cond ((= (length x) 4) (append x '("")))
1606 ((= (length x) 3) (append x '("" "")))
1607 (t x)))
1608 (default-value var)))
1609 :type '(repeat
1610 :tag "enabled"
1611 (list :value ("" ?a "\n" nil nil nil)
1612 (string :tag "Name")
1613 (character :tag "Selection Key")
1614 (string :tag "Template")
1615 (choice
1616 (file :tag "Destination file")
1617 (const :tag "Prompt for file" nil))
1618 (choice
1619 (string :tag "Destination headline")
1620 (const :tag "Selection interface for heading"))
1621 (choice
1622 (const :tag "Use by default" nil)
1623 (const :tag "Use in all contexts" t)
1624 (repeat :tag "Use only if in major mode"
1625 (symbol :tag "Major mode"))
1626 (function :tag "Perform a check against function")))))
1628 (defcustom org-reverse-note-order nil
1629 "Non-nil means, store new notes at the beginning of a file or entry.
1630 When nil, new notes will be filed to the end of a file or entry.
1631 This can also be a list with cons cells of regular expressions that
1632 are matched against file names, and values."
1633 :group 'org-remember
1634 :type '(choice
1635 (const :tag "Reverse always" t)
1636 (const :tag "Reverse never" nil)
1637 (repeat :tag "By file name regexp"
1638 (cons regexp boolean))))
1640 (defcustom org-refile-targets nil
1641 "Targets for refiling entries with \\[org-refile].
1642 This is list of cons cells. Each cell contains:
1643 - a specification of the files to be considered, either a list of files,
1644 or a symbol whose function or value fields will be used to retrieve
1645 a file name or a list of file names. Nil means, refile to a different
1646 heading in the current buffer.
1647 - A specification of how to find candidate refile targets. This may be
1648 any of
1649 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1650 This tag has to be present in all target headlines, inheritance will
1651 not be considered.
1652 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1653 todo keyword.
1654 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1655 headlines that are refiling targets.
1656 - a cons cell (:level . N). Any headline of level N is considered a target.
1657 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1658 ;; FIXME: what if there are a var and func with same name???
1659 :group 'org-remember
1660 :type '(repeat
1661 (cons
1662 (choice :value org-agenda-files
1663 (const :tag "All agenda files" org-agenda-files)
1664 (const :tag "Current buffer" nil)
1665 (function) (variable) (file))
1666 (choice :tag "Identify target headline by"
1667 (cons :tag "Specific tag" (const :tag) (string))
1668 (cons :tag "TODO keyword" (const :todo) (string))
1669 (cons :tag "Regular expression" (const :regexp) (regexp))
1670 (cons :tag "Level number" (const :level) (integer))
1671 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1673 (defcustom org-refile-use-outline-path nil
1674 "Non-nil means, provide refile targets as paths.
1675 So a level 3 headline will be available as level1/level2/level3.
1676 When the value is `file', also include the file name (without directory)
1677 into the path. When `full-file-path', include the full file path."
1678 :group 'org-remember
1679 :type '(choice
1680 (const :tag "Not" nil)
1681 (const :tag "Yes" t)
1682 (const :tag "Start with file name" file)
1683 (const :tag "Start with full file path" full-file-path)))
1685 (defgroup org-todo nil
1686 "Options concerning TODO items in Org-mode."
1687 :tag "Org TODO"
1688 :group 'org)
1690 (defgroup org-progress nil
1691 "Options concerning Progress logging in Org-mode."
1692 :tag "Org Progress"
1693 :group 'org-time)
1695 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1696 "List of TODO entry keyword sequences and their interpretation.
1697 \\<org-mode-map>This is a list of sequences.
1699 Each sequence starts with a symbol, either `sequence' or `type',
1700 indicating if the keywords should be interpreted as a sequence of
1701 action steps, or as different types of TODO items. The first
1702 keywords are states requiring action - these states will select a headline
1703 for inclusion into the global TODO list Org-mode produces. If one of
1704 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1705 signify that no further action is necessary. If \"|\" is not found,
1706 the last keyword is treated as the only DONE state of the sequence.
1708 The command \\[org-todo] cycles an entry through these states, and one
1709 additional state where no keyword is present. For details about this
1710 cycling, see the manual.
1712 TODO keywords and interpretation can also be set on a per-file basis with
1713 the special #+SEQ_TODO and #+TYP_TODO lines.
1715 Each keyword can optionally specify a character for fast state selection
1716 \(in combination with the variable `org-use-fast-todo-selection')
1717 and specifiers for state change logging, using the same syntax
1718 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1719 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1720 indicates to record a time stamp each time this state is selected.
1722 Each keyword may also specify if a timestamp or a note should be
1723 recorded when entering or leaving the state, by adding additional
1724 characters in the parenthesis after the keyword. This looks like this:
1725 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1726 record only the time of the state change. With X and Y being either
1727 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1728 Y when leaving the state if and only if the *target* state does not
1729 define X. You may omit any of the fast-selection key or X or /Y,
1730 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1732 For backward compatibility, this variable may also be just a list
1733 of keywords - in this case the interptetation (sequence or type) will be
1734 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1735 :group 'org-todo
1736 :group 'org-keywords
1737 :type '(choice
1738 (repeat :tag "Old syntax, just keywords"
1739 (string :tag "Keyword"))
1740 (repeat :tag "New syntax"
1741 (cons
1742 (choice
1743 :tag "Interpretation"
1744 (const :tag "Sequence (cycling hits every state)" sequence)
1745 (const :tag "Type (cycling directly to DONE)" type))
1746 (repeat
1747 (string :tag "Keyword"))))))
1749 (defvar org-todo-keywords-1 nil
1750 "All TODO and DONE keywords active in a buffer.")
1751 (make-variable-buffer-local 'org-todo-keywords-1)
1752 (defvar org-todo-keywords-for-agenda nil)
1753 (defvar org-done-keywords-for-agenda nil)
1754 (defvar org-not-done-keywords nil)
1755 (make-variable-buffer-local 'org-not-done-keywords)
1756 (defvar org-done-keywords nil)
1757 (make-variable-buffer-local 'org-done-keywords)
1758 (defvar org-todo-heads nil)
1759 (make-variable-buffer-local 'org-todo-heads)
1760 (defvar org-todo-sets nil)
1761 (make-variable-buffer-local 'org-todo-sets)
1762 (defvar org-todo-log-states nil)
1763 (make-variable-buffer-local 'org-todo-log-states)
1764 (defvar org-todo-kwd-alist nil)
1765 (make-variable-buffer-local 'org-todo-kwd-alist)
1766 (defvar org-todo-key-alist nil)
1767 (make-variable-buffer-local 'org-todo-key-alist)
1768 (defvar org-todo-key-trigger nil)
1769 (make-variable-buffer-local 'org-todo-key-trigger)
1771 (defcustom org-todo-interpretation 'sequence
1772 "Controls how TODO keywords are interpreted.
1773 This variable is in principle obsolete and is only used for
1774 backward compatibility, if the interpretation of todo keywords is
1775 not given already in `org-todo-keywords'. See that variable for
1776 more information."
1777 :group 'org-todo
1778 :group 'org-keywords
1779 :type '(choice (const sequence)
1780 (const type)))
1782 (defcustom org-use-fast-todo-selection 'prefix
1783 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1784 This variable describes if and under what circumstances the cycling
1785 mechanism for TODO keywords will be replaced by a single-key, direct
1786 selection scheme.
1788 When nil, fast selection is never used.
1790 When the symbol `prefix', it will be used when `org-todo' is called with
1791 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1792 in an agenda buffer.
1794 When t, fast selection is used by default. In this case, the prefix
1795 argument forces cycling instead.
1797 In all cases, the special interface is only used if access keys have actually
1798 been assigned by the user, i.e. if keywords in the configuration are followed
1799 by a letter in parenthesis, like TODO(t)."
1800 :group 'org-todo
1801 :type '(choice
1802 (const :tag "Never" nil)
1803 (const :tag "By default" t)
1804 (const :tag "Only with C-u C-c C-t" prefix)))
1806 (defcustom org-after-todo-state-change-hook nil
1807 "Hook which is run after the state of a TODO item was changed.
1808 The new state (a string with a TODO keyword, or nil) is available in the
1809 Lisp variable `state'."
1810 :group 'org-todo
1811 :type 'hook)
1813 (defcustom org-log-done nil
1814 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1815 When equal to the list (done), also prompt for a closing note.
1816 This can also be configured on a per-file basis by adding one of
1817 the following lines anywhere in the buffer:
1819 #+STARTUP: logdone
1820 #+STARTUP: lognotedone
1821 #+STARTUP: nologdone"
1822 :group 'org-todo
1823 :group 'org-progress
1824 :type '(choice
1825 (const :tag "No logging" nil)
1826 (const :tag "Record CLOSED timestamp" time)
1827 (const :tag "Record CLOSED timestamp with closing note." note)))
1829 ;; Normalize old uses of org-log-done.
1830 (cond
1831 ((eq org-log-done t) (setq org-log-done 'time))
1832 ((and (listp org-log-done) (memq 'done org-log-done))
1833 (setq org-log-done 'note)))
1835 ;; FIXME: document
1836 (defcustom org-log-note-clock-out nil
1837 "Non-nil means, recored a note when clocking out of an item.
1838 This can also be configured on a per-file basis by adding one of
1839 the following lines anywhere in the buffer:
1841 #+STARTUP: lognoteclock-out
1842 #+STARTUP: nolognoteclock-out"
1843 :group 'org-todo
1844 :group 'org-progress
1845 :type 'boolean)
1847 (defcustom org-log-done-with-time t
1848 "Non-nil means, the CLOSED time stamp will contain date and time.
1849 When nil, only the date will be recorded."
1850 :group 'org-progress
1851 :type 'boolean)
1853 (defcustom org-log-note-headings
1854 '((done . "CLOSING NOTE %t")
1855 (state . "State %-12s %t")
1856 (clock-out . ""))
1857 "Headings for notes added when clocking out or closing TODO items.
1858 The value is an alist, with the car being a symbol indicating the note
1859 context, and the cdr is the heading to be used. The heading may also be the
1860 empty string.
1861 %t in the heading will be replaced by a time stamp.
1862 %s will be replaced by the new TODO state, in double quotes.
1863 %u will be replaced by the user name.
1864 %U will be replaced by the full user name."
1865 :group 'org-todo
1866 :group 'org-progress
1867 :type '(list :greedy t
1868 (cons (const :tag "Heading when closing an item" done) string)
1869 (cons (const :tag
1870 "Heading when changing todo state (todo sequence only)"
1871 state) string)
1872 (cons (const :tag "Heading when clocking out" clock-out) string)))
1874 (defcustom org-log-states-order-reversed t
1875 "Non-nil means, the latest state change note will be directly after heading.
1876 When nil, the notes will be orderer according to time."
1877 :group 'org-todo
1878 :group 'org-progress
1879 :type 'boolean)
1881 (defcustom org-log-repeat 'time
1882 "Non-nil means, record moving through the DONE state when triggering repeat.
1883 An auto-repeating tasks is immediately switched back to TODO when marked
1884 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1885 the TODO keyword definition, or recording a cloing note by setting
1886 `org-log-done', there will be no record of the task moving trhough DONE.
1887 This variable forces taking a note anyway. Possible values are:
1889 nil Don't force a record
1890 time Record a time stamp
1891 note Record a note
1893 This option can also be set with on a per-file-basis with
1895 #+STARTUP: logrepeat
1896 #+STARTUP: lognoterepeat
1897 #+STARTUP: nologrepeat
1899 You can have local logging settings for a subtree by setting the LOGGING
1900 property to one or more of these keywords."
1901 :group 'org-todo
1902 :group 'org-progress
1903 :type '(choice
1904 (const :tag "Don't force a record" nil)
1905 (const :tag "Force recording the DONE state" time)
1906 (const :tag "Force recording a note with the DONE state" note)))
1908 (defcustom org-clock-into-drawer 2
1909 "Should clocking info be wrapped into a drawer?
1910 When t, clocking info will always be inserted into a :CLOCK: drawer.
1911 If necessary, the drawer will be created.
1912 When nil, the drawer will not be created, but used when present.
1913 When an integer and the number of clocking entries in an item
1914 reaches or exceeds this number, a drawer will be created."
1915 :group 'org-todo
1916 :group 'org-progress
1917 :type '(choice
1918 (const :tag "Always" t)
1919 (const :tag "Only when drawer exists" nil)
1920 (integer :tag "When at least N clock entries")))
1922 (defcustom org-clock-out-when-done t
1923 "When t, the clock will be stopped when the relevant entry is marked DONE.
1924 Nil means, clock will keep running until stopped explicitly with
1925 `C-c C-x C-o', or until the clock is started in a different item."
1926 :group 'org-progress
1927 :type 'boolean)
1929 (defcustom org-clock-in-switch-to-state nil
1930 "Set task to a special todo state while clocking it.
1931 The value should be the state to which the entry should be switched."
1932 :group 'org-progress
1933 :group 'org-todo
1934 :type '(choice
1935 (const :tag "Don't force a state" nil)
1936 (string :tag "State")))
1938 (defgroup org-priorities nil
1939 "Priorities in Org-mode."
1940 :tag "Org Priorities"
1941 :group 'org-todo)
1943 (defcustom org-highest-priority ?A
1944 "The highest priority of TODO items. A character like ?A, ?B etc.
1945 Must have a smaller ASCII number than `org-lowest-priority'."
1946 :group 'org-priorities
1947 :type 'character)
1949 (defcustom org-lowest-priority ?C
1950 "The lowest priority of TODO items. A character like ?A, ?B etc.
1951 Must have a larger ASCII number than `org-highest-priority'."
1952 :group 'org-priorities
1953 :type 'character)
1955 (defcustom org-default-priority ?B
1956 "The default priority of TODO items.
1957 This is the priority an item get if no explicit priority is given."
1958 :group 'org-priorities
1959 :type 'character)
1961 (defcustom org-priority-start-cycle-with-default t
1962 "Non-nil means, start with default priority when starting to cycle.
1963 When this is nil, the first step in the cycle will be (depending on the
1964 command used) one higher or lower that the default priority."
1965 :group 'org-priorities
1966 :type 'boolean)
1968 (defgroup org-time nil
1969 "Options concerning time stamps and deadlines in Org-mode."
1970 :tag "Org Time"
1971 :group 'org)
1973 (defcustom org-insert-labeled-timestamps-at-point nil
1974 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1975 When nil, these labeled time stamps are forces into the second line of an
1976 entry, just after the headline. When scheduling from the global TODO list,
1977 the time stamp will always be forced into the second line."
1978 :group 'org-time
1979 :type 'boolean)
1981 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1982 "Formats for `format-time-string' which are used for time stamps.
1983 It is not recommended to change this constant.")
1985 (defcustom org-time-stamp-rounding-minutes '(0 5)
1986 "Number of minutes to round time stamps to.
1987 These are two values, the first applies when first creating a time stamp.
1988 The second applies when changing it with the commands `S-up' and `S-down'.
1989 When changing the time stamp, this means that it will change in steps
1990 of N minues, as given by the second value.
1992 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1993 numbers should be factors of 60, so for example 5, 10, 15.
1995 When this is larger than 1, you can still force an exact time-stamp by using
1996 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1997 and by using a prefix arg to `S-up/down' to specify the exact number
1998 of minutes to shift."
1999 :group 'org-time
2000 :get '(lambda (var) ; Make sure all entries have 5 elements
2001 (if (integerp (default-value var))
2002 (list (default-value var) 5)
2003 (default-value var)))
2004 :type '(list
2005 (integer :tag "when inserting times")
2006 (integer :tag "when modifying times")))
2008 (defcustom org-display-custom-times nil
2009 "Non-nil means, overlay custom formats over all time stamps.
2010 The formats are defined through the variable `org-time-stamp-custom-formats'.
2011 To turn this on on a per-file basis, insert anywhere in the file:
2012 #+STARTUP: customtime"
2013 :group 'org-time
2014 :set 'set-default
2015 :type 'sexp)
2016 (make-variable-buffer-local 'org-display-custom-times)
2018 (defcustom org-time-stamp-custom-formats
2019 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2020 "Custom formats for time stamps. See `format-time-string' for the syntax.
2021 These are overlayed over the default ISO format if the variable
2022 `org-display-custom-times' is set. Time like %H:%M should be at the
2023 end of the second format."
2024 :group 'org-time
2025 :type 'sexp)
2027 (defun org-time-stamp-format (&optional long inactive)
2028 "Get the right format for a time string."
2029 (let ((f (if long (cdr org-time-stamp-formats)
2030 (car org-time-stamp-formats))))
2031 (if inactive
2032 (concat "[" (substring f 1 -1) "]")
2033 f)))
2035 (defcustom org-read-date-prefer-future t
2036 "Non-nil means, assume future for incomplete date input from user.
2037 This affects the following situations:
2038 1. The user gives a day, but no month.
2039 For example, if today is the 15th, and you enter \"3\", Org-mode will
2040 read this as the third of *next* month. However, if you enter \"17\",
2041 it will be considered as *this* month.
2042 2. The user gives a month but not a year.
2043 For example, if it is april and you enter \"feb 2\", this will be read
2044 as feb 2, *next* year. \"May 5\", however, will be this year.
2046 When this option is nil, the current month and year will always be used
2047 as defaults."
2048 :group 'org-time
2049 :type 'boolean)
2051 (defcustom org-read-date-display-live t
2052 "Non-nil means, display current interpretation of date prompt live.
2053 This display will be in an overlay, in the minibuffer."
2054 :group 'org-time
2055 :type 'boolean)
2057 (defcustom org-read-date-popup-calendar t
2058 "Non-nil means, pop up a calendar when prompting for a date.
2059 In the calendar, the date can be selected with mouse-1. However, the
2060 minibuffer will also be active, and you can simply enter the date as well.
2061 When nil, only the minibuffer will be available."
2062 :group 'org-time
2063 :type 'boolean)
2064 (if (fboundp 'defvaralias)
2065 (defvaralias 'org-popup-calendar-for-date-prompt
2066 'org-read-date-popup-calendar))
2068 (defcustom org-extend-today-until 0
2069 "The hour when your day really ends.
2070 This has influence for the following applications:
2071 - When switching the agenda to \"today\". It it is still earlier than
2072 the time given here, the day recognized as TODAY is actually yesterday.
2073 - When a date is read from the user and it is still before the time given
2074 here, the current date and time will be assumed to be yesterday, 23:59.
2076 FIXME:
2077 IMPORTANT: This is still a very experimental feature, it may disappear
2078 again or it may be extended to mean more things."
2079 :group 'org-time
2080 :type 'number)
2082 (defcustom org-edit-timestamp-down-means-later nil
2083 "Non-nil means, S-down will increase the time in a time stamp.
2084 When nil, S-up will increase."
2085 :group 'org-time
2086 :type 'boolean)
2088 (defcustom org-calendar-follow-timestamp-change t
2089 "Non-nil means, make the calendar window follow timestamp changes.
2090 When a timestamp is modified and the calendar window is visible, it will be
2091 moved to the new date."
2092 :group 'org-time
2093 :type 'boolean)
2095 (defcustom org-clock-heading-function nil
2096 "When non-nil, should be a function to create `org-clock-heading'.
2097 This is the string shown in the mode line when a clock is running.
2098 The function is called with point at the beginning of the headline."
2099 :group 'org-time ; FIXME: Should we have a separate group????
2100 :type 'function)
2102 (defgroup org-tags nil
2103 "Options concerning tags in Org-mode."
2104 :tag "Org Tags"
2105 :group 'org)
2107 (defcustom org-tag-alist nil
2108 "List of tags allowed in Org-mode files.
2109 When this list is nil, Org-mode will base TAG input on what is already in the
2110 buffer.
2111 The value of this variable is an alist, the car of each entry must be a
2112 keyword as a string, the cdr may be a character that is used to select
2113 that tag through the fast-tag-selection interface.
2114 See the manual for details."
2115 :group 'org-tags
2116 :type '(repeat
2117 (choice
2118 (cons (string :tag "Tag name")
2119 (character :tag "Access char"))
2120 (const :tag "Start radio group" (:startgroup))
2121 (const :tag "End radio group" (:endgroup)))))
2123 (defcustom org-use-fast-tag-selection 'auto
2124 "Non-nil means, use fast tag selection scheme.
2125 This is a special interface to select and deselect tags with single keys.
2126 When nil, fast selection is never used.
2127 When the symbol `auto', fast selection is used if and only if selection
2128 characters for tags have been configured, either through the variable
2129 `org-tag-alist' or through a #+TAGS line in the buffer.
2130 When t, fast selection is always used and selection keys are assigned
2131 automatically if necessary."
2132 :group 'org-tags
2133 :type '(choice
2134 (const :tag "Always" t)
2135 (const :tag "Never" nil)
2136 (const :tag "When selection characters are configured" 'auto)))
2138 (defcustom org-fast-tag-selection-single-key nil
2139 "Non-nil means, fast tag selection exits after first change.
2140 When nil, you have to press RET to exit it.
2141 During fast tag selection, you can toggle this flag with `C-c'.
2142 This variable can also have the value `expert'. In this case, the window
2143 displaying the tags menu is not even shown, until you press C-c again."
2144 :group 'org-tags
2145 :type '(choice
2146 (const :tag "No" nil)
2147 (const :tag "Yes" t)
2148 (const :tag "Expert" expert)))
2150 (defvar org-fast-tag-selection-include-todo nil
2151 "Non-nil means, fast tags selection interface will also offer TODO states.
2152 This is an undocumented feature, you should not rely on it.")
2154 (defcustom org-tags-column -80
2155 "The column to which tags should be indented in a headline.
2156 If this number is positive, it specifies the column. If it is negative,
2157 it means that the tags should be flushright to that column. For example,
2158 -80 works well for a normal 80 character screen."
2159 :group 'org-tags
2160 :type 'integer)
2162 (defcustom org-auto-align-tags t
2163 "Non-nil means, realign tags after pro/demotion of TODO state change.
2164 These operations change the length of a headline and therefore shift
2165 the tags around. With this options turned on, after each such operation
2166 the tags are again aligned to `org-tags-column'."
2167 :group 'org-tags
2168 :type 'boolean)
2170 (defcustom org-use-tag-inheritance t
2171 "Non-nil means, tags in levels apply also for sublevels.
2172 When nil, only the tags directly given in a specific line apply there.
2173 If you turn off this option, you very likely want to turn on the
2174 companion option `org-tags-match-list-sublevels'."
2175 :group 'org-tags
2176 :type 'boolean)
2178 (defcustom org-tags-match-list-sublevels nil
2179 "Non-nil means list also sublevels of headlines matching tag search.
2180 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2181 the sublevels of a headline matching a tag search often also match
2182 the same search. Listing all of them can create very long lists.
2183 Setting this variable to nil causes subtrees of a match to be skipped.
2184 This option is off by default, because inheritance in on. If you turn
2185 inheritance off, you very likely want to turn this option on.
2187 As a special case, if the tag search is restricted to TODO items, the
2188 value of this variable is ignored and sublevels are always checked, to
2189 make sure all corresponding TODO items find their way into the list."
2190 :group 'org-tags
2191 :type 'boolean)
2193 (defvar org-tags-history nil
2194 "History of minibuffer reads for tags.")
2195 (defvar org-last-tags-completion-table nil
2196 "The last used completion table for tags.")
2197 (defvar org-after-tags-change-hook nil
2198 "Hook that is run after the tags in a line have changed.")
2200 (defgroup org-properties nil
2201 "Options concerning properties in Org-mode."
2202 :tag "Org Properties"
2203 :group 'org)
2205 (defcustom org-property-format "%-10s %s"
2206 "How property key/value pairs should be formatted by `indent-line'.
2207 When `indent-line' hits a property definition, it will format the line
2208 according to this format, mainly to make sure that the values are
2209 lined-up with respect to each other."
2210 :group 'org-properties
2211 :type 'string)
2213 (defcustom org-use-property-inheritance nil
2214 "Non-nil means, properties apply also for sublevels.
2215 This setting is only relevant during property searches, not when querying
2216 an entry with `org-entry-get'. To retrieve a property with inheritance,
2217 you need to call `org-entry-get' with the inheritance flag.
2218 Turning this on can cause significant overhead when doing a search, so
2219 this is turned off by default.
2220 When nil, only the properties directly given in the current entry count.
2221 The value may also be a list of properties that shouldhave inheritance.
2223 However, note that some special properties use inheritance under special
2224 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2225 and the properties ending in \"_ALL\" when they are used as descriptor
2226 for valid values of a property."
2227 :group 'org-properties
2228 :type '(choice
2229 (const :tag "Not" nil)
2230 (const :tag "Always" nil)
2231 (repeat :tag "Specific properties" (string :tag "Property"))))
2233 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2234 "The default column format, if no other format has been defined.
2235 This variable can be set on the per-file basis by inserting a line
2237 #+COLUMNS: %25ITEM ....."
2238 :group 'org-properties
2239 :type 'string)
2241 (defcustom org-global-properties nil
2242 "List of property/value pairs that can be inherited by any entry.
2243 You can set buffer-local values for this by adding lines like
2245 #+PROPERTY: NAME VALUE"
2246 :group 'org-properties
2247 :type '(repeat
2248 (cons (string :tag "Property")
2249 (string :tag "Value"))))
2251 (defvar org-local-properties nil
2252 "List of property/value pairs that can be inherited by any entry.
2253 Valid for the current buffer.
2254 This variable is populated from #+PROPERTY lines.")
2256 (defgroup org-agenda nil
2257 "Options concerning agenda views in Org-mode."
2258 :tag "Org Agenda"
2259 :group 'org)
2261 (defvar org-category nil
2262 "Variable used by org files to set a category for agenda display.
2263 Such files should use a file variable to set it, for example
2265 # -*- mode: org; org-category: \"ELisp\"
2267 or contain a special line
2269 #+CATEGORY: ELisp
2271 If the file does not specify a category, then file's base name
2272 is used instead.")
2273 (make-variable-buffer-local 'org-category)
2275 (defcustom org-agenda-files nil
2276 "The files to be used for agenda display.
2277 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2278 \\[org-remove-file]. You can also use customize to edit the list.
2280 If an entry is a directory, all files in that directory that are matched by
2281 `org-agenda-file-regexp' will be part of the file list.
2283 If the value of the variable is not a list but a single file name, then
2284 the list of agenda files is actually stored and maintained in that file, one
2285 agenda file per line."
2286 :group 'org-agenda
2287 :type '(choice
2288 (repeat :tag "List of files and directories" file)
2289 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2291 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2292 "Regular expression to match files for `org-agenda-files'.
2293 If any element in the list in that variable contains a directory instead
2294 of a normal file, all files in that directory that are matched by this
2295 regular expression will be included."
2296 :group 'org-agenda
2297 :type 'regexp)
2299 (defcustom org-agenda-skip-unavailable-files nil
2300 "t means to just skip non-reachable files in `org-agenda-files'.
2301 Nil means to remove them, after a query, from the list."
2302 :group 'org-agenda
2303 :type 'boolean)
2305 (defcustom org-agenda-text-search-extra-files nil
2306 "List of extra files to be searched by text search commands.
2307 These files will be search in addition to the agenda files bu the
2308 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2309 Note that these files will only be searched for text search commands,
2310 not for the other agenda views like todo lists, tag earches or the weekly
2311 agenda. This variable is intended to list notes and possibly archive files
2312 that should also be searched by these two commands."
2313 :group 'org-agenda
2314 :type '(repeat file))
2316 (if (fboundp 'defvaralias)
2317 (defvaralias 'org-agenda-multi-occur-extra-files
2318 'org-agenda-text-search-extra-files))
2320 (defcustom org-agenda-confirm-kill 1
2321 "When set, remote killing from the agenda buffer needs confirmation.
2322 When t, a confirmation is always needed. When a number N, confirmation is
2323 only needed when the text to be killed contains more than N non-white lines."
2324 :group 'org-agenda
2325 :type '(choice
2326 (const :tag "Never" nil)
2327 (const :tag "Always" t)
2328 (number :tag "When more than N lines")))
2330 (defcustom org-calendar-to-agenda-key [?c]
2331 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2332 The command `org-calendar-goto-agenda' will be bound to this key. The
2333 default is the character `c' because then `c' can be used to switch back and
2334 forth between agenda and calendar."
2335 :group 'org-agenda
2336 :type 'sexp)
2338 (defcustom org-agenda-compact-blocks nil
2339 "Non-nil means, make the block agenda more compact.
2340 This is done by leaving out unnecessary lines."
2341 :group 'org-agenda
2342 :type nil)
2344 (defgroup org-agenda-export nil
2345 "Options concerning exporting agenda views in Org-mode."
2346 :tag "Org Agenda Export"
2347 :group 'org-agenda)
2349 (defcustom org-agenda-with-colors t
2350 "Non-nil means, use colors in agenda views."
2351 :group 'org-agenda-export
2352 :type 'boolean)
2354 (defcustom org-agenda-exporter-settings nil
2355 "Alist of variable/value pairs that should be active during agenda export.
2356 This is a good place to set uptions for ps-print and for htmlize."
2357 :group 'org-agenda-export
2358 :type '(repeat
2359 (list
2360 (variable)
2361 (sexp :tag "Value"))))
2363 (defcustom org-agenda-export-html-style ""
2364 "The style specification for exported HTML Agenda files.
2365 If this variable contains a string, it will replace the default <style>
2366 section as produced by `htmlize'.
2367 Since there are different ways of setting style information, this variable
2368 needs to contain the full HTML structure to provide a style, including the
2369 surrounding HTML tags. The style specifications should include definitions
2370 the fonts used by the agenda, here is an example:
2372 <style type=\"text/css\">
2373 p { font-weight: normal; color: gray; }
2374 .org-agenda-structure {
2375 font-size: 110%;
2376 color: #003399;
2377 font-weight: 600;
2379 .org-todo {
2380 color: #cc6666;Week-agenda:
2381 font-weight: bold;
2383 .org-done {
2384 color: #339933;
2386 .title { text-align: center; }
2387 .todo, .deadline { color: red; }
2388 .done { color: green; }
2389 </style>
2391 or, if you want to keep the style in a file,
2393 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2395 As the value of this option simply gets inserted into the HTML <head> header,
2396 you can \"misuse\" it to also add other text to the header. However,
2397 <style>...</style> is required, if not present the variable will be ignored."
2398 :group 'org-agenda-export
2399 :group 'org-export-html
2400 :type 'string)
2402 (defgroup org-agenda-custom-commands nil
2403 "Options concerning agenda views in Org-mode."
2404 :tag "Org Agenda Custom Commands"
2405 :group 'org-agenda)
2407 (defconst org-sorting-choice
2408 '(choice
2409 (const time-up) (const time-down)
2410 (const category-keep) (const category-up) (const category-down)
2411 (const tag-down) (const tag-up)
2412 (const priority-up) (const priority-down))
2413 "Sorting choices.")
2415 (defconst org-agenda-custom-commands-local-options
2416 `(repeat :tag "Local settings for this command. Remember to quote values"
2417 (choice :tag "Setting"
2418 (list :tag "Any variable"
2419 (variable :tag "Variable")
2420 (sexp :tag "Value"))
2421 (list :tag "Files to be searched"
2422 (const org-agenda-files)
2423 (list
2424 (const :format "" quote)
2425 (repeat
2426 (file))))
2427 (list :tag "Sorting strategy"
2428 (const org-agenda-sorting-strategy)
2429 (list
2430 (const :format "" quote)
2431 (repeat
2432 ,org-sorting-choice)))
2433 (list :tag "Prefix format"
2434 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2435 (string))
2436 (list :tag "Number of days in agenda"
2437 (const org-agenda-ndays)
2438 (integer :value 1))
2439 (list :tag "Fixed starting date"
2440 (const org-agenda-start-day)
2441 (string :value "2007-11-01"))
2442 (list :tag "Start on day of week"
2443 (const org-agenda-start-on-weekday)
2444 (choice :value 1
2445 (const :tag "Today" nil)
2446 (number :tag "Weekday No.")))
2447 (list :tag "Include data from diary"
2448 (const org-agenda-include-diary)
2449 (boolean))
2450 (list :tag "Deadline Warning days"
2451 (const org-deadline-warning-days)
2452 (integer :value 1))
2453 (list :tag "Standard skipping condition"
2454 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2455 (const org-agenda-skip-function)
2456 (list
2457 (const :format "" quote)
2458 (list
2459 (choice
2460 :tag "Skiping range"
2461 (const :tag "Skip entry" org-agenda-skip-entry-if)
2462 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2463 (repeat :inline t :tag "Conditions for skipping"
2464 (choice
2465 :tag "Condition type"
2466 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2467 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2468 (const :tag "scheduled" 'scheduled)
2469 (const :tag "not scheduled" 'notscheduled)
2470 (const :tag "deadline" 'deadline)
2471 (const :tag "no deadline" 'notdeadline))))))
2472 (list :tag "Non-standard skipping condition"
2473 :value (org-agenda-skip-function)
2474 (list
2475 (const org-agenda-skip-function)
2476 (sexp :tag "Function or form (quoted!)")))))
2477 "Selection of examples for agenda command settings.
2478 This will be spliced into the custom type of
2479 `org-agenda-custom-commands'.")
2482 (defcustom org-agenda-custom-commands nil
2483 "Custom commands for the agenda.
2484 These commands will be offered on the splash screen displayed by the
2485 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2487 (key desc type match settings files)
2489 key The key (one or more characters as a string) to be associated
2490 with the command.
2491 desc A description of the command, when omitted or nil, a default
2492 description is built using MATCH.
2493 type The command type, any of the following symbols:
2494 agenda The daily/weekly agenda.
2495 todo Entries with a specific TODO keyword, in all agenda files.
2496 search Entries containing search words entry or headline.
2497 tags Tags/Property/TODO match in all agenda files.
2498 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2499 todo-tree Sparse tree of specific TODO keyword in *current* file.
2500 tags-tree Sparse tree with all tags matches in *current* file.
2501 occur-tree Occur sparse tree for *current* file.
2502 ... A user-defined function.
2503 match What to search for:
2504 - a single keyword for TODO keyword searches
2505 - a tags match expression for tags searches
2506 - a word search expression for text searches.
2507 - a regular expression for occur searches
2508 For all other commands, this should be the empty string.
2509 settings A list of option settings, similar to that in a let form, so like
2510 this: ((opt1 val1) (opt2 val2) ...). The values will be
2511 evaluated at the moment of execution, so quote them when needed.
2512 files A list of files file to write the produced agenda buffer to
2513 with the command `org-store-agenda-views'.
2514 If a file name ends in \".html\", an HTML version of the buffer
2515 is written out. If it ends in \".ps\", a postscript version is
2516 produced. Otherwide, only the plain text is written to the file.
2518 You can also define a set of commands, to create a composite agenda buffer.
2519 In this case, an entry looks like this:
2521 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2523 where
2525 desc A description string to be displayed in the dispatcher menu.
2526 cmd An agenda command, similar to the above. However, tree commands
2527 are no allowed, but instead you can get agenda and global todo list.
2528 So valid commands for a set are:
2529 (agenda \"\" settings)
2530 (alltodo \"\" settings)
2531 (stuck \"\" settings)
2532 (todo \"match\" settings files)
2533 (search \"match\" settings files)
2534 (tags \"match\" settings files)
2535 (tags-todo \"match\" settings files)
2537 Each command can carry a list of options, and another set of options can be
2538 given for the whole set of commands. Individual command options take
2539 precedence over the general options.
2541 When using several characters as key to a command, the first characters
2542 are prefix commands. For the dispatcher to display useful information, you
2543 should provide a description for the prefix, like
2545 (setq org-agenda-custom-commands
2546 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2547 (\"hl\" tags \"+HOME+Lisa\")
2548 (\"hp\" tags \"+HOME+Peter\")
2549 (\"hk\" tags \"+HOME+Kim\")))"
2550 :group 'org-agenda-custom-commands
2551 :type `(repeat
2552 (choice :value ("x" "Describe command here" tags "" nil)
2553 (list :tag "Single command"
2554 (string :tag "Access Key(s) ")
2555 (option (string :tag "Description"))
2556 (choice
2557 (const :tag "Agenda" agenda)
2558 (const :tag "TODO list" alltodo)
2559 (const :tag "Search words" search)
2560 (const :tag "Stuck projects" stuck)
2561 (const :tag "Tags search (all agenda files)" tags)
2562 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2563 (const :tag "TODO keyword search (all agenda files)" todo)
2564 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2565 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2566 (const :tag "Occur tree (current buffer)" occur-tree)
2567 (sexp :tag "Other, user-defined function"))
2568 (string :tag "Match (only for some commands)")
2569 ,org-agenda-custom-commands-local-options
2570 (option (repeat :tag "Export" (file :tag "Export to"))))
2571 (list :tag "Command series, all agenda files"
2572 (string :tag "Access Key(s)")
2573 (string :tag "Description ")
2574 (repeat :tag "Component"
2575 (choice
2576 (list :tag "Agenda"
2577 (const :format "" agenda)
2578 (const :tag "" :format "" "")
2579 ,org-agenda-custom-commands-local-options)
2580 (list :tag "TODO list (all keywords)"
2581 (const :format "" alltodo)
2582 (const :tag "" :format "" "")
2583 ,org-agenda-custom-commands-local-options)
2584 (list :tag "Search words"
2585 (const :format "" search)
2586 (string :tag "Match")
2587 ,org-agenda-custom-commands-local-options)
2588 (list :tag "Stuck projects"
2589 (const :format "" stuck)
2590 (const :tag "" :format "" "")
2591 ,org-agenda-custom-commands-local-options)
2592 (list :tag "Tags search"
2593 (const :format "" tags)
2594 (string :tag "Match")
2595 ,org-agenda-custom-commands-local-options)
2596 (list :tag "Tags search, TODO entries only"
2597 (const :format "" tags-todo)
2598 (string :tag "Match")
2599 ,org-agenda-custom-commands-local-options)
2600 (list :tag "TODO keyword search"
2601 (const :format "" todo)
2602 (string :tag "Match")
2603 ,org-agenda-custom-commands-local-options)
2604 (list :tag "Other, user-defined function"
2605 (symbol :tag "function")
2606 (string :tag "Match")
2607 ,org-agenda-custom-commands-local-options)))
2609 (repeat :tag "Settings for entire command set"
2610 (list (variable :tag "Any variable")
2611 (sexp :tag "Value")))
2612 (option (repeat :tag "Export" (file :tag "Export to"))))
2613 (cons :tag "Prefix key documentation"
2614 (string :tag "Access Key(s)")
2615 (string :tag "Description ")))))
2617 (defcustom org-agenda-query-register ?o
2618 "The register holding the current query string.
2619 The prupose of this is that if you construct a query string interactively,
2620 you can then use it to define a custom command."
2621 :group 'org-agenda-custom-commands
2622 :type 'character)
2624 (defcustom org-stuck-projects
2625 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2626 "How to identify stuck projects.
2627 This is a list of four items:
2628 1. A tags/todo matcher string that is used to identify a project.
2629 The entire tree below a headline matched by this is considered one project.
2630 2. A list of TODO keywords identifying non-stuck projects.
2631 If the project subtree contains any headline with one of these todo
2632 keywords, the project is considered to be not stuck. If you specify
2633 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2634 3. A list of tags identifying non-stuck projects.
2635 If the project subtree contains any headline with one of these tags,
2636 the project is considered to be not stuck. If you specify \"*\" as
2637 a tag, any tag will mark the project unstuck.
2638 4. An arbitrary regular expression matching non-stuck projects.
2640 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2641 or `C-c a #' to produce the list."
2642 :group 'org-agenda-custom-commands
2643 :type '(list
2644 (string :tag "Tags/TODO match to identify a project")
2645 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2646 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2647 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2650 (defgroup org-agenda-skip nil
2651 "Options concerning skipping parts of agenda files."
2652 :tag "Org Agenda Skip"
2653 :group 'org-agenda)
2655 (defcustom org-agenda-todo-list-sublevels t
2656 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2657 When nil, the sublevels of a TODO entry are not checked, resulting in
2658 potentially much shorter TODO lists."
2659 :group 'org-agenda-skip
2660 :group 'org-todo
2661 :type 'boolean)
2663 (defcustom org-agenda-todo-ignore-with-date nil
2664 "Non-nil means, don't show entries with a date in the global todo list.
2665 You can use this if you prefer to mark mere appointments with a TODO keyword,
2666 but don't want them to show up in the TODO list.
2667 When this is set, it also covers deadlines and scheduled items, the settings
2668 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2669 will be ignored."
2670 :group 'org-agenda-skip
2671 :group 'org-todo
2672 :type 'boolean)
2674 (defcustom org-agenda-todo-ignore-scheduled nil
2675 "Non-nil means, don't show scheduled entries in the global todo list.
2676 The idea behind this is that by scheduling it, you have already taken care
2677 of this item.
2678 See also `org-agenda-todo-ignore-with-date'."
2679 :group 'org-agenda-skip
2680 :group 'org-todo
2681 :type 'boolean)
2683 (defcustom org-agenda-todo-ignore-deadlines nil
2684 "Non-nil means, don't show near deadline entries in the global todo list.
2685 Near means closer than `org-deadline-warning-days' days.
2686 The idea behind this is that such items will appear in the agenda anyway.
2687 See also `org-agenda-todo-ignore-with-date'."
2688 :group 'org-agenda-skip
2689 :group 'org-todo
2690 :type 'boolean)
2692 (defcustom org-agenda-skip-scheduled-if-done nil
2693 "Non-nil means don't show scheduled items in agenda when they are done.
2694 This is relevant for the daily/weekly agenda, not for the TODO list. And
2695 it applies only to the actual date of the scheduling. Warnings about
2696 an item with a past scheduling dates are always turned off when the item
2697 is DONE."
2698 :group 'org-agenda-skip
2699 :type 'boolean)
2701 (defcustom org-agenda-skip-deadline-if-done nil
2702 "Non-nil means don't show deadines when the corresponding item is done.
2703 When nil, the deadline is still shown and should give you a happy feeling.
2704 This is relevant for the daily/weekly agenda. And it applied only to the
2705 actualy date of the deadline. Warnings about approching and past-due
2706 deadlines are always turned off when the item is DONE."
2707 :group 'org-agenda-skip
2708 :type 'boolean)
2710 (defcustom org-agenda-skip-timestamp-if-done nil
2711 "Non-nil means don't select item by timestamp or -range if it is DONE."
2712 :group 'org-agenda-skip
2713 :type 'boolean)
2715 (defcustom org-timeline-show-empty-dates 3
2716 "Non-nil means, `org-timeline' also shows dates without an entry.
2717 When nil, only the days which actually have entries are shown.
2718 When t, all days between the first and the last date are shown.
2719 When an integer, show also empty dates, but if there is a gap of more than
2720 N days, just insert a special line indicating the size of the gap."
2721 :group 'org-agenda-skip
2722 :type '(choice
2723 (const :tag "None" nil)
2724 (const :tag "All" t)
2725 (number :tag "at most")))
2728 (defgroup org-agenda-startup nil
2729 "Options concerning initial settings in the Agenda in Org Mode."
2730 :tag "Org Agenda Startup"
2731 :group 'org-agenda)
2733 (defcustom org-finalize-agenda-hook nil
2734 "Hook run just before displaying an agenda buffer."
2735 :group 'org-agenda-startup
2736 :type 'hook)
2738 (defcustom org-agenda-mouse-1-follows-link nil
2739 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2740 A longer mouse click will still set point. Does not work on XEmacs.
2741 Needs to be set before org.el is loaded."
2742 :group 'org-agenda-startup
2743 :type 'boolean)
2745 (defcustom org-agenda-start-with-follow-mode nil
2746 "The initial value of follow-mode in a newly created agenda window."
2747 :group 'org-agenda-startup
2748 :type 'boolean)
2750 (defgroup org-agenda-windows nil
2751 "Options concerning the windows used by the Agenda in Org Mode."
2752 :tag "Org Agenda Windows"
2753 :group 'org-agenda)
2755 (defcustom org-agenda-window-setup 'reorganize-frame
2756 "How the agenda buffer should be displayed.
2757 Possible values for this option are:
2759 current-window Show agenda in the current window, keeping all other windows.
2760 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2761 other-window Use `switch-to-buffer-other-window' to display agenda.
2762 reorganize-frame Show only two windows on the current frame, the current
2763 window and the agenda.
2764 See also the variable `org-agenda-restore-windows-after-quit'."
2765 :group 'org-agenda-windows
2766 :type '(choice
2767 (const current-window)
2768 (const other-frame)
2769 (const other-window)
2770 (const reorganize-frame)))
2772 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2773 "The min and max height of the agenda window as a fraction of frame height.
2774 The value of the variable is a cons cell with two numbers between 0 and 1.
2775 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2776 :group 'org-agenda-windows
2777 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2779 (defcustom org-agenda-restore-windows-after-quit nil
2780 "Non-nil means, restore window configuration open exiting agenda.
2781 Before the window configuration is changed for displaying the agenda,
2782 the current status is recorded. When the agenda is exited with
2783 `q' or `x' and this option is set, the old state is restored. If
2784 `org-agenda-window-setup' is `other-frame', the value of this
2785 option will be ignored.."
2786 :group 'org-agenda-windows
2787 :type 'boolean)
2789 (defcustom org-indirect-buffer-display 'other-window
2790 "How should indirect tree buffers be displayed?
2791 This applies to indirect buffers created with the commands
2792 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2793 Valid values are:
2794 current-window Display in the current window
2795 other-window Just display in another window.
2796 dedicated-frame Create one new frame, and re-use it each time.
2797 new-frame Make a new frame each time. Note that in this case
2798 previously-made indirect buffers are kept, and you need to
2799 kill these buffers yourself."
2800 :group 'org-structure
2801 :group 'org-agenda-windows
2802 :type '(choice
2803 (const :tag "In current window" current-window)
2804 (const :tag "In current frame, other window" other-window)
2805 (const :tag "Each time a new frame" new-frame)
2806 (const :tag "One dedicated frame" dedicated-frame)))
2808 (defgroup org-agenda-daily/weekly nil
2809 "Options concerning the daily/weekly agenda."
2810 :tag "Org Agenda Daily/Weekly"
2811 :group 'org-agenda)
2813 (defcustom org-agenda-ndays 7
2814 "Number of days to include in overview display.
2815 Should be 1 or 7."
2816 :group 'org-agenda-daily/weekly
2817 :type 'number)
2819 (defcustom org-agenda-start-on-weekday 1
2820 "Non-nil means, start the overview always on the specified weekday.
2821 0 denotes Sunday, 1 denotes Monday etc.
2822 When nil, always start on the current day."
2823 :group 'org-agenda-daily/weekly
2824 :type '(choice (const :tag "Today" nil)
2825 (number :tag "Weekday No.")))
2827 (defcustom org-agenda-show-all-dates t
2828 "Non-nil means, `org-agenda' shows every day in the selected range.
2829 When nil, only the days which actually have entries are shown."
2830 :group 'org-agenda-daily/weekly
2831 :type 'boolean)
2833 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2834 "Format string for displaying dates in the agenda.
2835 Used by the daily/weekly agenda and by the timeline. This should be
2836 a format string understood by `format-time-string', or a function returning
2837 the formatted date as a string. The function must take a single argument,
2838 a calendar-style date list like (month day year)."
2839 :group 'org-agenda-daily/weekly
2840 :type '(choice
2841 (string :tag "Format string")
2842 (function :tag "Function")))
2844 (defun org-agenda-format-date-aligned (date)
2845 "Format a date string for display in the daily/weekly agenda, or timeline.
2846 This function makes sure that dates are aligned for easy reading."
2847 (format "%-9s %2d %s %4d"
2848 (calendar-day-name date)
2849 (extract-calendar-day date)
2850 (calendar-month-name (extract-calendar-month date))
2851 (extract-calendar-year date)))
2853 (defcustom org-agenda-include-diary nil
2854 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2855 :group 'org-agenda-daily/weekly
2856 :type 'boolean)
2858 (defcustom org-agenda-include-all-todo nil
2859 "Set means weekly/daily agenda will always contain all TODO entries.
2860 The TODO entries will be listed at the top of the agenda, before
2861 the entries for specific days."
2862 :group 'org-agenda-daily/weekly
2863 :type 'boolean)
2865 (defcustom org-agenda-repeating-timestamp-show-all t
2866 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2867 When nil, only one occurence is shown, either today or the
2868 nearest into the future."
2869 :group 'org-agenda-daily/weekly
2870 :type 'boolean)
2872 (defcustom org-deadline-warning-days 14
2873 "No. of days before expiration during which a deadline becomes active.
2874 This variable governs the display in sparse trees and in the agenda.
2875 When 0 or negative, it means use this number (the absolute value of it)
2876 even if a deadline has a different individual lead time specified."
2877 :group 'org-time
2878 :group 'org-agenda-daily/weekly
2879 :type 'number)
2881 (defcustom org-scheduled-past-days 10000
2882 "No. of days to continue listing scheduled items that are not marked DONE.
2883 When an item is scheduled on a date, it shows up in the agenda on this
2884 day and will be listed until it is marked done for the number of days
2885 given here."
2886 :group 'org-agenda-daily/weekly
2887 :type 'number)
2889 (defgroup org-agenda-time-grid nil
2890 "Options concerning the time grid in the Org-mode Agenda."
2891 :tag "Org Agenda Time Grid"
2892 :group 'org-agenda)
2894 (defcustom org-agenda-use-time-grid t
2895 "Non-nil means, show a time grid in the agenda schedule.
2896 A time grid is a set of lines for specific times (like every two hours between
2897 8:00 and 20:00). The items scheduled for a day at specific times are
2898 sorted in between these lines.
2899 For details about when the grid will be shown, and what it will look like, see
2900 the variable `org-agenda-time-grid'."
2901 :group 'org-agenda-time-grid
2902 :type 'boolean)
2904 (defcustom org-agenda-time-grid
2905 '((daily today require-timed)
2906 "----------------"
2907 (800 1000 1200 1400 1600 1800 2000))
2909 "The settings for time grid for agenda display.
2910 This is a list of three items. The first item is again a list. It contains
2911 symbols specifying conditions when the grid should be displayed:
2913 daily if the agenda shows a single day
2914 weekly if the agenda shows an entire week
2915 today show grid on current date, independent of daily/weekly display
2916 require-timed show grid only if at least one item has a time specification
2918 The second item is a string which will be places behing the grid time.
2920 The third item is a list of integers, indicating the times that should have
2921 a grid line."
2922 :group 'org-agenda-time-grid
2923 :type
2924 '(list
2925 (set :greedy t :tag "Grid Display Options"
2926 (const :tag "Show grid in single day agenda display" daily)
2927 (const :tag "Show grid in weekly agenda display" weekly)
2928 (const :tag "Always show grid for today" today)
2929 (const :tag "Show grid only if any timed entries are present"
2930 require-timed)
2931 (const :tag "Skip grid times already present in an entry"
2932 remove-match))
2933 (string :tag "Grid String")
2934 (repeat :tag "Grid Times" (integer :tag "Time"))))
2936 (defgroup org-agenda-sorting nil
2937 "Options concerning sorting in the Org-mode Agenda."
2938 :tag "Org Agenda Sorting"
2939 :group 'org-agenda)
2941 (defcustom org-agenda-sorting-strategy
2942 '((agenda time-up category-keep priority-down)
2943 (todo category-keep priority-down)
2944 (tags category-keep priority-down)
2945 (search category-keep))
2946 "Sorting structure for the agenda items of a single day.
2947 This is a list of symbols which will be used in sequence to determine
2948 if an entry should be listed before another entry. The following
2949 symbols are recognized:
2951 time-up Put entries with time-of-day indications first, early first
2952 time-down Put entries with time-of-day indications first, late first
2953 category-keep Keep the default order of categories, corresponding to the
2954 sequence in `org-agenda-files'.
2955 category-up Sort alphabetically by category, A-Z.
2956 category-down Sort alphabetically by category, Z-A.
2957 tag-up Sort alphabetically by last tag, A-Z.
2958 tag-down Sort alphabetically by last tag, Z-A.
2959 priority-up Sort numerically by priority, high priority last.
2960 priority-down Sort numerically by priority, high priority first.
2962 The different possibilities will be tried in sequence, and testing stops
2963 if one comparison returns a \"not-equal\". For example, the default
2964 '(time-up category-keep priority-down)
2965 means: Pull out all entries having a specified time of day and sort them,
2966 in order to make a time schedule for the current day the first thing in the
2967 agenda listing for the day. Of the entries without a time indication, keep
2968 the grouped in categories, don't sort the categories, but keep them in
2969 the sequence given in `org-agenda-files'. Within each category sort by
2970 priority.
2972 Leaving out `category-keep' would mean that items will be sorted across
2973 categories by priority.
2975 Instead of a single list, this can also be a set of list for specific
2976 contents, with a context symbol in the car of the list, any of
2977 `agenda', `todo', `tags' for the corresponding agenda views."
2978 :group 'org-agenda-sorting
2979 :type `(choice
2980 (repeat :tag "General" ,org-sorting-choice)
2981 (list :tag "Individually"
2982 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2983 (repeat ,org-sorting-choice))
2984 (cons (const :tag "Strategy for TODO lists" todo)
2985 (repeat ,org-sorting-choice))
2986 (cons (const :tag "Strategy for Tags matches" tags)
2987 (repeat ,org-sorting-choice)))))
2989 (defcustom org-sort-agenda-notime-is-late t
2990 "Non-nil means, items without time are considered late.
2991 This is only relevant for sorting. When t, items which have no explicit
2992 time like 15:30 will be considered as 99:01, i.e. later than any items which
2993 do have a time. When nil, the default time is before 0:00. You can use this
2994 option to decide if the schedule for today should come before or after timeless
2995 agenda entries."
2996 :group 'org-agenda-sorting
2997 :type 'boolean)
2999 (defgroup org-agenda-line-format nil
3000 "Options concerning the entry prefix in the Org-mode agenda display."
3001 :tag "Org Agenda Line Format"
3002 :group 'org-agenda)
3004 (defcustom org-agenda-prefix-format
3005 '((agenda . " %-12:c%?-12t% s")
3006 (timeline . " % s")
3007 (todo . " %-12:c")
3008 (tags . " %-12:c")
3009 (search . " %-12:c"))
3010 "Format specifications for the prefix of items in the agenda views.
3011 An alist with four entries, for the different agenda types. The keys to the
3012 sublists are `agenda', `timeline', `todo', and `tags'. The values
3013 are format strings.
3014 This format works similar to a printf format, with the following meaning:
3016 %c the category of the item, \"Diary\" for entries from the diary, or
3017 as given by the CATEGORY keyword or derived from the file name.
3018 %T the *last* tag of the item. Last because inherited tags come
3019 first in the list.
3020 %t the time-of-day specification if one applies to the entry, in the
3021 format HH:MM
3022 %s Scheduling/Deadline information, a short string
3024 All specifiers work basically like the standard `%s' of printf, but may
3025 contain two additional characters: A question mark just after the `%' and
3026 a whitespace/punctuation character just before the final letter.
3028 If the first character after `%' is a question mark, the entire field
3029 will only be included if the corresponding value applies to the
3030 current entry. This is useful for fields which should have fixed
3031 width when present, but zero width when absent. For example,
3032 \"%?-12t\" will result in a 12 character time field if a time of the
3033 day is specified, but will completely disappear in entries which do
3034 not contain a time.
3036 If there is punctuation or whitespace character just before the final
3037 format letter, this character will be appended to the field value if
3038 the value is not empty. For example, the format \"%-12:c\" leads to
3039 \"Diary: \" if the category is \"Diary\". If the category were be
3040 empty, no additional colon would be interted.
3042 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3043 - Indent the line with two space characters
3044 - Give the category in a 12 chars wide field, padded with whitespace on
3045 the right (because of `-'). Append a colon if there is a category
3046 (because of `:').
3047 - If there is a time-of-day, put it into a 12 chars wide field. If no
3048 time, don't put in an empty field, just skip it (because of '?').
3049 - Finally, put the scheduling information and append a whitespace.
3051 As another example, if you don't want the time-of-day of entries in
3052 the prefix, you could use:
3054 (setq org-agenda-prefix-format \" %-11:c% s\")
3056 See also the variables `org-agenda-remove-times-when-in-prefix' and
3057 `org-agenda-remove-tags'."
3058 :type '(choice
3059 (string :tag "General format")
3060 (list :greedy t :tag "View dependent"
3061 (cons (const agenda) (string :tag "Format"))
3062 (cons (const timeline) (string :tag "Format"))
3063 (cons (const todo) (string :tag "Format"))
3064 (cons (const tags) (string :tag "Format"))
3065 (cons (const search) (string :tag "Format"))))
3066 :group 'org-agenda-line-format)
3068 (defvar org-prefix-format-compiled nil
3069 "The compiled version of the most recently used prefix format.
3070 See the variable `org-agenda-prefix-format'.")
3072 (defcustom org-agenda-todo-keyword-format "%-1s"
3073 "Format for the TODO keyword in agenda lines.
3074 Set this to something like \"%-12s\" if you want all TODO keywords
3075 to occupy a fixed space in the agenda display."
3076 :group 'org-agenda-line-format
3077 :type 'string)
3079 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3080 "Text preceeding scheduled items in the agenda view.
3081 This is a list with two strings. The first applies when the item is
3082 scheduled on the current day. The second applies when it has been scheduled
3083 previously, it may contain a %d to capture how many days ago the item was
3084 scheduled."
3085 :group 'org-agenda-line-format
3086 :type '(list
3087 (string :tag "Scheduled today ")
3088 (string :tag "Scheduled previously")))
3090 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3091 "Text preceeding deadline items in the agenda view.
3092 This is a list with two strings. The first applies when the item has its
3093 deadline on the current day. The second applies when it is in the past or
3094 in the future, it may contain %d to capture how many days away the deadline
3095 is (was)."
3096 :group 'org-agenda-line-format
3097 :type '(list
3098 (string :tag "Deadline today ")
3099 (string :tag "Deadline relative")))
3101 (defcustom org-agenda-remove-times-when-in-prefix t
3102 "Non-nil means, remove duplicate time specifications in agenda items.
3103 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3104 time-of-day specification in a headline or diary entry is extracted and
3105 placed into the prefix. If this option is non-nil, the original specification
3106 \(a timestamp or -range, or just a plain time(range) specification like
3107 11:30-4pm) will be removed for agenda display. This makes the agenda less
3108 cluttered.
3109 The option can be t or nil. It may also be the symbol `beg', indicating
3110 that the time should only be removed what it is located at the beginning of
3111 the headline/diary entry."
3112 :group 'org-agenda-line-format
3113 :type '(choice
3114 (const :tag "Always" t)
3115 (const :tag "Never" nil)
3116 (const :tag "When at beginning of entry" beg)))
3119 (defcustom org-agenda-default-appointment-duration nil
3120 "Default duration for appointments that only have a starting time.
3121 When nil, no duration is specified in such cases.
3122 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3123 :group 'org-agenda-line-format
3124 :type '(choice
3125 (integer :tag "Minutes")
3126 (const :tag "No default duration")))
3129 (defcustom org-agenda-remove-tags nil
3130 "Non-nil means, remove the tags from the headline copy in the agenda.
3131 When this is the symbol `prefix', only remove tags when
3132 `org-agenda-prefix-format' contains a `%T' specifier."
3133 :group 'org-agenda-line-format
3134 :type '(choice
3135 (const :tag "Always" t)
3136 (const :tag "Never" nil)
3137 (const :tag "When prefix format contains %T" prefix)))
3139 (if (fboundp 'defvaralias)
3140 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3141 'org-agenda-remove-tags))
3143 (defcustom org-agenda-tags-column -80
3144 "Shift tags in agenda items to this column.
3145 If this number is positive, it specifies the column. If it is negative,
3146 it means that the tags should be flushright to that column. For example,
3147 -80 works well for a normal 80 character screen."
3148 :group 'org-agenda-line-format
3149 :type 'integer)
3151 (if (fboundp 'defvaralias)
3152 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3154 (defcustom org-agenda-fontify-priorities t
3155 "Non-nil means, highlight low and high priorities in agenda.
3156 When t, the highest priority entries are bold, lowest priority italic.
3157 This may also be an association list of priority faces. The face may be
3158 a names face, or a list like `(:background \"Red\")'."
3159 :group 'org-agenda-line-format
3160 :type '(choice
3161 (const :tag "Never" nil)
3162 (const :tag "Defaults" t)
3163 (repeat :tag "Specify"
3164 (list (character :tag "Priority" :value ?A)
3165 (sexp :tag "face")))))
3167 (defgroup org-latex nil
3168 "Options for embedding LaTeX code into Org-mode"
3169 :tag "Org LaTeX"
3170 :group 'org)
3172 (defcustom org-format-latex-options
3173 '(:foreground default :background default :scale 1.0
3174 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3175 :matchers ("begin" "$" "$$" "\\(" "\\["))
3176 "Options for creating images from LaTeX fragments.
3177 This is a property list with the following properties:
3178 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3179 `default' means use the forground of the default face.
3180 :background the background color, or \"Transparent\".
3181 `default' means use the background of the default face.
3182 :scale a scaling factor for the size of the images
3183 :html-foreground, :html-background, :html-scale
3184 The same numbers for HTML export.
3185 :matchers a list indicating which matchers should be used to
3186 find LaTeX fragments. Valid members of this list are:
3187 \"begin\" find environments
3188 \"$\" find math expressions surrounded by $...$
3189 \"$$\" find math expressions surrounded by $$....$$
3190 \"\\(\" find math expressions surrounded by \\(...\\)
3191 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3192 :group 'org-latex
3193 :type 'plist)
3195 (defcustom org-format-latex-header "\\documentclass{article}
3196 \\usepackage{fullpage} % do not remove
3197 \\usepackage{amssymb}
3198 \\usepackage[usenames]{color}
3199 \\usepackage{amsmath}
3200 \\usepackage{latexsym}
3201 \\usepackage[mathscr]{eucal}
3202 \\pagestyle{empty} % do not remove"
3203 "The document header used for processing LaTeX fragments."
3204 :group 'org-latex
3205 :type 'string)
3207 (defgroup org-export nil
3208 "Options for exporting org-listings."
3209 :tag "Org Export"
3210 :group 'org)
3212 (defgroup org-export-general nil
3213 "General options for exporting Org-mode files."
3214 :tag "Org Export General"
3215 :group 'org-export)
3217 ;; FIXME
3218 (defvar org-export-publishing-directory nil)
3220 (defcustom org-export-with-special-strings t
3221 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3222 When this option is turned on, these strings will be exported as:
3224 Org HTML LaTeX
3225 -----+----------+--------
3226 \\- &shy; \\-
3227 -- &ndash; --
3228 --- &mdash; ---
3229 ... &hellip; \ldots
3231 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3232 :group 'org-export-translation
3233 :type 'boolean)
3235 (defcustom org-export-language-setup
3236 '(("en" "Author" "Date" "Table of Contents")
3237 ("cs" "Autor" "Datum" "Obsah")
3238 ("da" "Ophavsmand" "Dato" "Indhold")
3239 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3240 ("es" "Autor" "Fecha" "\xcdndice")
3241 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3242 ("it" "Autore" "Data" "Indice")
3243 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3244 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3245 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3246 "Terms used in export text, translated to different languages.
3247 Use the variable `org-export-default-language' to set the language,
3248 or use the +OPTION lines for a per-file setting."
3249 :group 'org-export-general
3250 :type '(repeat
3251 (list
3252 (string :tag "HTML language tag")
3253 (string :tag "Author")
3254 (string :tag "Date")
3255 (string :tag "Table of Contents"))))
3257 (defcustom org-export-default-language "en"
3258 "The default language of HTML export, as a string.
3259 This should have an association in `org-export-language-setup'."
3260 :group 'org-export-general
3261 :type 'string)
3263 (defcustom org-export-skip-text-before-1st-heading t
3264 "Non-nil means, skip all text before the first headline when exporting.
3265 When nil, that text is exported as well."
3266 :group 'org-export-general
3267 :type 'boolean)
3269 (defcustom org-export-headline-levels 3
3270 "The last level which is still exported as a headline.
3271 Inferior levels will produce itemize lists when exported.
3272 Note that a numeric prefix argument to an exporter function overrides
3273 this setting.
3275 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3276 :group 'org-export-general
3277 :type 'number)
3279 (defcustom org-export-with-section-numbers t
3280 "Non-nil means, add section numbers to headlines when exporting.
3282 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3283 :group 'org-export-general
3284 :type 'boolean)
3286 (defcustom org-export-with-toc t
3287 "Non-nil means, create a table of contents in exported files.
3288 The TOC contains headlines with levels up to`org-export-headline-levels'.
3289 When an integer, include levels up to N in the toc, this may then be
3290 different from `org-export-headline-levels', but it will not be allowed
3291 to be larger than the number of headline levels.
3292 When nil, no table of contents is made.
3294 Headlines which contain any TODO items will be marked with \"(*)\" in
3295 ASCII export, and with red color in HTML output, if the option
3296 `org-export-mark-todo-in-toc' is set.
3298 In HTML output, the TOC will be clickable.
3300 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3301 or \"toc:3\"."
3302 :group 'org-export-general
3303 :type '(choice
3304 (const :tag "No Table of Contents" nil)
3305 (const :tag "Full Table of Contents" t)
3306 (integer :tag "TOC to level")))
3308 (defcustom org-export-mark-todo-in-toc nil
3309 "Non-nil means, mark TOC lines that contain any open TODO items."
3310 :group 'org-export-general
3311 :type 'boolean)
3313 (defcustom org-export-preserve-breaks nil
3314 "Non-nil means, preserve all line breaks when exporting.
3315 Normally, in HTML output paragraphs will be reformatted. In ASCII
3316 export, line breaks will always be preserved, regardless of this variable.
3318 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3319 :group 'org-export-general
3320 :type 'boolean)
3322 (defcustom org-export-with-archived-trees 'headline
3323 "Whether subtrees with the ARCHIVE tag should be exported.
3324 This can have three different values
3325 nil Do not export, pretend this tree is not present
3326 t Do export the entire tree
3327 headline Only export the headline, but skip the tree below it."
3328 :group 'org-export-general
3329 :group 'org-archive
3330 :type '(choice
3331 (const :tag "not at all" nil)
3332 (const :tag "headline only" 'headline)
3333 (const :tag "entirely" t)))
3335 (defcustom org-export-author-info t
3336 "Non-nil means, insert author name and email into the exported file.
3338 This option can also be set with the +OPTIONS line,
3339 e.g. \"author-info:nil\"."
3340 :group 'org-export-general
3341 :type 'boolean)
3343 (defcustom org-export-time-stamp-file t
3344 "Non-nil means, insert a time stamp into the exported file.
3345 The time stamp shows when the file was created.
3347 This option can also be set with the +OPTIONS line,
3348 e.g. \"timestamp:nil\"."
3349 :group 'org-export-general
3350 :type 'boolean)
3352 (defcustom org-export-with-timestamps t
3353 "If nil, do not export time stamps and associated keywords."
3354 :group 'org-export-general
3355 :type 'boolean)
3357 (defcustom org-export-remove-timestamps-from-toc t
3358 "If nil, remove timestamps from the table of contents entries."
3359 :group 'org-export-general
3360 :type 'boolean)
3362 (defcustom org-export-with-tags 'not-in-toc
3363 "If nil, do not export tags, just remove them from headlines.
3364 If this is the symbol `not-in-toc', tags will be removed from table of
3365 contents entries, but still be shown in the headlines of the document.
3367 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3368 :group 'org-export-general
3369 :type '(choice
3370 (const :tag "Off" nil)
3371 (const :tag "Not in TOC" not-in-toc)
3372 (const :tag "On" t)))
3374 (defcustom org-export-with-drawers nil
3375 "Non-nil means, export with drawers like the property drawer.
3376 When t, all drawers are exported. This may also be a list of
3377 drawer names to export."
3378 :group 'org-export-general
3379 :type '(choice
3380 (const :tag "All drawers" t)
3381 (const :tag "None" nil)
3382 (repeat :tag "Selected drawers"
3383 (string :tag "Drawer name"))))
3385 (defgroup org-export-translation nil
3386 "Options for translating special ascii sequences for the export backends."
3387 :tag "Org Export Translation"
3388 :group 'org-export)
3390 (defcustom org-export-with-emphasize t
3391 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3392 If the export target supports emphasizing text, the word will be
3393 typeset in bold, italic, or underlined, respectively. Works only for
3394 single words, but you can say: I *really* *mean* *this*.
3395 Not all export backends support this.
3397 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3398 :group 'org-export-translation
3399 :type 'boolean)
3401 (defcustom org-export-with-footnotes t
3402 "If nil, export [1] as a footnote marker.
3403 Lines starting with [1] will be formatted as footnotes.
3405 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3406 :group 'org-export-translation
3407 :type 'boolean)
3409 (defcustom org-export-with-sub-superscripts t
3410 "Non-nil means, interpret \"_\" and \"^\" for export.
3411 When this option is turned on, you can use TeX-like syntax for sub- and
3412 superscripts. Several characters after \"_\" or \"^\" will be
3413 considered as a single item - so grouping with {} is normally not
3414 needed. For example, the following things will be parsed as single
3415 sub- or superscripts.
3417 10^24 or 10^tau several digits will be considered 1 item.
3418 10^-12 or 10^-tau a leading sign with digits or a word
3419 x^2-y^3 will be read as x^2 - y^3, because items are
3420 terminated by almost any nonword/nondigit char.
3421 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3423 Still, ambiguity is possible - so when in doubt use {} to enclose the
3424 sub/superscript. If you set this variable to the symbol `{}',
3425 the braces are *required* in order to trigger interpretations as
3426 sub/superscript. This can be helpful in documents that need \"_\"
3427 frequently in plain text.
3429 Not all export backends support this, but HTML does.
3431 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3432 :group 'org-export-translation
3433 :type '(choice
3434 (const :tag "Always interpret" t)
3435 (const :tag "Only with braces" {})
3436 (const :tag "Never interpret" nil)))
3438 (defcustom org-export-with-special-strings t
3439 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3440 When this option is turned on, these strings will be exported as:
3442 \\- : &shy;
3443 -- : &ndash;
3444 --- : &mdash;
3446 Not all export backends support this, but HTML does.
3448 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3449 :group 'org-export-translation
3450 :type 'boolean)
3452 (defcustom org-export-with-TeX-macros t
3453 "Non-nil means, interpret simple TeX-like macros when exporting.
3454 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3455 No only real TeX macros will work here, but the standard HTML entities
3456 for math can be used as macro names as well. For a list of supported
3457 names in HTML export, see the constant `org-html-entities'.
3458 Not all export backends support this.
3460 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3461 :group 'org-export-translation
3462 :group 'org-export-latex
3463 :type 'boolean)
3465 (defcustom org-export-with-LaTeX-fragments nil
3466 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3467 When set, the exporter will find LaTeX environments if the \\begin line is
3468 the first non-white thing on a line. It will also find the math delimiters
3469 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3470 display math.
3472 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3473 :group 'org-export-translation
3474 :group 'org-export-latex
3475 :type 'boolean)
3477 (defcustom org-export-with-fixed-width t
3478 "Non-nil means, lines starting with \":\" will be in fixed width font.
3479 This can be used to have pre-formatted text, fragments of code etc. For
3480 example:
3481 : ;; Some Lisp examples
3482 : (while (defc cnt)
3483 : (ding))
3484 will be looking just like this in also HTML. See also the QUOTE keyword.
3485 Not all export backends support this.
3487 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3488 :group 'org-export-translation
3489 :type 'boolean)
3491 (defcustom org-match-sexp-depth 3
3492 "Number of stacked braces for sub/superscript matching.
3493 This has to be set before loading org.el to be effective."
3494 :group 'org-export-translation
3495 :type 'integer)
3497 (defgroup org-export-tables nil
3498 "Options for exporting tables in Org-mode."
3499 :tag "Org Export Tables"
3500 :group 'org-export)
3502 (defcustom org-export-with-tables t
3503 "If non-nil, lines starting with \"|\" define a table.
3504 For example:
3506 | Name | Address | Birthday |
3507 |-------------+----------+-----------|
3508 | Arthur Dent | England | 29.2.2100 |
3510 Not all export backends support this.
3512 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3513 :group 'org-export-tables
3514 :type 'boolean)
3516 (defcustom org-export-highlight-first-table-line t
3517 "Non-nil means, highlight the first table line.
3518 In HTML export, this means use <th> instead of <td>.
3519 In tables created with table.el, this applies to the first table line.
3520 In Org-mode tables, all lines before the first horizontal separator
3521 line will be formatted with <th> tags."
3522 :group 'org-export-tables
3523 :type 'boolean)
3525 (defcustom org-export-table-remove-special-lines t
3526 "Remove special lines and marking characters in calculating tables.
3527 This removes the special marking character column from tables that are set
3528 up for spreadsheet calculations. It also removes the entire lines
3529 marked with `!', `_', or `^'. The lines with `$' are kept, because
3530 the values of constants may be useful to have."
3531 :group 'org-export-tables
3532 :type 'boolean)
3534 (defcustom org-export-prefer-native-exporter-for-tables nil
3535 "Non-nil means, always export tables created with table.el natively.
3536 Natively means, use the HTML code generator in table.el.
3537 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3538 the table does not use row- or column-spanning). This has the
3539 advantage, that the automatic HTML conversions for math symbols and
3540 sub/superscripts can be applied. Org-mode's HTML generator is also
3541 much faster."
3542 :group 'org-export-tables
3543 :type 'boolean)
3545 (defgroup org-export-ascii nil
3546 "Options specific for ASCII export of Org-mode files."
3547 :tag "Org Export ASCII"
3548 :group 'org-export)
3550 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3551 "Characters for underlining headings in ASCII export.
3552 In the given sequence, these characters will be used for level 1, 2, ..."
3553 :group 'org-export-ascii
3554 :type '(repeat character))
3556 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3557 "Bullet characters for headlines converted to lists in ASCII export.
3558 The first character is used for the first lest level generated in this
3559 way, and so on. If there are more levels than characters given here,
3560 the list will be repeated.
3561 Note that plain lists will keep the same bullets as the have in the
3562 Org-mode file."
3563 :group 'org-export-ascii
3564 :type '(repeat character))
3566 (defgroup org-export-xml nil
3567 "Options specific for XML export of Org-mode files."
3568 :tag "Org Export XML"
3569 :group 'org-export)
3571 (defgroup org-export-html nil
3572 "Options specific for HTML export of Org-mode files."
3573 :tag "Org Export HTML"
3574 :group 'org-export)
3576 (defcustom org-export-html-coding-system nil
3578 :group 'org-export-html
3579 :type 'coding-system)
3581 (defcustom org-export-html-extension "html"
3582 "The extension for exported HTML files."
3583 :group 'org-export-html
3584 :type 'string)
3586 (defcustom org-export-html-style
3587 "<style type=\"text/css\">
3588 html {
3589 font-family: Times, serif;
3590 font-size: 12pt;
3592 .title { text-align: center; }
3593 .todo { color: red; }
3594 .done { color: green; }
3595 .timestamp { color: grey }
3596 .timestamp-kwd { color: CadetBlue }
3597 .tag { background-color:lightblue; font-weight:normal }
3598 .target { background-color: lavender; }
3599 pre {
3600 border: 1pt solid #AEBDCC;
3601 background-color: #F3F5F7;
3602 padding: 5pt;
3603 font-family: courier, monospace;
3605 table { border-collapse: collapse; }
3606 td, th {
3607 vertical-align: top;
3608 <!--border: 1pt solid #ADB9CC;-->
3610 </style>"
3611 "The default style specification for exported HTML files.
3612 Since there are different ways of setting style information, this variable
3613 needs to contain the full HTML structure to provide a style, including the
3614 surrounding HTML tags. The style specifications should include definitions
3615 for new classes todo, done, title, and deadline. For example, valid values
3616 would be:
3618 <style type=\"text/css\">
3619 p { font-weight: normal; color: gray; }
3620 h1 { color: black; }
3621 .title { text-align: center; }
3622 .todo, .deadline { color: red; }
3623 .done { color: green; }
3624 </style>
3626 or, if you want to keep the style in a file,
3628 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3630 As the value of this option simply gets inserted into the HTML <head> header,
3631 you can \"misuse\" it to add arbitrary text to the header."
3632 :group 'org-export-html
3633 :type 'string)
3636 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3637 "Format for typesetting the document title in HTML export."
3638 :group 'org-export-html
3639 :type 'string)
3641 (defcustom org-export-html-toplevel-hlevel 2
3642 "The <H> level for level 1 headings in HTML export."
3643 :group 'org-export-html
3644 :type 'string)
3646 (defcustom org-export-html-link-org-files-as-html t
3647 "Non-nil means, make file links to `file.org' point to `file.html'.
3648 When org-mode is exporting an org-mode file to HTML, links to
3649 non-html files are directly put into a href tag in HTML.
3650 However, links to other Org-mode files (recognized by the
3651 extension `.org.) should become links to the corresponding html
3652 file, assuming that the linked org-mode file will also be
3653 converted to HTML.
3654 When nil, the links still point to the plain `.org' file."
3655 :group 'org-export-html
3656 :type 'boolean)
3658 (defcustom org-export-html-inline-images 'maybe
3659 "Non-nil means, inline images into exported HTML pages.
3660 This is done using an <img> tag. When nil, an anchor with href is used to
3661 link to the image. If this option is `maybe', then images in links with
3662 an empty description will be inlined, while images with a description will
3663 be linked only."
3664 :group 'org-export-html
3665 :type '(choice (const :tag "Never" nil)
3666 (const :tag "Always" t)
3667 (const :tag "When there is no description" maybe)))
3669 ;; FIXME: rename
3670 (defcustom org-export-html-expand t
3671 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3672 When nil, these tags will be exported as plain text and therefore
3673 not be interpreted by a browser.
3675 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3676 :group 'org-export-html
3677 :type 'boolean)
3679 (defcustom org-export-html-table-tag
3680 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3681 "The HTML tag that is used to start a table.
3682 This must be a <table> tag, but you may change the options like
3683 borders and spacing."
3684 :group 'org-export-html
3685 :type 'string)
3687 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3688 "The opening tag for table header fields.
3689 This is customizable so that alignment options can be specified."
3690 :group 'org-export-tables
3691 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3693 (defcustom org-export-table-data-tags '("<td>" . "</td>")
3694 "The opening tag for table data fields.
3695 This is customizable so that alignment options can be specified."
3696 :group 'org-export-tables
3697 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3699 (defcustom org-export-html-with-timestamp nil
3700 "If non-nil, write `org-export-html-html-helper-timestamp'
3701 into the exported HTML text. Otherwise, the buffer will just be saved
3702 to a file."
3703 :group 'org-export-html
3704 :type 'boolean)
3706 (defcustom org-export-html-html-helper-timestamp
3707 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3708 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3709 :group 'org-export-html
3710 :type 'string)
3712 (defgroup org-export-icalendar nil
3713 "Options specific for iCalendar export of Org-mode files."
3714 :tag "Org Export iCalendar"
3715 :group 'org-export)
3717 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3718 "The file name for the iCalendar file covering all agenda files.
3719 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3720 The file name should be absolute, the file will be overwritten without warning."
3721 :group 'org-export-icalendar
3722 :type 'file)
3724 (defcustom org-icalendar-include-todo nil
3725 "Non-nil means, export to iCalendar files should also cover TODO items."
3726 :group 'org-export-icalendar
3727 :type '(choice
3728 (const :tag "None" nil)
3729 (const :tag "Unfinished" t)
3730 (const :tag "All" all)))
3732 (defcustom org-icalendar-include-sexps t
3733 "Non-nil means, export to iCalendar files should also cover sexp entries.
3734 These are entries like in the diary, but directly in an Org-mode file."
3735 :group 'org-export-icalendar
3736 :type 'boolean)
3738 (defcustom org-icalendar-include-body 100
3739 "Amount of text below headline to be included in iCalendar export.
3740 This is a number of characters that should maximally be included.
3741 Properties, scheduling and clocking lines will always be removed.
3742 The text will be inserted into the DESCRIPTION field."
3743 :group 'org-export-icalendar
3744 :type '(choice
3745 (const :tag "Nothing" nil)
3746 (const :tag "Everything" t)
3747 (integer :tag "Max characters")))
3749 (defcustom org-icalendar-combined-name "OrgMode"
3750 "Calendar name for the combined iCalendar representing all agenda files."
3751 :group 'org-export-icalendar
3752 :type 'string)
3754 (defgroup org-font-lock nil
3755 "Font-lock settings for highlighting in Org-mode."
3756 :tag "Org Font Lock"
3757 :group 'org)
3759 (defcustom org-level-color-stars-only nil
3760 "Non-nil means fontify only the stars in each headline.
3761 When nil, the entire headline is fontified.
3762 Changing it requires restart of `font-lock-mode' to become effective
3763 also in regions already fontified."
3764 :group 'org-font-lock
3765 :type 'boolean)
3767 (defcustom org-hide-leading-stars nil
3768 "Non-nil means, hide the first N-1 stars in a headline.
3769 This works by using the face `org-hide' for these stars. This
3770 face is white for a light background, and black for a dark
3771 background. You may have to customize the face `org-hide' to
3772 make this work.
3773 Changing it requires restart of `font-lock-mode' to become effective
3774 also in regions already fontified.
3775 You may also set this on a per-file basis by adding one of the following
3776 lines to the buffer:
3778 #+STARTUP: hidestars
3779 #+STARTUP: showstars"
3780 :group 'org-font-lock
3781 :type 'boolean)
3783 (defcustom org-fontify-done-headline nil
3784 "Non-nil means, change the face of a headline if it is marked DONE.
3785 Normally, only the TODO/DONE keyword indicates the state of a headline.
3786 When this is non-nil, the headline after the keyword is set to the
3787 `org-headline-done' as an additional indication."
3788 :group 'org-font-lock
3789 :type 'boolean)
3791 (defcustom org-fontify-emphasized-text t
3792 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3793 Changing this variable requires a restart of Emacs to take effect."
3794 :group 'org-font-lock
3795 :type 'boolean)
3797 (defcustom org-highlight-latex-fragments-and-specials nil
3798 "Non-nil means, fontify what is treated specially by the exporters."
3799 :group 'org-font-lock
3800 :type 'boolean)
3802 (defcustom org-hide-emphasis-markers nil
3803 "Non-nil mean font-lock should hide the emphasis marker characters."
3804 :group 'org-font-lock
3805 :type 'boolean)
3807 (defvar org-emph-re nil
3808 "Regular expression for matching emphasis.")
3809 (defvar org-verbatim-re nil
3810 "Regular expression for matching verbatim text.")
3811 (defvar org-emphasis-regexp-components) ; defined just below
3812 (defvar org-emphasis-alist) ; defined just below
3813 (defun org-set-emph-re (var val)
3814 "Set variable and compute the emphasis regular expression."
3815 (set var val)
3816 (when (and (boundp 'org-emphasis-alist)
3817 (boundp 'org-emphasis-regexp-components)
3818 org-emphasis-alist org-emphasis-regexp-components)
3819 (let* ((e org-emphasis-regexp-components)
3820 (pre (car e))
3821 (post (nth 1 e))
3822 (border (nth 2 e))
3823 (body (nth 3 e))
3824 (nl (nth 4 e))
3825 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3826 (body1 (concat body "*?"))
3827 (markers (mapconcat 'car org-emphasis-alist ""))
3828 (vmarkers (mapconcat
3829 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3830 org-emphasis-alist "")))
3831 ;; make sure special characters appear at the right position in the class
3832 (if (string-match "\\^" markers)
3833 (setq markers (concat (replace-match "" t t markers) "^")))
3834 (if (string-match "-" markers)
3835 (setq markers (concat (replace-match "" t t markers) "-")))
3836 (if (string-match "\\^" vmarkers)
3837 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3838 (if (string-match "-" vmarkers)
3839 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3840 (if (> nl 0)
3841 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3842 (int-to-string nl) "\\}")))
3843 ;; Make the regexp
3844 (setq org-emph-re
3845 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3846 "\\("
3847 "\\([" markers "]\\)"
3848 "\\("
3849 "[^" border "]\\|"
3850 "[^" border (if (and nil stacked) markers) "]"
3851 body1
3852 "[^" border (if (and nil stacked) markers) "]"
3853 "\\)"
3854 "\\3\\)"
3855 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3856 (setq org-verbatim-re
3857 (concat "\\([" pre "]\\|^\\)"
3858 "\\("
3859 "\\([" vmarkers "]\\)"
3860 "\\("
3861 "[^" border "]\\|"
3862 "[^" border "]"
3863 body1
3864 "[^" border "]"
3865 "\\)"
3866 "\\3\\)"
3867 "\\([" post "]\\|$\\)")))))
3869 (defcustom org-emphasis-regexp-components
3870 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3871 "Components used to build the regular expression for emphasis.
3872 This is a list with 6 entries. Terminology: In an emphasis string
3873 like \" *strong word* \", we call the initial space PREMATCH, the final
3874 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3875 and \"trong wor\" is the body. The different components in this variable
3876 specify what is allowed/forbidden in each part:
3878 pre Chars allowed as prematch. Beginning of line will be allowed too.
3879 post Chars allowed as postmatch. End of line will be allowed too.
3880 border The chars *forbidden* as border characters.
3881 body-regexp A regexp like \".\" to match a body character. Don't use
3882 non-shy groups here, and don't allow newline here.
3883 newline The maximum number of newlines allowed in an emphasis exp.
3885 Use customize to modify this, or restart Emacs after changing it."
3886 :group 'org-font-lock
3887 :set 'org-set-emph-re
3888 :type '(list
3889 (sexp :tag "Allowed chars in pre ")
3890 (sexp :tag "Allowed chars in post ")
3891 (sexp :tag "Forbidden chars in border ")
3892 (sexp :tag "Regexp for body ")
3893 (integer :tag "number of newlines allowed")
3894 (option (boolean :tag "Stacking (DISABLED) "))))
3896 (defcustom org-emphasis-alist
3897 '(("*" bold "<b>" "</b>")
3898 ("/" italic "<i>" "</i>")
3899 ("_" underline "<u>" "</u>")
3900 ("=" org-code "<code>" "</code>" verbatim)
3901 ("~" org-verbatim "" "" verbatim)
3902 ("+" (:strike-through t) "<del>" "</del>")
3904 "Special syntax for emphasized text.
3905 Text starting and ending with a special character will be emphasized, for
3906 example *bold*, _underlined_ and /italic/. This variable sets the marker
3907 characters, the face to be used by font-lock for highlighting in Org-mode
3908 Emacs buffers, and the HTML tags to be used for this.
3909 Use customize to modify this, or restart Emacs after changing it."
3910 :group 'org-font-lock
3911 :set 'org-set-emph-re
3912 :type '(repeat
3913 (list
3914 (string :tag "Marker character")
3915 (choice
3916 (face :tag "Font-lock-face")
3917 (plist :tag "Face property list"))
3918 (string :tag "HTML start tag")
3919 (string :tag "HTML end tag")
3920 (option (const verbatim)))))
3922 ;;; The faces
3924 (defgroup org-faces nil
3925 "Faces in Org-mode."
3926 :tag "Org Faces"
3927 :group 'org-font-lock)
3929 (defun org-compatible-face (inherits specs)
3930 "Make a compatible face specification.
3931 If INHERITS is an existing face and if the Emacs version supports it,
3932 just inherit the face. If not, use SPECS to define the face.
3933 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3934 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3935 to the top of the list. The `min-colors' attribute will be removed from
3936 any other entries, and any resulting duplicates will be removed entirely."
3937 (cond
3938 ((and inherits (facep inherits)
3939 (not (featurep 'xemacs)) (> emacs-major-version 22))
3940 ;; In Emacs 23, we use inheritance where possible.
3941 ;; We only do this in Emacs 23, because only there the outline
3942 ;; faces have been changed to the original org-mode-level-faces.
3943 (list (list t :inherit inherits)))
3944 ((or (featurep 'xemacs) (< emacs-major-version 22))
3945 ;; These do not understand the `min-colors' attribute.
3946 (let (r e a)
3947 (while (setq e (pop specs))
3948 (cond
3949 ((memq (car e) '(t default)) (push e r))
3950 ((setq a (member '(min-colors 8) (car e)))
3951 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3952 (cdr e)))))
3953 ((setq a (assq 'min-colors (car e)))
3954 (setq e (cons (delq a (car e)) (cdr e)))
3955 (or (assoc (car e) r) (push e r)))
3956 (t (or (assoc (car e) r) (push e r)))))
3957 (nreverse r)))
3958 (t specs)))
3959 (put 'org-compatible-face 'lisp-indent-function 1)
3961 (defface org-hide
3962 '((((background light)) (:foreground "white"))
3963 (((background dark)) (:foreground "black")))
3964 "Face used to hide leading stars in headlines.
3965 The forground color of this face should be equal to the background
3966 color of the frame."
3967 :group 'org-faces)
3969 (defface org-level-1 ;; font-lock-function-name-face
3970 (org-compatible-face 'outline-1
3971 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3972 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3973 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3974 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3975 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3976 (t (:bold t))))
3977 "Face used for level 1 headlines."
3978 :group 'org-faces)
3980 (defface org-level-2 ;; font-lock-variable-name-face
3981 (org-compatible-face 'outline-2
3982 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3983 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3984 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3985 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3986 (t (:bold t))))
3987 "Face used for level 2 headlines."
3988 :group 'org-faces)
3990 (defface org-level-3 ;; font-lock-keyword-face
3991 (org-compatible-face 'outline-3
3992 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3993 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
3994 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
3995 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
3996 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
3997 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
3998 (t (:bold t))))
3999 "Face used for level 3 headlines."
4000 :group 'org-faces)
4002 (defface org-level-4 ;; font-lock-comment-face
4003 (org-compatible-face 'outline-4
4004 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4005 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4006 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4007 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4008 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4009 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4010 (t (:bold t))))
4011 "Face used for level 4 headlines."
4012 :group 'org-faces)
4014 (defface org-level-5 ;; font-lock-type-face
4015 (org-compatible-face 'outline-5
4016 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4017 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4018 (((class color) (min-colors 8)) (:foreground "green"))))
4019 "Face used for level 5 headlines."
4020 :group 'org-faces)
4022 (defface org-level-6 ;; font-lock-constant-face
4023 (org-compatible-face 'outline-6
4024 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4025 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4026 (((class color) (min-colors 8)) (:foreground "magenta"))))
4027 "Face used for level 6 headlines."
4028 :group 'org-faces)
4030 (defface org-level-7 ;; font-lock-builtin-face
4031 (org-compatible-face 'outline-7
4032 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4033 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4034 (((class color) (min-colors 8)) (:foreground "blue"))))
4035 "Face used for level 7 headlines."
4036 :group 'org-faces)
4038 (defface org-level-8 ;; font-lock-string-face
4039 (org-compatible-face 'outline-8
4040 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4041 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4042 (((class color) (min-colors 8)) (:foreground "green"))))
4043 "Face used for level 8 headlines."
4044 :group 'org-faces)
4046 (defface org-special-keyword ;; font-lock-string-face
4047 (org-compatible-face nil
4048 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4049 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4050 (t (:italic t))))
4051 "Face used for special keywords."
4052 :group 'org-faces)
4054 (defface org-drawer ;; font-lock-function-name-face
4055 (org-compatible-face nil
4056 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4057 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4058 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4059 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4060 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4061 (t (:bold t))))
4062 "Face used for drawers."
4063 :group 'org-faces)
4065 (defface org-property-value nil
4066 "Face used for the value of a property."
4067 :group 'org-faces)
4069 (defface org-column
4070 (org-compatible-face nil
4071 '((((class color) (min-colors 16) (background light))
4072 (:background "grey90"))
4073 (((class color) (min-colors 16) (background dark))
4074 (:background "grey30"))
4075 (((class color) (min-colors 8))
4076 (:background "cyan" :foreground "black"))
4077 (t (:inverse-video t))))
4078 "Face for column display of entry properties."
4079 :group 'org-faces)
4081 (when (fboundp 'set-face-attribute)
4082 ;; Make sure that a fixed-width face is used when we have a column table.
4083 (set-face-attribute 'org-column nil
4084 :height (face-attribute 'default :height)
4085 :family (face-attribute 'default :family)))
4087 (defface org-warning
4088 (org-compatible-face 'font-lock-warning-face
4089 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4090 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4091 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4092 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4093 (t (:bold t))))
4094 "Face for deadlines and TODO keywords."
4095 :group 'org-faces)
4097 (defface org-archived ; similar to shadow
4098 (org-compatible-face 'shadow
4099 '((((class color grayscale) (min-colors 88) (background light))
4100 (:foreground "grey50"))
4101 (((class color grayscale) (min-colors 88) (background dark))
4102 (:foreground "grey70"))
4103 (((class color) (min-colors 8) (background light))
4104 (:foreground "green"))
4105 (((class color) (min-colors 8) (background dark))
4106 (:foreground "yellow"))))
4107 "Face for headline with the ARCHIVE tag."
4108 :group 'org-faces)
4110 (defface org-link
4111 '((((class color) (background light)) (:foreground "Purple" :underline t))
4112 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4113 (t (:underline t)))
4114 "Face for links."
4115 :group 'org-faces)
4117 (defface org-ellipsis
4118 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4119 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4120 (t (:strike-through t)))
4121 "Face for the ellipsis in folded text."
4122 :group 'org-faces)
4124 (defface org-target
4125 '((((class color) (background light)) (:underline t))
4126 (((class color) (background dark)) (:underline t))
4127 (t (:underline t)))
4128 "Face for links."
4129 :group 'org-faces)
4131 (defface org-date
4132 '((((class color) (background light)) (:foreground "Purple" :underline t))
4133 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4134 (t (:underline t)))
4135 "Face for links."
4136 :group 'org-faces)
4138 (defface org-sexp-date
4139 '((((class color) (background light)) (:foreground "Purple"))
4140 (((class color) (background dark)) (:foreground "Cyan"))
4141 (t (:underline t)))
4142 "Face for links."
4143 :group 'org-faces)
4145 (defface org-tag
4146 '((t (:bold t)))
4147 "Face for tags."
4148 :group 'org-faces)
4150 (defface org-todo ; font-lock-warning-face
4151 (org-compatible-face nil
4152 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4153 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4154 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4155 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4156 (t (:inverse-video t :bold t))))
4157 "Face for TODO keywords."
4158 :group 'org-faces)
4160 (defface org-done ;; font-lock-type-face
4161 (org-compatible-face nil
4162 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4163 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4164 (((class color) (min-colors 8)) (:foreground "green"))
4165 (t (:bold t))))
4166 "Face used for todo keywords that indicate DONE items."
4167 :group 'org-faces)
4169 (defface org-headline-done ;; font-lock-string-face
4170 (org-compatible-face nil
4171 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4172 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4173 (((class color) (min-colors 8) (background light)) (:bold nil))))
4174 "Face used to indicate that a headline is DONE.
4175 This face is only used if `org-fontify-done-headline' is set. If applies
4176 to the part of the headline after the DONE keyword."
4177 :group 'org-faces)
4179 (defcustom org-todo-keyword-faces nil
4180 "Faces for specific TODO keywords.
4181 This is a list of cons cells, with TODO keywords in the car
4182 and faces in the cdr. The face can be a symbol, or a property
4183 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4184 :group 'org-faces
4185 :group 'org-todo
4186 :type '(repeat
4187 (cons
4188 (string :tag "keyword")
4189 (sexp :tag "face"))))
4191 (defface org-table ;; font-lock-function-name-face
4192 (org-compatible-face nil
4193 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4194 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4195 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4196 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4197 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4198 (((class color) (min-colors 8) (background dark)))))
4199 "Face used for tables."
4200 :group 'org-faces)
4202 (defface org-formula
4203 (org-compatible-face nil
4204 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4205 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4206 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4207 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4208 (t (:bold t :italic t))))
4209 "Face for formulas."
4210 :group 'org-faces)
4212 (defface org-code
4213 (org-compatible-face nil
4214 '((((class color grayscale) (min-colors 88) (background light))
4215 (:foreground "grey50"))
4216 (((class color grayscale) (min-colors 88) (background dark))
4217 (:foreground "grey70"))
4218 (((class color) (min-colors 8) (background light))
4219 (:foreground "green"))
4220 (((class color) (min-colors 8) (background dark))
4221 (:foreground "yellow"))))
4222 "Face for fixed-with text like code snippets."
4223 :group 'org-faces
4224 :version "22.1")
4226 (defface org-verbatim
4227 (org-compatible-face nil
4228 '((((class color grayscale) (min-colors 88) (background light))
4229 (:foreground "grey50" :underline t))
4230 (((class color grayscale) (min-colors 88) (background dark))
4231 (:foreground "grey70" :underline t))
4232 (((class color) (min-colors 8) (background light))
4233 (:foreground "green" :underline t))
4234 (((class color) (min-colors 8) (background dark))
4235 (:foreground "yellow" :underline t))))
4236 "Face for fixed-with text like code snippets."
4237 :group 'org-faces
4238 :version "22.1")
4240 (defface org-agenda-structure ;; font-lock-function-name-face
4241 (org-compatible-face nil
4242 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4243 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4244 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4245 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4246 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4247 (t (:bold t))))
4248 "Face used in agenda for captions and dates."
4249 :group 'org-faces)
4251 (defface org-scheduled-today
4252 (org-compatible-face nil
4253 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4254 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4255 (((class color) (min-colors 8)) (:foreground "green"))
4256 (t (:bold t :italic t))))
4257 "Face for items scheduled for a certain day."
4258 :group 'org-faces)
4260 (defface org-scheduled-previously
4261 (org-compatible-face nil
4262 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4263 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4264 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4265 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4266 (t (:bold t))))
4267 "Face for items scheduled previously, and not yet done."
4268 :group 'org-faces)
4270 (defface org-upcoming-deadline
4271 (org-compatible-face nil
4272 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4273 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4274 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4275 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4276 (t (:bold t))))
4277 "Face for items scheduled previously, and not yet done."
4278 :group 'org-faces)
4280 (defcustom org-agenda-deadline-faces
4281 '((1.0 . org-warning)
4282 (0.5 . org-upcoming-deadline)
4283 (0.0 . default))
4284 "Faces for showing deadlines in the agenda.
4285 This is a list of cons cells. The cdr of each cell is a face to be used,
4286 and it can also just be like '(:foreground \"yellow\").
4287 Each car is a fraction of the head-warning time that must have passed for
4288 this the face in the cdr to be used for display. The numbers must be
4289 given in descending order. The head-warning time is normally taken
4290 from `org-deadline-warning-days', but can also be specified in the deadline
4291 timestamp itself, like this:
4293 DEADLINE: <2007-08-13 Mon -8d>
4295 You may use d for days, w for weeks, m for months and y for years. Months
4296 and years will only be treated in an approximate fashion (30.4 days for a
4297 month and 365.24 days for a year)."
4298 :group 'org-faces
4299 :group 'org-agenda-daily/weekly
4300 :type '(repeat
4301 (cons
4302 (number :tag "Fraction of head-warning time passed")
4303 (sexp :tag "Face"))))
4305 ;; FIXME: this is not a good face yet.
4306 (defface org-agenda-restriction-lock
4307 (org-compatible-face nil
4308 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4309 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4310 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4311 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4312 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4313 (t (:inverse-video t))))
4314 "Face for showing the agenda restriction lock."
4315 :group 'org-faces)
4317 (defface org-time-grid ;; font-lock-variable-name-face
4318 (org-compatible-face nil
4319 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4320 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4321 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4322 "Face used for time grids."
4323 :group 'org-faces)
4325 (defconst org-level-faces
4326 '(org-level-1 org-level-2 org-level-3 org-level-4
4327 org-level-5 org-level-6 org-level-7 org-level-8
4330 (defcustom org-n-level-faces (length org-level-faces)
4331 "The number of different faces to be used for headlines.
4332 Org-mode defines 8 different headline faces, so this can be at most 8.
4333 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4334 :type 'number
4335 :group 'org-faces)
4337 ;;; Functions and variables from ther packages
4338 ;; Declared here to avoid compiler warnings
4340 (eval-and-compile
4341 (unless (fboundp 'declare-function)
4342 (defmacro declare-function (fn file &optional arglist fileonly))))
4344 ;; XEmacs only
4345 (defvar outline-mode-menu-heading)
4346 (defvar outline-mode-menu-show)
4347 (defvar outline-mode-menu-hide)
4348 (defvar zmacs-regions) ; XEmacs regions
4350 ;; Emacs only
4351 (defvar mark-active)
4353 ;; Various packages
4354 ;; FIXME: get the argument lists for the UNKNOWN stuff
4355 (declare-function add-to-diary-list "diary-lib"
4356 (date string specifier &optional marker globcolor literal))
4357 (declare-function table--at-cell-p "table" (position &optional object at-column))
4358 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4359 (declare-function bbdb "ext:bbdb-com" (string elidep))
4360 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4361 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4362 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4363 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4364 (declare-function bbdb-record-name "ext:bbdb" (record))
4365 (declare-function bibtex-beginning-of-entry "bibtex" ())
4366 (declare-function bibtex-generate-autokey "bibtex" ())
4367 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4368 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4369 (defvar calc-embedded-close-formula)
4370 (defvar calc-embedded-open-formula)
4371 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4372 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4373 (declare-function calendar-check-holidays "holidays" (date))
4374 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4375 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4376 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4377 (declare-function calendar-forward-day "cal-move" (arg))
4378 (declare-function calendar-french-date-string "cal-french" (&optional date))
4379 (declare-function calendar-goto-date "cal-move" (date))
4380 (declare-function calendar-goto-today "cal-move" ())
4381 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4382 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4383 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4384 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4385 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4386 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4387 (defvar calendar-mode-map)
4388 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4389 (declare-function cdlatex-tab "ext:cdlatex" ())
4390 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4391 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4392 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4393 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4394 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4395 (defvar font-lock-unfontify-region-function)
4396 (declare-function gnus-article-show-summary "gnus-art" ())
4397 (declare-function gnus-summary-last-subject "gnus-sum" ())
4398 (defvar gnus-other-frame-object)
4399 (defvar gnus-group-name)
4400 (defvar gnus-article-current)
4401 (defvar Info-current-file)
4402 (defvar Info-current-node)
4403 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4404 (declare-function mh-find-path "mh-utils" ())
4405 (declare-function mh-get-header-field "mh-utils" (field))
4406 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4407 (declare-function mh-header-display "mh-show" ())
4408 (declare-function mh-index-previous-folder "mh-search" ())
4409 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4410 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4411 (declare-function mh-search-choose "mh-search" (&optional searcher))
4412 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4413 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4414 (declare-function mh-show-header-display "mh-show" t t)
4415 (declare-function mh-show-msg "mh-show" (msg))
4416 (declare-function mh-show-show "mh-show" t t)
4417 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4418 (defvar mh-progs)
4419 (defvar mh-current-folder)
4420 (defvar mh-show-folder-buffer)
4421 (defvar mh-index-folder)
4422 (defvar mh-searcher)
4423 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4424 (declare-function parse-time-string "parse-time" (string))
4425 (declare-function remember "remember" (&optional initial))
4426 (declare-function remember-buffer-desc "remember" ())
4427 (declare-function remember-finalize "remember" ())
4428 (defvar remember-save-after-remembering)
4429 (defvar remember-data-file)
4430 (defvar remember-register)
4431 (defvar remember-buffer)
4432 (defvar remember-handler-functions)
4433 (defvar remember-annotation-functions)
4434 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4435 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4436 (declare-function rmail-what-message "rmail" ())
4437 (defvar rmail-current-message)
4438 (defvar texmathp-why)
4439 (declare-function vm-beginning-of-message "ext:vm-page" ())
4440 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4441 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4442 (declare-function vm-isearch-narrow "ext:vm-search" ())
4443 (declare-function vm-isearch-update "ext:vm-search" ())
4444 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4445 (declare-function vm-su-message-id "ext:vm-summary" (m))
4446 (declare-function vm-su-subject "ext:vm-summary" (m))
4447 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4448 (defvar vm-message-pointer)
4449 (defvar vm-folder-directory)
4450 (defvar w3m-current-url)
4451 (defvar w3m-current-title)
4452 ;; backward compatibility to old version of wl
4453 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4454 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4455 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4456 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4457 (declare-function wl-summary-line-from "ext:wl-summary" ())
4458 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4459 (declare-function wl-summary-message-number "ext:wl-summary" ())
4460 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4461 (defvar wl-summary-buffer-elmo-folder)
4462 (defvar wl-summary-buffer-folder-name)
4463 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4465 (defvar org-latex-regexps)
4466 (defvar constants-unit-system)
4468 ;;; Variables for pre-computed regular expressions, all buffer local
4470 (defvar org-drawer-regexp nil
4471 "Matches first line of a hidden block.")
4472 (make-variable-buffer-local 'org-drawer-regexp)
4473 (defvar org-todo-regexp nil
4474 "Matches any of the TODO state keywords.")
4475 (make-variable-buffer-local 'org-todo-regexp)
4476 (defvar org-not-done-regexp nil
4477 "Matches any of the TODO state keywords except the last one.")
4478 (make-variable-buffer-local 'org-not-done-regexp)
4479 (defvar org-todo-line-regexp nil
4480 "Matches a headline and puts TODO state into group 2 if present.")
4481 (make-variable-buffer-local 'org-todo-line-regexp)
4482 (defvar org-complex-heading-regexp nil
4483 "Matches a headline and puts everything into groups:
4484 group 1: the stars
4485 group 2: The todo keyword, maybe
4486 group 3: Priority cookie
4487 group 4: True headline
4488 group 5: Tags")
4489 (make-variable-buffer-local 'org-complex-heading-regexp)
4490 (defvar org-todo-line-tags-regexp nil
4491 "Matches a headline and puts TODO state into group 2 if present.
4492 Also put tags into group 4 if tags are present.")
4493 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4494 (defvar org-nl-done-regexp nil
4495 "Matches newline followed by a headline with the DONE keyword.")
4496 (make-variable-buffer-local 'org-nl-done-regexp)
4497 (defvar org-looking-at-done-regexp nil
4498 "Matches the DONE keyword a point.")
4499 (make-variable-buffer-local 'org-looking-at-done-regexp)
4500 (defvar org-ds-keyword-length 12
4501 "Maximum length of the Deadline and SCHEDULED keywords.")
4502 (make-variable-buffer-local 'org-ds-keyword-length)
4503 (defvar org-deadline-regexp nil
4504 "Matches the DEADLINE keyword.")
4505 (make-variable-buffer-local 'org-deadline-regexp)
4506 (defvar org-deadline-time-regexp nil
4507 "Matches the DEADLINE keyword together with a time stamp.")
4508 (make-variable-buffer-local 'org-deadline-time-regexp)
4509 (defvar org-deadline-line-regexp nil
4510 "Matches the DEADLINE keyword and the rest of the line.")
4511 (make-variable-buffer-local 'org-deadline-line-regexp)
4512 (defvar org-scheduled-regexp nil
4513 "Matches the SCHEDULED keyword.")
4514 (make-variable-buffer-local 'org-scheduled-regexp)
4515 (defvar org-scheduled-time-regexp nil
4516 "Matches the SCHEDULED keyword together with a time stamp.")
4517 (make-variable-buffer-local 'org-scheduled-time-regexp)
4518 (defvar org-closed-time-regexp nil
4519 "Matches the CLOSED keyword together with a time stamp.")
4520 (make-variable-buffer-local 'org-closed-time-regexp)
4522 (defvar org-keyword-time-regexp nil
4523 "Matches any of the 4 keywords, together with the time stamp.")
4524 (make-variable-buffer-local 'org-keyword-time-regexp)
4525 (defvar org-keyword-time-not-clock-regexp nil
4526 "Matches any of the 3 keywords, together with the time stamp.")
4527 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4528 (defvar org-maybe-keyword-time-regexp nil
4529 "Matches a timestamp, possibly preceeded by a keyword.")
4530 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4531 (defvar org-planning-or-clock-line-re nil
4532 "Matches a line with planning or clock info.")
4533 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4535 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4536 rear-nonsticky t mouse-map t fontified t)
4537 "Properties to remove when a string without properties is wanted.")
4539 (defsubst org-match-string-no-properties (num &optional string)
4540 (if (featurep 'xemacs)
4541 (let ((s (match-string num string)))
4542 (remove-text-properties 0 (length s) org-rm-props s)
4544 (match-string-no-properties num string)))
4546 (defsubst org-no-properties (s)
4547 (if (fboundp 'set-text-properties)
4548 (set-text-properties 0 (length s) nil s)
4549 (remove-text-properties 0 (length s) org-rm-props s))
4552 (defsubst org-get-alist-option (option key)
4553 (cond ((eq key t) t)
4554 ((eq option t) t)
4555 ((assoc key option) (cdr (assoc key option)))
4556 (t (cdr (assq 'default option)))))
4558 (defsubst org-inhibit-invisibility ()
4559 "Modified `buffer-invisibility-spec' for Emacs 21.
4560 Some ops with invisible text do not work correctly on Emacs 21. For these
4561 we turn off invisibility temporarily. Use this in a `let' form."
4562 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4564 (defsubst org-set-local (var value)
4565 "Make VAR local in current buffer and set it to VALUE."
4566 (set (make-variable-buffer-local var) value))
4568 (defsubst org-mode-p ()
4569 "Check if the current buffer is in Org-mode."
4570 (eq major-mode 'org-mode))
4572 (defsubst org-last (list)
4573 "Return the last element of LIST."
4574 (car (last list)))
4576 (defun org-let (list &rest body)
4577 (eval (cons 'let (cons list body))))
4578 (put 'org-let 'lisp-indent-function 1)
4580 (defun org-let2 (list1 list2 &rest body)
4581 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4582 (put 'org-let2 'lisp-indent-function 2)
4583 (defconst org-startup-options
4584 '(("fold" org-startup-folded t)
4585 ("overview" org-startup-folded t)
4586 ("nofold" org-startup-folded nil)
4587 ("showall" org-startup-folded nil)
4588 ("content" org-startup-folded content)
4589 ("hidestars" org-hide-leading-stars t)
4590 ("showstars" org-hide-leading-stars nil)
4591 ("odd" org-odd-levels-only t)
4592 ("oddeven" org-odd-levels-only nil)
4593 ("align" org-startup-align-all-tables t)
4594 ("noalign" org-startup-align-all-tables nil)
4595 ("customtime" org-display-custom-times t)
4596 ("logdone" org-log-done time)
4597 ("lognotedone" org-log-done note)
4598 ("nologdone" org-log-done nil)
4599 ("lognoteclock-out" org-log-note-clock-out t)
4600 ("nolognoteclock-out" org-log-note-clock-out nil)
4601 ("logrepeat" org-log-repeat state)
4602 ("lognoterepeat" org-log-repeat note)
4603 ("nologrepeat" org-log-repeat nil)
4604 ("constcgs" constants-unit-system cgs)
4605 ("constSI" constants-unit-system SI))
4606 "Variable associated with STARTUP options for org-mode.
4607 Each element is a list of three items: The startup options as written
4608 in the #+STARTUP line, the corresponding variable, and the value to
4609 set this variable to if the option is found. An optional forth element PUSH
4610 means to push this value onto the list in the variable.")
4612 (defun org-set-regexps-and-options ()
4613 "Precompute regular expressions for current buffer."
4614 (when (org-mode-p)
4615 (org-set-local 'org-todo-kwd-alist nil)
4616 (org-set-local 'org-todo-key-alist nil)
4617 (org-set-local 'org-todo-key-trigger nil)
4618 (org-set-local 'org-todo-keywords-1 nil)
4619 (org-set-local 'org-done-keywords nil)
4620 (org-set-local 'org-todo-heads nil)
4621 (org-set-local 'org-todo-sets nil)
4622 (org-set-local 'org-todo-log-states nil)
4623 (let ((re (org-make-options-regexp
4624 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4625 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4626 "CONSTANTS" "PROPERTY" "DRAWERS")))
4627 (splitre "[ \t]+")
4628 kwds kws0 kwsa key log value cat arch tags const links hw dws
4629 tail sep kws1 prio props drawers)
4630 (save-excursion
4631 (save-restriction
4632 (widen)
4633 (goto-char (point-min))
4634 (while (re-search-forward re nil t)
4635 (setq key (match-string 1) value (org-match-string-no-properties 2))
4636 (cond
4637 ((equal key "CATEGORY")
4638 (if (string-match "[ \t]+$" value)
4639 (setq value (replace-match "" t t value)))
4640 (setq cat value))
4641 ((member key '("SEQ_TODO" "TODO"))
4642 (push (cons 'sequence (org-split-string value splitre)) kwds))
4643 ((equal key "TYP_TODO")
4644 (push (cons 'type (org-split-string value splitre)) kwds))
4645 ((equal key "TAGS")
4646 (setq tags (append tags (org-split-string value splitre))))
4647 ((equal key "COLUMNS")
4648 (org-set-local 'org-columns-default-format value))
4649 ((equal key "LINK")
4650 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4651 (push (cons (match-string 1 value)
4652 (org-trim (match-string 2 value)))
4653 links)))
4654 ((equal key "PRIORITIES")
4655 (setq prio (org-split-string value " +")))
4656 ((equal key "PROPERTY")
4657 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4658 (push (cons (match-string 1 value) (match-string 2 value))
4659 props)))
4660 ((equal key "DRAWERS")
4661 (setq drawers (org-split-string value splitre)))
4662 ((equal key "CONSTANTS")
4663 (setq const (append const (org-split-string value splitre))))
4664 ((equal key "STARTUP")
4665 (let ((opts (org-split-string value splitre))
4666 l var val)
4667 (while (setq l (pop opts))
4668 (when (setq l (assoc l org-startup-options))
4669 (setq var (nth 1 l) val (nth 2 l))
4670 (if (not (nth 3 l))
4671 (set (make-local-variable var) val)
4672 (if (not (listp (symbol-value var)))
4673 (set (make-local-variable var) nil))
4674 (set (make-local-variable var) (symbol-value var))
4675 (add-to-list var val))))))
4676 ((equal key "ARCHIVE")
4677 (string-match " *$" value)
4678 (setq arch (replace-match "" t t value))
4679 (remove-text-properties 0 (length arch)
4680 '(face t fontified t) arch)))
4682 (when cat
4683 (org-set-local 'org-category (intern cat))
4684 (push (cons "CATEGORY" cat) props))
4685 (when prio
4686 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4687 (setq prio (mapcar 'string-to-char prio))
4688 (org-set-local 'org-highest-priority (nth 0 prio))
4689 (org-set-local 'org-lowest-priority (nth 1 prio))
4690 (org-set-local 'org-default-priority (nth 2 prio)))
4691 (and props (org-set-local 'org-local-properties (nreverse props)))
4692 (and drawers (org-set-local 'org-drawers drawers))
4693 (and arch (org-set-local 'org-archive-location arch))
4694 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4695 ;; Process the TODO keywords
4696 (unless kwds
4697 ;; Use the global values as if they had been given locally.
4698 (setq kwds (default-value 'org-todo-keywords))
4699 (if (stringp (car kwds))
4700 (setq kwds (list (cons org-todo-interpretation
4701 (default-value 'org-todo-keywords)))))
4702 (setq kwds (reverse kwds)))
4703 (setq kwds (nreverse kwds))
4704 (let (inter kws kw)
4705 (while (setq kws (pop kwds))
4706 (setq inter (pop kws) sep (member "|" kws)
4707 kws0 (delete "|" (copy-sequence kws))
4708 kwsa nil
4709 kws1 (mapcar
4710 (lambda (x)
4711 ;; 1 2
4712 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4713 (progn
4714 (setq kw (match-string 1 x)
4715 key (and (match-end 2) (match-string 2 x))
4716 log (org-extract-log-state-settings x))
4717 (push (cons kw (and key (string-to-char key))) kwsa)
4718 (and log (push log org-todo-log-states))
4720 (error "Invalid TODO keyword %s" x)))
4721 kws0)
4722 kwsa (if kwsa (append '((:startgroup))
4723 (nreverse kwsa)
4724 '((:endgroup))))
4725 hw (car kws1)
4726 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4727 tail (list inter hw (car dws) (org-last dws)))
4728 (add-to-list 'org-todo-heads hw 'append)
4729 (push kws1 org-todo-sets)
4730 (setq org-done-keywords (append org-done-keywords dws nil))
4731 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4732 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4733 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4734 (setq org-todo-sets (nreverse org-todo-sets)
4735 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4736 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4737 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4738 ;; Process the constants
4739 (when const
4740 (let (e cst)
4741 (while (setq e (pop const))
4742 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4743 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4744 (setq org-table-formula-constants-local cst)))
4746 ;; Process the tags.
4747 (when tags
4748 (let (e tgs)
4749 (while (setq e (pop tags))
4750 (cond
4751 ((equal e "{") (push '(:startgroup) tgs))
4752 ((equal e "}") (push '(:endgroup) tgs))
4753 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4754 (push (cons (match-string 1 e)
4755 (string-to-char (match-string 2 e)))
4756 tgs))
4757 (t (push (list e) tgs))))
4758 (org-set-local 'org-tag-alist nil)
4759 (while (setq e (pop tgs))
4760 (or (and (stringp (car e))
4761 (assoc (car e) org-tag-alist))
4762 (push e org-tag-alist))))))
4764 ;; Compute the regular expressions and other local variables
4765 (if (not org-done-keywords)
4766 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4767 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4768 (length org-scheduled-string)))
4769 org-drawer-regexp
4770 (concat "^[ \t]*:\\("
4771 (mapconcat 'regexp-quote org-drawers "\\|")
4772 "\\):[ \t]*$")
4773 org-not-done-keywords
4774 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4775 org-todo-regexp
4776 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4777 "\\|") "\\)\\>")
4778 org-not-done-regexp
4779 (concat "\\<\\("
4780 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4781 "\\)\\>")
4782 org-todo-line-regexp
4783 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4784 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4785 "\\)\\>\\)?[ \t]*\\(.*\\)")
4786 org-complex-heading-regexp
4787 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4788 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4789 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4790 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4791 org-nl-done-regexp
4792 (concat "\n\\*+[ \t]+"
4793 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4794 "\\)" "\\>")
4795 org-todo-line-tags-regexp
4796 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4797 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4798 (org-re
4799 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4800 org-looking-at-done-regexp
4801 (concat "^" "\\(?:"
4802 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4803 "\\>")
4804 org-deadline-regexp (concat "\\<" org-deadline-string)
4805 org-deadline-time-regexp
4806 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4807 org-deadline-line-regexp
4808 (concat "\\<\\(" org-deadline-string "\\).*")
4809 org-scheduled-regexp
4810 (concat "\\<" org-scheduled-string)
4811 org-scheduled-time-regexp
4812 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4813 org-closed-time-regexp
4814 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4815 org-keyword-time-regexp
4816 (concat "\\<\\(" org-scheduled-string
4817 "\\|" org-deadline-string
4818 "\\|" org-closed-string
4819 "\\|" org-clock-string "\\)"
4820 " *[[<]\\([^]>]+\\)[]>]")
4821 org-keyword-time-not-clock-regexp
4822 (concat "\\<\\(" org-scheduled-string
4823 "\\|" org-deadline-string
4824 "\\|" org-closed-string
4825 "\\)"
4826 " *[[<]\\([^]>]+\\)[]>]")
4827 org-maybe-keyword-time-regexp
4828 (concat "\\(\\<\\(" org-scheduled-string
4829 "\\|" org-deadline-string
4830 "\\|" org-closed-string
4831 "\\|" org-clock-string "\\)\\)?"
4832 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4833 org-planning-or-clock-line-re
4834 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string "\\|" org-clock-string
4837 "\\)\\>\\)")
4839 (org-compute-latex-and-specials-regexp)
4840 (org-set-font-lock-defaults)))
4842 (defun org-extract-log-state-settings (x)
4843 "Extract the log state setting from a TODO keyword string.
4844 This will extract info from a string like \"WAIT(w@/!)\"."
4845 (let (kw key log1 log2)
4846 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4847 (setq kw (match-string 1 x)
4848 key (and (match-end 2) (match-string 2 x))
4849 log1 (and (match-end 3) (match-string 3 x))
4850 log2 (and (match-end 4) (match-string 4 x)))
4851 (and (or log1 log2)
4852 (list kw
4853 (and log1 (if (equal log1 "!") 'time 'note))
4854 (and log2 (if (equal log2 "!") 'time 'note)))))))
4856 (defun org-remove-keyword-keys (list)
4857 "Remove a pair of parenthesis at the end of each string in LIST."
4858 (mapcar (lambda (x)
4859 (if (string-match "(.*)$" x)
4860 (substring x 0 (match-beginning 0))
4862 list))
4864 ;; FIXME: this could be done much better, using second characters etc.
4865 (defun org-assign-fast-keys (alist)
4866 "Assign fast keys to a keyword-key alist.
4867 Respect keys that are already there."
4868 (let (new e k c c1 c2 (char ?a))
4869 (while (setq e (pop alist))
4870 (cond
4871 ((equal e '(:startgroup)) (push e new))
4872 ((equal e '(:endgroup)) (push e new))
4874 (setq k (car e) c2 nil)
4875 (if (cdr e)
4876 (setq c (cdr e))
4877 ;; automatically assign a character.
4878 (setq c1 (string-to-char
4879 (downcase (substring
4880 k (if (= (string-to-char k) ?@) 1 0)))))
4881 (if (or (rassoc c1 new) (rassoc c1 alist))
4882 (while (or (rassoc char new) (rassoc char alist))
4883 (setq char (1+ char)))
4884 (setq c2 c1))
4885 (setq c (or c2 char)))
4886 (push (cons k c) new))))
4887 (nreverse new)))
4889 ;;; Some variables ujsed in various places
4891 (defvar org-window-configuration nil
4892 "Used in various places to store a window configuration.")
4893 (defvar org-finish-function nil
4894 "Function to be called when `C-c C-c' is used.
4895 This is for getting out of special buffers like remember.")
4898 ;; FIXME: Occasionally check by commenting these, to make sure
4899 ;; no other functions uses these, forgetting to let-bind them.
4900 (defvar entry)
4901 (defvar state)
4902 (defvar last-state)
4903 (defvar date)
4904 (defvar description)
4906 ;; Defined somewhere in this file, but used before definition.
4907 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4908 (defvar org-agenda-buffer-name)
4909 (defvar org-agenda-undo-list)
4910 (defvar org-agenda-pending-undo-list)
4911 (defvar org-agenda-overriding-header)
4912 (defvar orgtbl-mode)
4913 (defvar org-html-entities)
4914 (defvar org-struct-menu)
4915 (defvar org-org-menu)
4916 (defvar org-tbl-menu)
4917 (defvar org-agenda-keymap)
4919 ;;;; Emacs/XEmacs compatibility
4921 ;; Overlay compatibility functions
4922 (defun org-make-overlay (beg end &optional buffer)
4923 (if (featurep 'xemacs)
4924 (make-extent beg end buffer)
4925 (make-overlay beg end buffer)))
4926 (defun org-delete-overlay (ovl)
4927 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4928 (defun org-detach-overlay (ovl)
4929 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4930 (defun org-move-overlay (ovl beg end &optional buffer)
4931 (if (featurep 'xemacs)
4932 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4933 (move-overlay ovl beg end buffer)))
4934 (defun org-overlay-put (ovl prop value)
4935 (if (featurep 'xemacs)
4936 (set-extent-property ovl prop value)
4937 (overlay-put ovl prop value)))
4938 (defun org-overlay-display (ovl text &optional face evap)
4939 "Make overlay OVL display TEXT with face FACE."
4940 (if (featurep 'xemacs)
4941 (let ((gl (make-glyph text)))
4942 (and face (set-glyph-face gl face))
4943 (set-extent-property ovl 'invisible t)
4944 (set-extent-property ovl 'end-glyph gl))
4945 (overlay-put ovl 'display text)
4946 (if face (overlay-put ovl 'face face))
4947 (if evap (overlay-put ovl 'evaporate t))))
4948 (defun org-overlay-before-string (ovl text &optional face evap)
4949 "Make overlay OVL display TEXT with face FACE."
4950 (if (featurep 'xemacs)
4951 (let ((gl (make-glyph text)))
4952 (and face (set-glyph-face gl face))
4953 (set-extent-property ovl 'begin-glyph gl))
4954 (if face (org-add-props text nil 'face face))
4955 (overlay-put ovl 'before-string text)
4956 (if evap (overlay-put ovl 'evaporate t))))
4957 (defun org-overlay-get (ovl prop)
4958 (if (featurep 'xemacs)
4959 (extent-property ovl prop)
4960 (overlay-get ovl prop)))
4961 (defun org-overlays-at (pos)
4962 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4963 (defun org-overlays-in (&optional start end)
4964 (if (featurep 'xemacs)
4965 (extent-list nil start end)
4966 (overlays-in start end)))
4967 (defun org-overlay-start (o)
4968 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4969 (defun org-overlay-end (o)
4970 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4971 (defun org-find-overlays (prop &optional pos delete)
4972 "Find all overlays specifying PROP at POS or point.
4973 If DELETE is non-nil, delete all those overlays."
4974 (let ((overlays (org-overlays-at (or pos (point))))
4975 ov found)
4976 (while (setq ov (pop overlays))
4977 (if (org-overlay-get ov prop)
4978 (if delete (org-delete-overlay ov) (push ov found))))
4979 found))
4981 ;; Region compatibility
4983 (defun org-add-hook (hook function &optional append local)
4984 "Add-hook, compatible with both Emacsen."
4985 (if (and local (featurep 'xemacs))
4986 (add-local-hook hook function append)
4987 (add-hook hook function append local)))
4989 (defvar org-ignore-region nil
4990 "To temporarily disable the active region.")
4992 (defun org-region-active-p ()
4993 "Is `transient-mark-mode' on and the region active?
4994 Works on both Emacs and XEmacs."
4995 (if org-ignore-region
4997 (if (featurep 'xemacs)
4998 (and zmacs-regions (region-active-p))
4999 (if (fboundp 'use-region-p)
5000 (use-region-p)
5001 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
5003 ;; Invisibility compatibility
5005 (defun org-add-to-invisibility-spec (arg)
5006 "Add elements to `buffer-invisibility-spec'.
5007 See documentation for `buffer-invisibility-spec' for the kind of elements
5008 that can be added."
5009 (cond
5010 ((fboundp 'add-to-invisibility-spec)
5011 (add-to-invisibility-spec arg))
5012 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
5013 (setq buffer-invisibility-spec (list arg)))
5015 (setq buffer-invisibility-spec
5016 (cons arg buffer-invisibility-spec)))))
5018 (defun org-remove-from-invisibility-spec (arg)
5019 "Remove elements from `buffer-invisibility-spec'."
5020 (if (fboundp 'remove-from-invisibility-spec)
5021 (remove-from-invisibility-spec arg)
5022 (if (consp buffer-invisibility-spec)
5023 (setq buffer-invisibility-spec
5024 (delete arg buffer-invisibility-spec)))))
5026 (defun org-in-invisibility-spec-p (arg)
5027 "Is ARG a member of `buffer-invisibility-spec'?"
5028 (if (consp buffer-invisibility-spec)
5029 (member arg buffer-invisibility-spec)
5030 nil))
5032 ;;;; Define the Org-mode
5034 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5035 (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."))
5038 ;; We use a before-change function to check if a table might need
5039 ;; an update.
5040 (defvar org-table-may-need-update t
5041 "Indicates that a table might need an update.
5042 This variable is set by `org-before-change-function'.
5043 `org-table-align' sets it back to nil.")
5044 (defvar org-mode-map)
5045 (defvar org-mode-hook nil)
5046 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5047 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5048 (defvar org-table-buffer-is-an nil)
5049 (defconst org-outline-regexp "\\*+ ")
5051 ;;;###autoload
5052 (define-derived-mode org-mode outline-mode "Org"
5053 "Outline-based notes management and organizer, alias
5054 \"Carsten's outline-mode for keeping track of everything.\"
5056 Org-mode develops organizational tasks around a NOTES file which
5057 contains information about projects as plain text. Org-mode is
5058 implemented on top of outline-mode, which is ideal to keep the content
5059 of large files well structured. It supports ToDo items, deadlines and
5060 time stamps, which magically appear in the diary listing of the Emacs
5061 calendar. Tables are easily created with a built-in table editor.
5062 Plain text URL-like links connect to websites, emails (VM), Usenet
5063 messages (Gnus), BBDB entries, and any files related to the project.
5064 For printing and sharing of notes, an Org-mode file (or a part of it)
5065 can be exported as a structured ASCII or HTML file.
5067 The following commands are available:
5069 \\{org-mode-map}"
5071 ;; Get rid of Outline menus, they are not needed
5072 ;; Need to do this here because define-derived-mode sets up
5073 ;; the keymap so late. Still, it is a waste to call this each time
5074 ;; we switch another buffer into org-mode.
5075 (if (featurep 'xemacs)
5076 (when (boundp 'outline-mode-menu-heading)
5077 ;; Assume this is Greg's port, it used easymenu
5078 (easy-menu-remove outline-mode-menu-heading)
5079 (easy-menu-remove outline-mode-menu-show)
5080 (easy-menu-remove outline-mode-menu-hide))
5081 (define-key org-mode-map [menu-bar headings] 'undefined)
5082 (define-key org-mode-map [menu-bar hide] 'undefined)
5083 (define-key org-mode-map [menu-bar show] 'undefined))
5085 (easy-menu-add org-org-menu)
5086 (easy-menu-add org-tbl-menu)
5087 (org-install-agenda-files-menu)
5088 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5089 (org-add-to-invisibility-spec '(org-cwidth))
5090 (when (featurep 'xemacs)
5091 (org-set-local 'line-move-ignore-invisible t))
5092 (org-set-local 'outline-regexp org-outline-regexp)
5093 (org-set-local 'outline-level 'org-outline-level)
5094 (when (and org-ellipsis
5095 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5096 (fboundp 'make-glyph-code))
5097 (unless org-display-table
5098 (setq org-display-table (make-display-table)))
5099 (set-display-table-slot
5100 org-display-table 4
5101 (vconcat (mapcar
5102 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5103 org-ellipsis)))
5104 (if (stringp org-ellipsis) org-ellipsis "..."))))
5105 (setq buffer-display-table org-display-table))
5106 (org-set-regexps-and-options)
5107 ;; Calc embedded
5108 (org-set-local 'calc-embedded-open-mode "# ")
5109 (modify-syntax-entry ?# "<")
5110 (modify-syntax-entry ?@ "w")
5111 (if org-startup-truncated (setq truncate-lines t))
5112 (org-set-local 'font-lock-unfontify-region-function
5113 'org-unfontify-region)
5114 ;; Activate before-change-function
5115 (org-set-local 'org-table-may-need-update t)
5116 (org-add-hook 'before-change-functions 'org-before-change-function nil
5117 'local)
5118 ;; Check for running clock before killing a buffer
5119 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5120 ;; Paragraphs and auto-filling
5121 (org-set-autofill-regexps)
5122 (setq indent-line-function 'org-indent-line-function)
5123 (org-update-radio-target-regexp)
5125 ;; Comment characters
5126 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5127 (org-set-local 'comment-padding " ")
5129 ;; Align options lines
5130 (org-set-local
5131 'align-mode-rules-list
5132 '((org-in-buffer-settings
5133 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5134 (modes . '(org-mode)))))
5136 ;; Imenu
5137 (org-set-local 'imenu-create-index-function
5138 'org-imenu-get-tree)
5140 ;; Make isearch reveal context
5141 (if (or (featurep 'xemacs)
5142 (not (boundp 'outline-isearch-open-invisible-function)))
5143 ;; Emacs 21 and XEmacs make use of the hook
5144 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5145 ;; Emacs 22 deals with this through a special variable
5146 (org-set-local 'outline-isearch-open-invisible-function
5147 (lambda (&rest ignore) (org-show-context 'isearch))))
5149 ;; If empty file that did not turn on org-mode automatically, make it to.
5150 (if (and org-insert-mode-line-in-empty-file
5151 (interactive-p)
5152 (= (point-min) (point-max)))
5153 (insert "# -*- mode: org -*-\n\n"))
5155 (unless org-inhibit-startup
5156 (when org-startup-align-all-tables
5157 (let ((bmp (buffer-modified-p)))
5158 (org-table-map-tables 'org-table-align)
5159 (set-buffer-modified-p bmp)))
5160 (org-cycle-hide-drawers 'all)
5161 (cond
5162 ((eq org-startup-folded t)
5163 (org-cycle '(4)))
5164 ((eq org-startup-folded 'content)
5165 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5166 (org-cycle '(4)) (org-cycle '(4)))))))
5168 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5170 (defsubst org-call-with-arg (command arg)
5171 "Call COMMAND interactively, but pretend prefix are was ARG."
5172 (let ((current-prefix-arg arg)) (call-interactively command)))
5174 (defsubst org-current-line (&optional pos)
5175 (save-excursion
5176 (and pos (goto-char pos))
5177 ;; works also in narrowed buffer, because we start at 1, not point-min
5178 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5180 (defun org-current-time ()
5181 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5182 (if (> (car org-time-stamp-rounding-minutes) 1)
5183 (let ((r (car org-time-stamp-rounding-minutes))
5184 (time (decode-time)))
5185 (apply 'encode-time
5186 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5187 (nthcdr 2 time))))
5188 (current-time)))
5190 (defun org-add-props (string plist &rest props)
5191 "Add text properties to entire string, from beginning to end.
5192 PLIST may be a list of properties, PROPS are individual properties and values
5193 that will be added to PLIST. Returns the string that was modified."
5194 (add-text-properties
5195 0 (length string) (if props (append plist props) plist) string)
5196 string)
5197 (put 'org-add-props 'lisp-indent-function 2)
5200 ;;;; Font-Lock stuff, including the activators
5202 (defvar org-mouse-map (make-sparse-keymap))
5203 (org-defkey org-mouse-map
5204 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5205 (org-defkey org-mouse-map
5206 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5207 (when org-mouse-1-follows-link
5208 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5209 (when org-tab-follows-link
5210 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5211 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5212 (when org-return-follows-link
5213 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5214 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5216 (require 'font-lock)
5218 (defconst org-non-link-chars "]\t\n\r<>")
5219 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5220 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5221 (defvar org-link-re-with-space nil
5222 "Matches a link with spaces, optional angular brackets around it.")
5223 (defvar org-link-re-with-space2 nil
5224 "Matches a link with spaces, optional angular brackets around it.")
5225 (defvar org-angle-link-re nil
5226 "Matches link with angular brackets, spaces are allowed.")
5227 (defvar org-plain-link-re nil
5228 "Matches plain link, without spaces.")
5229 (defvar org-bracket-link-regexp nil
5230 "Matches a link in double brackets.")
5231 (defvar org-bracket-link-analytic-regexp nil
5232 "Regular expression used to analyze links.
5233 Here is what the match groups contain after a match:
5234 1: http:
5235 2: http
5236 3: path
5237 4: [desc]
5238 5: desc")
5239 (defvar org-any-link-re nil
5240 "Regular expression matching any link.")
5242 (defun org-make-link-regexps ()
5243 "Update the link regular expressions.
5244 This should be called after the variable `org-link-types' has changed."
5245 (setq org-link-re-with-space
5246 (concat
5247 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5248 "\\([^" org-non-link-chars " ]"
5249 "[^" org-non-link-chars "]*"
5250 "[^" org-non-link-chars " ]\\)>?")
5251 org-link-re-with-space2
5252 (concat
5253 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5254 "\\([^" org-non-link-chars " ]"
5255 "[^]\t\n\r]*"
5256 "[^" org-non-link-chars " ]\\)>?")
5257 org-angle-link-re
5258 (concat
5259 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5260 "\\([^" org-non-link-chars " ]"
5261 "[^" org-non-link-chars "]*"
5262 "\\)>")
5263 org-plain-link-re
5264 (concat
5265 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5266 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5267 org-bracket-link-regexp
5268 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5269 org-bracket-link-analytic-regexp
5270 (concat
5271 "\\[\\["
5272 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5273 "\\([^]]+\\)"
5274 "\\]"
5275 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5276 "\\]")
5277 org-any-link-re
5278 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5279 org-angle-link-re "\\)\\|\\("
5280 org-plain-link-re "\\)")))
5282 (org-make-link-regexps)
5284 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5285 "Regular expression for fast time stamp matching.")
5286 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5287 "Regular expression for fast time stamp matching.")
5288 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5289 "Regular expression matching time strings for analysis.
5290 This one does not require the space after the date, so it can be used
5291 on a string that terminates immediately after the date.")
5292 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5293 "Regular expression matching time strings for analysis.")
5294 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5295 "Regular expression matching time stamps, with groups.")
5296 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5297 "Regular expression matching time stamps (also [..]), with groups.")
5298 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5299 "Regular expression matching a time stamp range.")
5300 (defconst org-tr-regexp-both
5301 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5302 "Regular expression matching a time stamp range.")
5303 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5304 org-ts-regexp "\\)?")
5305 "Regular expression matching a time stamp or time stamp range.")
5306 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5307 org-ts-regexp-both "\\)?")
5308 "Regular expression matching a time stamp or time stamp range.
5309 The time stamps may be either active or inactive.")
5311 (defvar org-emph-face nil)
5313 (defun org-do-emphasis-faces (limit)
5314 "Run through the buffer and add overlays to links."
5315 (let (rtn)
5316 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5317 (if (not (= (char-after (match-beginning 3))
5318 (char-after (match-beginning 4))))
5319 (progn
5320 (setq rtn t)
5321 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5322 'face
5323 (nth 1 (assoc (match-string 3)
5324 org-emphasis-alist)))
5325 (add-text-properties (match-beginning 2) (match-end 2)
5326 '(font-lock-multiline t))
5327 (when org-hide-emphasis-markers
5328 (add-text-properties (match-end 4) (match-beginning 5)
5329 '(invisible org-link))
5330 (add-text-properties (match-beginning 3) (match-end 3)
5331 '(invisible org-link)))))
5332 (backward-char 1))
5333 rtn))
5335 (defun org-emphasize (&optional char)
5336 "Insert or change an emphasis, i.e. a font like bold or italic.
5337 If there is an active region, change that region to a new emphasis.
5338 If there is no region, just insert the marker characters and position
5339 the cursor between them.
5340 CHAR should be either the marker character, or the first character of the
5341 HTML tag associated with that emphasis. If CHAR is a space, the means
5342 to remove the emphasis of the selected region.
5343 If char is not given (for example in an interactive call) it
5344 will be prompted for."
5345 (interactive)
5346 (let ((eal org-emphasis-alist) e det
5347 (erc org-emphasis-regexp-components)
5348 (prompt "")
5349 (string "") beg end move tag c s)
5350 (if (org-region-active-p)
5351 (setq beg (region-beginning) end (region-end)
5352 string (buffer-substring beg end))
5353 (setq move t))
5355 (while (setq e (pop eal))
5356 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5357 c (aref tag 0))
5358 (push (cons c (string-to-char (car e))) det)
5359 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5360 (substring tag 1)))))
5361 (unless char
5362 (message "%s" (concat "Emphasis marker or tag:" prompt))
5363 (setq char (read-char-exclusive)))
5364 (setq char (or (cdr (assoc char det)) char))
5365 (if (equal char ?\ )
5366 (setq s "" move nil)
5367 (unless (assoc (char-to-string char) org-emphasis-alist)
5368 (error "No such emphasis marker: \"%c\"" char))
5369 (setq s (char-to-string char)))
5370 (while (and (> (length string) 1)
5371 (equal (substring string 0 1) (substring string -1))
5372 (assoc (substring string 0 1) org-emphasis-alist))
5373 (setq string (substring string 1 -1)))
5374 (setq string (concat s string s))
5375 (if beg (delete-region beg end))
5376 (unless (or (bolp)
5377 (string-match (concat "[" (nth 0 erc) "\n]")
5378 (char-to-string (char-before (point)))))
5379 (insert " "))
5380 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5381 (char-to-string (char-after (point))))
5382 (insert " ") (backward-char 1))
5383 (insert string)
5384 (and move (backward-char 1))))
5386 (defconst org-nonsticky-props
5387 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5390 (defun org-activate-plain-links (limit)
5391 "Run through the buffer and add overlays to links."
5392 (catch 'exit
5393 (let (f)
5394 (while (re-search-forward org-plain-link-re limit t)
5395 (setq f (get-text-property (match-beginning 0) 'face))
5396 (if (or (eq f 'org-tag)
5397 (and (listp f) (memq 'org-tag f)))
5399 (add-text-properties (match-beginning 0) (match-end 0)
5400 (list 'mouse-face 'highlight
5401 'rear-nonsticky org-nonsticky-props
5402 'keymap org-mouse-map
5404 (throw 'exit t))))))
5406 (defun org-activate-code (limit)
5407 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5408 (unless (get-text-property (match-beginning 1) 'face)
5409 (remove-text-properties (match-beginning 0) (match-end 0)
5410 '(display t invisible t intangible t))
5411 t)))
5413 (defun org-activate-angle-links (limit)
5414 "Run through the buffer and add overlays to links."
5415 (if (re-search-forward org-angle-link-re limit t)
5416 (progn
5417 (add-text-properties (match-beginning 0) (match-end 0)
5418 (list 'mouse-face 'highlight
5419 'rear-nonsticky org-nonsticky-props
5420 'keymap org-mouse-map
5422 t)))
5424 (defmacro org-maybe-intangible (props)
5425 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5426 In emacs 21, invisible text is not avoided by the command loop, so the
5427 intangible property is needed to make sure point skips this text.
5428 In Emacs 22, this is not necessary. The intangible text property has
5429 led to problems with flyspell. These problems are fixed in flyspell.el,
5430 but we still avoid setting the property in Emacs 22 and later.
5431 We use a macro so that the test can happen at compilation time."
5432 (if (< emacs-major-version 22)
5433 `(append '(intangible t) ,props)
5434 props))
5436 (defun org-activate-bracket-links (limit)
5437 "Run through the buffer and add overlays to bracketed links."
5438 (if (re-search-forward org-bracket-link-regexp limit t)
5439 (let* ((help (concat "LINK: "
5440 (org-match-string-no-properties 1)))
5441 ;; FIXME: above we should remove the escapes.
5442 ;; but that requires another match, protecting match data,
5443 ;; a lot of overhead for font-lock.
5444 (ip (org-maybe-intangible
5445 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5446 'keymap org-mouse-map 'mouse-face 'highlight
5447 'font-lock-multiline t 'help-echo help)))
5448 (vp (list 'rear-nonsticky org-nonsticky-props
5449 'keymap org-mouse-map 'mouse-face 'highlight
5450 ' font-lock-multiline t 'help-echo help)))
5451 ;; We need to remove the invisible property here. Table narrowing
5452 ;; may have made some of this invisible.
5453 (remove-text-properties (match-beginning 0) (match-end 0)
5454 '(invisible nil))
5455 (if (match-end 3)
5456 (progn
5457 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5458 (add-text-properties (match-beginning 3) (match-end 3) vp)
5459 (add-text-properties (match-end 3) (match-end 0) ip))
5460 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5461 (add-text-properties (match-beginning 1) (match-end 1) vp)
5462 (add-text-properties (match-end 1) (match-end 0) ip))
5463 t)))
5465 (defun org-activate-dates (limit)
5466 "Run through the buffer and add overlays to dates."
5467 (if (re-search-forward org-tsr-regexp-both limit t)
5468 (progn
5469 (add-text-properties (match-beginning 0) (match-end 0)
5470 (list 'mouse-face 'highlight
5471 'rear-nonsticky org-nonsticky-props
5472 'keymap org-mouse-map))
5473 (when org-display-custom-times
5474 (if (match-end 3)
5475 (org-display-custom-time (match-beginning 3) (match-end 3)))
5476 (org-display-custom-time (match-beginning 1) (match-end 1)))
5477 t)))
5479 (defvar org-target-link-regexp nil
5480 "Regular expression matching radio targets in plain text.")
5481 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5482 "Regular expression matching a link target.")
5483 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5484 "Regular expression matching a radio target.")
5485 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5486 "Regular expression matching any target.")
5488 (defun org-activate-target-links (limit)
5489 "Run through the buffer and add overlays to target matches."
5490 (when org-target-link-regexp
5491 (let ((case-fold-search t))
5492 (if (re-search-forward org-target-link-regexp limit t)
5493 (progn
5494 (add-text-properties (match-beginning 0) (match-end 0)
5495 (list 'mouse-face 'highlight
5496 'rear-nonsticky org-nonsticky-props
5497 'keymap org-mouse-map
5498 'help-echo "Radio target link"
5499 'org-linked-text t))
5500 t)))))
5502 (defun org-update-radio-target-regexp ()
5503 "Find all radio targets in this file and update the regular expression."
5504 (interactive)
5505 (when (memq 'radio org-activate-links)
5506 (setq org-target-link-regexp
5507 (org-make-target-link-regexp (org-all-targets 'radio)))
5508 (org-restart-font-lock)))
5510 (defun org-hide-wide-columns (limit)
5511 (let (s e)
5512 (setq s (text-property-any (point) (or limit (point-max))
5513 'org-cwidth t))
5514 (when s
5515 (setq e (next-single-property-change s 'org-cwidth))
5516 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5517 (goto-char e)
5518 t)))
5520 (defvar org-latex-and-specials-regexp nil
5521 "Regular expression for highlighting export special stuff.")
5522 (defvar org-match-substring-regexp)
5523 (defvar org-match-substring-with-braces-regexp)
5524 (defvar org-export-html-special-string-regexps)
5526 (defun org-compute-latex-and-specials-regexp ()
5527 "Compute regular expression for stuff treated specially by exporters."
5528 (if (not org-highlight-latex-fragments-and-specials)
5529 (org-set-local 'org-latex-and-specials-regexp nil)
5530 (let*
5531 ((matchers (plist-get org-format-latex-options :matchers))
5532 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5533 org-latex-regexps)))
5534 (options (org-combine-plists (org-default-export-plist)
5535 (org-infile-export-plist)))
5536 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5537 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5538 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5539 (org-export-html-expand (plist-get options :expand-quoted-html))
5540 (org-export-with-special-strings (plist-get options :special-strings))
5541 (re-sub
5542 (cond
5543 ((equal org-export-with-sub-superscripts '{})
5544 (list org-match-substring-with-braces-regexp))
5545 (org-export-with-sub-superscripts
5546 (list org-match-substring-regexp))
5547 (t nil)))
5548 (re-latex
5549 (if org-export-with-LaTeX-fragments
5550 (mapcar (lambda (x) (nth 1 x)) latexs)))
5551 (re-macros
5552 (if org-export-with-TeX-macros
5553 (list (concat "\\\\"
5554 (regexp-opt
5555 (append (mapcar 'car org-html-entities)
5556 (if (boundp 'org-latex-entities)
5557 org-latex-entities nil))
5558 'words))) ; FIXME
5560 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5561 (re-special (if org-export-with-special-strings
5562 (mapcar (lambda (x) (car x))
5563 org-export-html-special-string-regexps)))
5564 (re-rest
5565 (delq nil
5566 (list
5567 (if org-export-html-expand "@<[^>\n]+>")
5568 ))))
5569 (org-set-local
5570 'org-latex-and-specials-regexp
5571 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5572 re-rest) "\\|")))))
5574 (defface org-latex-and-export-specials
5575 (let ((font (cond ((assq :inherit custom-face-attributes)
5576 '(:inherit underline))
5577 (t '(:underline t)))))
5578 `((((class grayscale) (background light))
5579 (:foreground "DimGray" ,@font))
5580 (((class grayscale) (background dark))
5581 (:foreground "LightGray" ,@font))
5582 (((class color) (background light))
5583 (:foreground "SaddleBrown"))
5584 (((class color) (background dark))
5585 (:foreground "burlywood"))
5586 (t (,@font))))
5587 "Face used to highlight math latex and other special exporter stuff."
5588 :group 'org-faces)
5590 (defun org-do-latex-and-special-faces (limit)
5591 "Run through the buffer and add overlays to links."
5592 (when org-latex-and-specials-regexp
5593 (let (rtn d)
5594 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5595 limit t))
5596 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5597 'face))
5598 '(org-code org-verbatim underline)))
5599 (progn
5600 (setq rtn t
5601 d (cond ((member (char-after (1+ (match-beginning 0)))
5602 '(?_ ?^)) 1)
5603 (t 0)))
5604 (font-lock-prepend-text-property
5605 (+ d (match-beginning 0)) (match-end 0)
5606 'face 'org-latex-and-export-specials)
5607 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5608 '(font-lock-multiline t)))))
5609 rtn)))
5611 (defun org-restart-font-lock ()
5612 "Restart font-lock-mode, to force refontification."
5613 (when (and (boundp 'font-lock-mode) font-lock-mode)
5614 (font-lock-mode -1)
5615 (font-lock-mode 1)))
5617 (defun org-all-targets (&optional radio)
5618 "Return a list of all targets in this file.
5619 With optional argument RADIO, only find radio targets."
5620 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5621 rtn)
5622 (save-excursion
5623 (goto-char (point-min))
5624 (while (re-search-forward re nil t)
5625 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5626 rtn)))
5628 (defun org-make-target-link-regexp (targets)
5629 "Make regular expression matching all strings in TARGETS.
5630 The regular expression finds the targets also if there is a line break
5631 between words."
5632 (and targets
5633 (concat
5634 "\\<\\("
5635 (mapconcat
5636 (lambda (x)
5637 (while (string-match " +" x)
5638 (setq x (replace-match "\\s-+" t t x)))
5640 targets
5641 "\\|")
5642 "\\)\\>")))
5644 (defun org-activate-tags (limit)
5645 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5646 (progn
5647 (add-text-properties (match-beginning 1) (match-end 1)
5648 (list 'mouse-face 'highlight
5649 'rear-nonsticky org-nonsticky-props
5650 'keymap org-mouse-map))
5651 t)))
5653 (defun org-outline-level ()
5654 (save-excursion
5655 (looking-at outline-regexp)
5656 (if (match-beginning 1)
5657 (+ (org-get-string-indentation (match-string 1)) 1000)
5658 (1- (- (match-end 0) (match-beginning 0))))))
5660 (defvar org-font-lock-keywords nil)
5662 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5663 "Regular expression matching a property line.")
5665 (defun org-set-font-lock-defaults ()
5666 (let* ((em org-fontify-emphasized-text)
5667 (lk org-activate-links)
5668 (org-font-lock-extra-keywords
5669 (list
5670 ;; Headlines
5671 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5672 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5673 ;; Table lines
5674 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5675 (1 'org-table t))
5676 ;; Table internals
5677 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5678 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5679 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5680 ;; Drawers
5681 (list org-drawer-regexp '(0 'org-special-keyword t))
5682 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5683 ;; Properties
5684 (list org-property-re
5685 '(1 'org-special-keyword t)
5686 '(3 'org-property-value t))
5687 (if org-format-transports-properties-p
5688 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5689 ;; Links
5690 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5691 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5692 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5693 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5694 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5695 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5696 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5697 '(org-hide-wide-columns (0 nil append))
5698 ;; TODO lines
5699 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5700 '(1 (org-get-todo-face 1) t))
5701 ;; DONE
5702 (if org-fontify-done-headline
5703 (list (concat "^[*]+ +\\<\\("
5704 (mapconcat 'regexp-quote org-done-keywords "\\|")
5705 "\\)\\(.*\\)")
5706 '(2 'org-headline-done t))
5707 nil)
5708 ;; Priorities
5709 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5710 ;; Special keywords
5711 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5712 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5713 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5714 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5715 ;; Emphasis
5716 (if em
5717 (if (featurep 'xemacs)
5718 '(org-do-emphasis-faces (0 nil append))
5719 '(org-do-emphasis-faces)))
5720 ;; Checkboxes
5721 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5722 2 'bold prepend)
5723 (if org-provide-checkbox-statistics
5724 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5725 (0 (org-get-checkbox-statistics-face) t)))
5726 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5727 '(1 'org-archived prepend))
5728 ;; Specials
5729 '(org-do-latex-and-special-faces)
5730 ;; Code
5731 '(org-activate-code (1 'org-code t))
5732 ;; COMMENT
5733 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5734 "\\|" org-quote-string "\\)\\>")
5735 '(1 'org-special-keyword t))
5736 '("^#.*" (0 'font-lock-comment-face t))
5738 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5739 ;; Now set the full font-lock-keywords
5740 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5741 (org-set-local 'font-lock-defaults
5742 '(org-font-lock-keywords t nil nil backward-paragraph))
5743 (kill-local-variable 'font-lock-keywords) nil))
5745 (defvar org-m nil)
5746 (defvar org-l nil)
5747 (defvar org-f nil)
5748 (defun org-get-level-face (n)
5749 "Get the right face for match N in font-lock matching of healdines."
5750 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5751 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5752 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5753 (cond
5754 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5755 ((eq n 2) org-f)
5756 (t (if org-level-color-stars-only nil org-f))))
5758 (defun org-get-todo-face (kwd)
5759 "Get the right face for a TODO keyword KWD.
5760 If KWD is a number, get the corresponding match group."
5761 (if (numberp kwd) (setq kwd (match-string kwd)))
5762 (or (cdr (assoc kwd org-todo-keyword-faces))
5763 (and (member kwd org-done-keywords) 'org-done)
5764 'org-todo))
5766 (defun org-unfontify-region (beg end &optional maybe_loudly)
5767 "Remove fontification and activation overlays from links."
5768 (font-lock-default-unfontify-region beg end)
5769 (let* ((buffer-undo-list t)
5770 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5771 (inhibit-modification-hooks t)
5772 deactivate-mark buffer-file-name buffer-file-truename)
5773 (remove-text-properties beg end
5774 '(mouse-face t keymap t org-linked-text t
5775 invisible t intangible t))))
5777 ;;;; Visibility cycling, including org-goto and indirect buffer
5779 ;;; Cycling
5781 (defvar org-cycle-global-status nil)
5782 (make-variable-buffer-local 'org-cycle-global-status)
5783 (defvar org-cycle-subtree-status nil)
5784 (make-variable-buffer-local 'org-cycle-subtree-status)
5786 ;;;###autoload
5787 (defun org-cycle (&optional arg)
5788 "Visibility cycling for Org-mode.
5790 - When this function is called with a prefix argument, rotate the entire
5791 buffer through 3 states (global cycling)
5792 1. OVERVIEW: Show only top-level headlines.
5793 2. CONTENTS: Show all headlines of all levels, but no body text.
5794 3. SHOW ALL: Show everything.
5796 - When point is at the beginning of a headline, rotate the subtree started
5797 by this line through 3 different states (local cycling)
5798 1. FOLDED: Only the main headline is shown.
5799 2. CHILDREN: The main headline and the direct children are shown.
5800 From this state, you can move to one of the children
5801 and zoom in further.
5802 3. SUBTREE: Show the entire subtree, including body text.
5804 - When there is a numeric prefix, go up to a heading with level ARG, do
5805 a `show-subtree' and return to the previous cursor position. If ARG
5806 is negative, go up that many levels.
5808 - When point is not at the beginning of a headline, execute
5809 `indent-relative', like TAB normally does. See the option
5810 `org-cycle-emulate-tab' for details.
5812 - Special case: if point is at the beginning of the buffer and there is
5813 no headline in line 1, this function will act as if called with prefix arg.
5814 But only if also the variable `org-cycle-global-at-bob' is t."
5815 (interactive "P")
5816 (let* ((outline-regexp
5817 (if (and (org-mode-p) org-cycle-include-plain-lists)
5818 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5819 outline-regexp))
5820 (bob-special (and org-cycle-global-at-bob (bobp)
5821 (not (looking-at outline-regexp))))
5822 (org-cycle-hook
5823 (if bob-special
5824 (delq 'org-optimize-window-after-visibility-change
5825 (copy-sequence org-cycle-hook))
5826 org-cycle-hook))
5827 (pos (point)))
5829 (if (or bob-special (equal arg '(4)))
5830 ;; special case: use global cycling
5831 (setq arg t))
5833 (cond
5835 ((org-at-table-p 'any)
5836 ;; Enter the table or move to the next field in the table
5837 (or (org-table-recognize-table.el)
5838 (progn
5839 (if arg (org-table-edit-field t)
5840 (org-table-justify-field-maybe)
5841 (call-interactively 'org-table-next-field)))))
5843 ((eq arg t) ;; Global cycling
5845 (cond
5846 ((and (eq last-command this-command)
5847 (eq org-cycle-global-status 'overview))
5848 ;; We just created the overview - now do table of contents
5849 ;; This can be slow in very large buffers, so indicate action
5850 (message "CONTENTS...")
5851 (org-content)
5852 (message "CONTENTS...done")
5853 (setq org-cycle-global-status 'contents)
5854 (run-hook-with-args 'org-cycle-hook 'contents))
5856 ((and (eq last-command this-command)
5857 (eq org-cycle-global-status 'contents))
5858 ;; We just showed the table of contents - now show everything
5859 (show-all)
5860 (message "SHOW ALL")
5861 (setq org-cycle-global-status 'all)
5862 (run-hook-with-args 'org-cycle-hook 'all))
5865 ;; Default action: go to overview
5866 (org-overview)
5867 (message "OVERVIEW")
5868 (setq org-cycle-global-status 'overview)
5869 (run-hook-with-args 'org-cycle-hook 'overview))))
5871 ((and org-drawers org-drawer-regexp
5872 (save-excursion
5873 (beginning-of-line 1)
5874 (looking-at org-drawer-regexp)))
5875 ;; Toggle block visibility
5876 (org-flag-drawer
5877 (not (get-char-property (match-end 0) 'invisible))))
5879 ((integerp arg)
5880 ;; Show-subtree, ARG levels up from here.
5881 (save-excursion
5882 (org-back-to-heading)
5883 (outline-up-heading (if (< arg 0) (- arg)
5884 (- (funcall outline-level) arg)))
5885 (org-show-subtree)))
5887 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5888 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5889 ;; At a heading: rotate between three different views
5890 (org-back-to-heading)
5891 (let ((goal-column 0) eoh eol eos)
5892 ;; First, some boundaries
5893 (save-excursion
5894 (org-back-to-heading)
5895 (save-excursion
5896 (beginning-of-line 2)
5897 (while (and (not (eobp)) ;; this is like `next-line'
5898 (get-char-property (1- (point)) 'invisible))
5899 (beginning-of-line 2)) (setq eol (point)))
5900 (outline-end-of-heading) (setq eoh (point))
5901 (org-end-of-subtree t)
5902 (unless (eobp)
5903 (skip-chars-forward " \t\n")
5904 (beginning-of-line 1) ; in case this is an item
5906 (setq eos (1- (point))))
5907 ;; Find out what to do next and set `this-command'
5908 (cond
5909 ((= eos eoh)
5910 ;; Nothing is hidden behind this heading
5911 (message "EMPTY ENTRY")
5912 (setq org-cycle-subtree-status nil)
5913 (save-excursion
5914 (goto-char eos)
5915 (outline-next-heading)
5916 (if (org-invisible-p) (org-flag-heading nil))))
5917 ((or (>= eol eos)
5918 (not (string-match "\\S-" (buffer-substring eol eos))))
5919 ;; Entire subtree is hidden in one line: open it
5920 (org-show-entry)
5921 (show-children)
5922 (message "CHILDREN")
5923 (save-excursion
5924 (goto-char eos)
5925 (outline-next-heading)
5926 (if (org-invisible-p) (org-flag-heading nil)))
5927 (setq org-cycle-subtree-status 'children)
5928 (run-hook-with-args 'org-cycle-hook 'children))
5929 ((and (eq last-command this-command)
5930 (eq org-cycle-subtree-status 'children))
5931 ;; We just showed the children, now show everything.
5932 (org-show-subtree)
5933 (message "SUBTREE")
5934 (setq org-cycle-subtree-status 'subtree)
5935 (run-hook-with-args 'org-cycle-hook 'subtree))
5937 ;; Default action: hide the subtree.
5938 (hide-subtree)
5939 (message "FOLDED")
5940 (setq org-cycle-subtree-status 'folded)
5941 (run-hook-with-args 'org-cycle-hook 'folded)))))
5943 ;; TAB emulation
5944 (buffer-read-only (org-back-to-heading))
5946 ((org-try-cdlatex-tab))
5948 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5949 (or (not (bolp))
5950 (not (looking-at outline-regexp))))
5951 (call-interactively (global-key-binding "\t")))
5953 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5954 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5955 (or (and (eq org-cycle-emulate-tab 'white)
5956 (= (match-end 0) (point-at-eol)))
5957 (and (eq org-cycle-emulate-tab 'whitestart)
5958 (>= (match-end 0) pos))))
5960 (eq org-cycle-emulate-tab t))
5961 ; (if (and (looking-at "[ \n\r\t]")
5962 ; (string-match "^[ \t]*$" (buffer-substring
5963 ; (point-at-bol) (point))))
5964 ; (progn
5965 ; (beginning-of-line 1)
5966 ; (and (looking-at "[ \t]+") (replace-match ""))))
5967 (call-interactively (global-key-binding "\t")))
5969 (t (save-excursion
5970 (org-back-to-heading)
5971 (org-cycle))))))
5973 ;;;###autoload
5974 (defun org-global-cycle (&optional arg)
5975 "Cycle the global visibility. For details see `org-cycle'."
5976 (interactive "P")
5977 (let ((org-cycle-include-plain-lists
5978 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5979 (if (integerp arg)
5980 (progn
5981 (show-all)
5982 (hide-sublevels arg)
5983 (setq org-cycle-global-status 'contents))
5984 (org-cycle '(4)))))
5986 (defun org-overview ()
5987 "Switch to overview mode, shoing only top-level headlines.
5988 Really, this shows all headlines with level equal or greater than the level
5989 of the first headline in the buffer. This is important, because if the
5990 first headline is not level one, then (hide-sublevels 1) gives confusing
5991 results."
5992 (interactive)
5993 (let ((level (save-excursion
5994 (goto-char (point-min))
5995 (if (re-search-forward (concat "^" outline-regexp) nil t)
5996 (progn
5997 (goto-char (match-beginning 0))
5998 (funcall outline-level))))))
5999 (and level (hide-sublevels level))))
6001 (defun org-content (&optional arg)
6002 "Show all headlines in the buffer, like a table of contents.
6003 With numerical argument N, show content up to level N."
6004 (interactive "P")
6005 (save-excursion
6006 ;; Visit all headings and show their offspring
6007 (and (integerp arg) (org-overview))
6008 (goto-char (point-max))
6009 (catch 'exit
6010 (while (and (progn (condition-case nil
6011 (outline-previous-visible-heading 1)
6012 (error (goto-char (point-min))))
6014 (looking-at outline-regexp))
6015 (if (integerp arg)
6016 (show-children (1- arg))
6017 (show-branches))
6018 (if (bobp) (throw 'exit nil))))))
6021 (defun org-optimize-window-after-visibility-change (state)
6022 "Adjust the window after a change in outline visibility.
6023 This function is the default value of the hook `org-cycle-hook'."
6024 (when (get-buffer-window (current-buffer))
6025 (cond
6026 ; ((eq state 'overview) (org-first-headline-recenter 1))
6027 ; ((eq state 'overview) (org-beginning-of-line))
6028 ((eq state 'content) nil)
6029 ((eq state 'all) nil)
6030 ((eq state 'folded) nil)
6031 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6032 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6034 (defun org-compact-display-after-subtree-move ()
6035 (let (beg end)
6036 (save-excursion
6037 (if (org-up-heading-safe)
6038 (progn
6039 (hide-subtree)
6040 (show-entry)
6041 (show-children)
6042 (org-cycle-show-empty-lines 'children)
6043 (org-cycle-hide-drawers 'children))
6044 (org-overview)))))
6046 (defun org-cycle-show-empty-lines (state)
6047 "Show empty lines above all visible headlines.
6048 The region to be covered depends on STATE when called through
6049 `org-cycle-hook'. Lisp program can use t for STATE to get the
6050 entire buffer covered. Note that an empty line is only shown if there
6051 are at least `org-cycle-separator-lines' empty lines before the headeline."
6052 (when (> org-cycle-separator-lines 0)
6053 (save-excursion
6054 (let* ((n org-cycle-separator-lines)
6055 (re (cond
6056 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6057 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6058 (t (let ((ns (number-to-string (- n 2))))
6059 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6060 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6061 beg end)
6062 (cond
6063 ((memq state '(overview contents t))
6064 (setq beg (point-min) end (point-max)))
6065 ((memq state '(children folded))
6066 (setq beg (point) end (progn (org-end-of-subtree t t)
6067 (beginning-of-line 2)
6068 (point)))))
6069 (when beg
6070 (goto-char beg)
6071 (while (re-search-forward re end t)
6072 (if (not (get-char-property (match-end 1) 'invisible))
6073 (outline-flag-region
6074 (match-beginning 1) (match-end 1) nil)))))))
6075 ;; Never hide empty lines at the end of the file.
6076 (save-excursion
6077 (goto-char (point-max))
6078 (outline-previous-heading)
6079 (outline-end-of-heading)
6080 (if (and (looking-at "[ \t\n]+")
6081 (= (match-end 0) (point-max)))
6082 (outline-flag-region (point) (match-end 0) nil))))
6084 (defun org-subtree-end-visible-p ()
6085 "Is the end of the current subtree visible?"
6086 (pos-visible-in-window-p
6087 (save-excursion (org-end-of-subtree t) (point))))
6089 (defun org-first-headline-recenter (&optional N)
6090 "Move cursor to the first headline and recenter the headline.
6091 Optional argument N means, put the headline into the Nth line of the window."
6092 (goto-char (point-min))
6093 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6094 (beginning-of-line)
6095 (recenter (prefix-numeric-value N))))
6097 ;;; Org-goto
6099 (defvar org-goto-window-configuration nil)
6100 (defvar org-goto-marker nil)
6101 (defvar org-goto-map
6102 (let ((map (make-sparse-keymap)))
6103 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6104 (while (setq cmd (pop cmds))
6105 (substitute-key-definition cmd cmd map global-map)))
6106 (suppress-keymap map)
6107 (org-defkey map "\C-m" 'org-goto-ret)
6108 (org-defkey map [(return)] 'org-goto-ret)
6109 (org-defkey map [(left)] 'org-goto-left)
6110 (org-defkey map [(right)] 'org-goto-right)
6111 (org-defkey map [(control ?g)] 'org-goto-quit)
6112 (org-defkey map "\C-i" 'org-cycle)
6113 (org-defkey map [(tab)] 'org-cycle)
6114 (org-defkey map [(down)] 'outline-next-visible-heading)
6115 (org-defkey map [(up)] 'outline-previous-visible-heading)
6116 (if org-goto-auto-isearch
6117 (if (fboundp 'define-key-after)
6118 (define-key-after map [t] 'org-goto-local-auto-isearch)
6119 nil)
6120 (org-defkey map "q" 'org-goto-quit)
6121 (org-defkey map "n" 'outline-next-visible-heading)
6122 (org-defkey map "p" 'outline-previous-visible-heading)
6123 (org-defkey map "f" 'outline-forward-same-level)
6124 (org-defkey map "b" 'outline-backward-same-level)
6125 (org-defkey map "u" 'outline-up-heading))
6126 (org-defkey map "/" 'org-occur)
6127 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6128 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6129 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6130 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6131 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6132 map))
6134 (defconst org-goto-help
6135 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6136 RET=jump to location [Q]uit and return to previous location
6137 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6139 (defvar org-goto-start-pos) ; dynamically scoped parameter
6141 (defun org-goto (&optional alternative-interface)
6142 "Look up a different location in the current file, keeping current visibility.
6144 When you want look-up or go to a different location in a document, the
6145 fastest way is often to fold the entire buffer and then dive into the tree.
6146 This method has the disadvantage, that the previous location will be folded,
6147 which may not be what you want.
6149 This command works around this by showing a copy of the current buffer
6150 in an indirect buffer, in overview mode. You can dive into the tree in
6151 that copy, use org-occur and incremental search to find a location.
6152 When pressing RET or `Q', the command returns to the original buffer in
6153 which the visibility is still unchanged. After RET is will also jump to
6154 the location selected in the indirect buffer and expose the
6155 the headline hierarchy above."
6156 (interactive "P")
6157 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6158 (org-refile-use-outline-path t)
6159 (interface
6160 (if (not alternative-interface)
6161 org-goto-interface
6162 (if (eq org-goto-interface 'outline)
6163 'outline-path-completion
6164 'outline)))
6165 (org-goto-start-pos (point))
6166 (selected-point
6167 (if (eq interface 'outline)
6168 (car (org-get-location (current-buffer) org-goto-help))
6169 (nth 3 (org-refile-get-location "Goto: ")))))
6170 (if selected-point
6171 (progn
6172 (org-mark-ring-push org-goto-start-pos)
6173 (goto-char selected-point)
6174 (if (or (org-invisible-p) (org-invisible-p2))
6175 (org-show-context 'org-goto)))
6176 (message "Quit"))))
6178 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6179 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6180 (defvar org-goto-local-auto-isearch-map) ; defined below
6182 (defun org-get-location (buf help)
6183 "Let the user select a location in the Org-mode buffer BUF.
6184 This function uses a recursive edit. It returns the selected position
6185 or nil."
6186 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6187 (isearch-hide-immediately nil)
6188 (isearch-search-fun-function
6189 (lambda () 'org-goto-local-search-forward-headings))
6190 (org-goto-selected-point org-goto-exit-command))
6191 (save-excursion
6192 (save-window-excursion
6193 (delete-other-windows)
6194 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6195 (switch-to-buffer
6196 (condition-case nil
6197 (make-indirect-buffer (current-buffer) "*org-goto*")
6198 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6199 (with-output-to-temp-buffer "*Help*"
6200 (princ help))
6201 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6202 (setq buffer-read-only nil)
6203 (let ((org-startup-truncated t)
6204 (org-startup-folded nil)
6205 (org-startup-align-all-tables nil))
6206 (org-mode)
6207 (org-overview))
6208 (setq buffer-read-only t)
6209 (if (and (boundp 'org-goto-start-pos)
6210 (integer-or-marker-p org-goto-start-pos))
6211 (let ((org-show-hierarchy-above t)
6212 (org-show-siblings t)
6213 (org-show-following-heading t))
6214 (goto-char org-goto-start-pos)
6215 (and (org-invisible-p) (org-show-context)))
6216 (goto-char (point-min)))
6217 (org-beginning-of-line)
6218 (message "Select location and press RET")
6219 (use-local-map org-goto-map)
6220 (recursive-edit)
6222 (kill-buffer "*org-goto*")
6223 (cons org-goto-selected-point org-goto-exit-command)))
6225 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6226 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6227 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6228 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6230 (defun org-goto-local-search-forward-headings (string bound noerror)
6231 "Search and make sure that anu matches are in headlines."
6232 (catch 'return
6233 (while (search-forward string bound noerror)
6234 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6235 (and (member :headline context)
6236 (not (member :tags context))))
6237 (throw 'return (point))))))
6239 (defun org-goto-local-auto-isearch ()
6240 "Start isearch."
6241 (interactive)
6242 (goto-char (point-min))
6243 (let ((keys (this-command-keys)))
6244 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6245 (isearch-mode t)
6246 (isearch-process-search-char (string-to-char keys)))))
6248 (defun org-goto-ret (&optional arg)
6249 "Finish `org-goto' by going to the new location."
6250 (interactive "P")
6251 (setq org-goto-selected-point (point)
6252 org-goto-exit-command 'return)
6253 (throw 'exit nil))
6255 (defun org-goto-left ()
6256 "Finish `org-goto' by going to the new location."
6257 (interactive)
6258 (if (org-on-heading-p)
6259 (progn
6260 (beginning-of-line 1)
6261 (setq org-goto-selected-point (point)
6262 org-goto-exit-command 'left)
6263 (throw 'exit nil))
6264 (error "Not on a heading")))
6266 (defun org-goto-right ()
6267 "Finish `org-goto' by going to the new location."
6268 (interactive)
6269 (if (org-on-heading-p)
6270 (progn
6271 (setq org-goto-selected-point (point)
6272 org-goto-exit-command 'right)
6273 (throw 'exit nil))
6274 (error "Not on a heading")))
6276 (defun org-goto-quit ()
6277 "Finish `org-goto' without cursor motion."
6278 (interactive)
6279 (setq org-goto-selected-point nil)
6280 (setq org-goto-exit-command 'quit)
6281 (throw 'exit nil))
6283 ;;; Indirect buffer display of subtrees
6285 (defvar org-indirect-dedicated-frame nil
6286 "This is the frame being used for indirect tree display.")
6287 (defvar org-last-indirect-buffer nil)
6289 (defun org-tree-to-indirect-buffer (&optional arg)
6290 "Create indirect buffer and narrow it to current subtree.
6291 With numerical prefix ARG, go up to this level and then take that tree.
6292 If ARG is negative, go up that many levels.
6293 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6294 indirect buffer previously made with this command, to avoid proliferation of
6295 indirect buffers. However, when you call the command with a `C-u' prefix, or
6296 when `org-indirect-buffer-display' is `new-frame', the last buffer
6297 is kept so that you can work with several indirect buffers at the same time.
6298 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6299 requests that a new frame be made for the new buffer, so that the dedicated
6300 frame is not changed."
6301 (interactive "P")
6302 (let ((cbuf (current-buffer))
6303 (cwin (selected-window))
6304 (pos (point))
6305 beg end level heading ibuf)
6306 (save-excursion
6307 (org-back-to-heading t)
6308 (when (numberp arg)
6309 (setq level (org-outline-level))
6310 (if (< arg 0) (setq arg (+ level arg)))
6311 (while (> (setq level (org-outline-level)) arg)
6312 (outline-up-heading 1 t)))
6313 (setq beg (point)
6314 heading (org-get-heading))
6315 (org-end-of-subtree t) (setq end (point)))
6316 (if (and (buffer-live-p org-last-indirect-buffer)
6317 (not (eq org-indirect-buffer-display 'new-frame))
6318 (not arg))
6319 (kill-buffer org-last-indirect-buffer))
6320 (setq ibuf (org-get-indirect-buffer cbuf)
6321 org-last-indirect-buffer ibuf)
6322 (cond
6323 ((or (eq org-indirect-buffer-display 'new-frame)
6324 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6325 (select-frame (make-frame))
6326 (delete-other-windows)
6327 (switch-to-buffer ibuf)
6328 (org-set-frame-title heading))
6329 ((eq org-indirect-buffer-display 'dedicated-frame)
6330 (raise-frame
6331 (select-frame (or (and org-indirect-dedicated-frame
6332 (frame-live-p org-indirect-dedicated-frame)
6333 org-indirect-dedicated-frame)
6334 (setq org-indirect-dedicated-frame (make-frame)))))
6335 (delete-other-windows)
6336 (switch-to-buffer ibuf)
6337 (org-set-frame-title (concat "Indirect: " heading)))
6338 ((eq org-indirect-buffer-display 'current-window)
6339 (switch-to-buffer ibuf))
6340 ((eq org-indirect-buffer-display 'other-window)
6341 (pop-to-buffer ibuf))
6342 (t (error "Invalid value.")))
6343 (if (featurep 'xemacs)
6344 (save-excursion (org-mode) (turn-on-font-lock)))
6345 (narrow-to-region beg end)
6346 (show-all)
6347 (goto-char pos)
6348 (and (window-live-p cwin) (select-window cwin))))
6350 (defun org-get-indirect-buffer (&optional buffer)
6351 (setq buffer (or buffer (current-buffer)))
6352 (let ((n 1) (base (buffer-name buffer)) bname)
6353 (while (buffer-live-p
6354 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6355 (setq n (1+ n)))
6356 (condition-case nil
6357 (make-indirect-buffer buffer bname 'clone)
6358 (error (make-indirect-buffer buffer bname)))))
6360 (defun org-set-frame-title (title)
6361 "Set the title of the current frame to the string TITLE."
6362 ;; FIXME: how to name a single frame in XEmacs???
6363 (unless (featurep 'xemacs)
6364 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6366 ;;;; Structure editing
6368 ;;; Inserting headlines
6370 (defun org-insert-heading (&optional force-heading)
6371 "Insert a new heading or item with same depth at point.
6372 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6373 If point is at the beginning of a headline, insert a sibling before the
6374 current headline. If point is not at the beginning, do not split the line,
6375 but create the new hedline after the current line."
6376 (interactive "P")
6377 (if (= (buffer-size) 0)
6378 (insert "\n* ")
6379 (when (or force-heading (not (org-insert-item)))
6380 (let* ((head (save-excursion
6381 (condition-case nil
6382 (progn
6383 (org-back-to-heading)
6384 (match-string 0))
6385 (error "*"))))
6386 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6387 pos)
6388 (cond
6389 ((and (org-on-heading-p) (bolp)
6390 (or (bobp)
6391 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6392 ;; insert before the current line
6393 (open-line (if blank 2 1)))
6394 ((and (bolp)
6395 (or (bobp)
6396 (save-excursion
6397 (backward-char 1) (not (org-invisible-p)))))
6398 ;; insert right here
6399 nil)
6401 ; ;; in the middle of the line
6402 ; (org-show-entry)
6403 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6404 ; (if (and
6405 ; (org-on-heading-p)
6406 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6407 ; ;; protect the tags
6408 ;; (let ((tags (match-string 2)) pos)
6409 ; (delete-region (match-beginning 1) (match-end 1))
6410 ; (setq pos (point-at-bol))
6411 ; (newline (if blank 2 1))
6412 ; (save-excursion
6413 ; (goto-char pos)
6414 ; (end-of-line 1)
6415 ; (insert " " tags)
6416 ; (org-set-tags nil 'align)))
6417 ; (newline (if blank 2 1)))
6418 ; (newline (if blank 2 1))))
6421 ;; in the middle of the line
6422 (org-show-entry)
6423 (let ((split
6424 (org-get-alist-option org-M-RET-may-split-line 'headline))
6425 tags pos)
6426 (if (org-on-heading-p)
6427 (progn
6428 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6429 (setq tags (and (match-end 2) (match-string 2)))
6430 (and (match-end 1)
6431 (delete-region (match-beginning 1) (match-end 1)))
6432 (setq pos (point-at-bol))
6433 (or split (end-of-line 1))
6434 (delete-horizontal-space)
6435 (newline (if blank 2 1))
6436 (when tags
6437 (save-excursion
6438 (goto-char pos)
6439 (end-of-line 1)
6440 (insert " " tags)
6441 (org-set-tags nil 'align))))
6442 (or split (end-of-line 1))
6443 (newline (if blank 2 1))))))
6444 (insert head) (just-one-space)
6445 (setq pos (point))
6446 (end-of-line 1)
6447 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6448 (run-hooks 'org-insert-heading-hook)))))
6450 (defun org-insert-heading-after-current ()
6451 "Insert a new heading with same level as current, after current subtree."
6452 (interactive)
6453 (org-back-to-heading)
6454 (org-insert-heading)
6455 (org-move-subtree-down)
6456 (end-of-line 1))
6458 (defun org-insert-todo-heading (arg)
6459 "Insert a new heading with the same level and TODO state as current heading.
6460 If the heading has no TODO state, or if the state is DONE, use the first
6461 state (TODO by default). Also with prefix arg, force first state."
6462 (interactive "P")
6463 (when (not (org-insert-item 'checkbox))
6464 (org-insert-heading)
6465 (save-excursion
6466 (org-back-to-heading)
6467 (outline-previous-heading)
6468 (looking-at org-todo-line-regexp))
6469 (if (or arg
6470 (not (match-beginning 2))
6471 (member (match-string 2) org-done-keywords))
6472 (insert (car org-todo-keywords-1) " ")
6473 (insert (match-string 2) " "))))
6475 (defun org-insert-subheading (arg)
6476 "Insert a new subheading and demote it.
6477 Works for outline headings and for plain lists alike."
6478 (interactive "P")
6479 (org-insert-heading arg)
6480 (cond
6481 ((org-on-heading-p) (org-do-demote))
6482 ((org-at-item-p) (org-indent-item 1))))
6484 (defun org-insert-todo-subheading (arg)
6485 "Insert a new subheading with TODO keyword or checkbox and demote it.
6486 Works for outline headings and for plain lists alike."
6487 (interactive "P")
6488 (org-insert-todo-heading arg)
6489 (cond
6490 ((org-on-heading-p) (org-do-demote))
6491 ((org-at-item-p) (org-indent-item 1))))
6493 ;;; Promotion and Demotion
6495 (defun org-promote-subtree ()
6496 "Promote the entire subtree.
6497 See also `org-promote'."
6498 (interactive)
6499 (save-excursion
6500 (org-map-tree 'org-promote))
6501 (org-fix-position-after-promote))
6503 (defun org-demote-subtree ()
6504 "Demote the entire subtree. See `org-demote'.
6505 See also `org-promote'."
6506 (interactive)
6507 (save-excursion
6508 (org-map-tree 'org-demote))
6509 (org-fix-position-after-promote))
6512 (defun org-do-promote ()
6513 "Promote the current heading higher up the tree.
6514 If the region is active in `transient-mark-mode', promote all headings
6515 in the region."
6516 (interactive)
6517 (save-excursion
6518 (if (org-region-active-p)
6519 (org-map-region 'org-promote (region-beginning) (region-end))
6520 (org-promote)))
6521 (org-fix-position-after-promote))
6523 (defun org-do-demote ()
6524 "Demote the current heading lower down the tree.
6525 If the region is active in `transient-mark-mode', demote all headings
6526 in the region."
6527 (interactive)
6528 (save-excursion
6529 (if (org-region-active-p)
6530 (org-map-region 'org-demote (region-beginning) (region-end))
6531 (org-demote)))
6532 (org-fix-position-after-promote))
6534 (defun org-fix-position-after-promote ()
6535 "Make sure that after pro/demotion cursor position is right."
6536 (let ((pos (point)))
6537 (when (save-excursion
6538 (beginning-of-line 1)
6539 (looking-at org-todo-line-regexp)
6540 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6541 (cond ((eobp) (insert " "))
6542 ((eolp) (insert " "))
6543 ((equal (char-after) ?\ ) (forward-char 1))))))
6545 (defun org-reduced-level (l)
6546 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6548 (defun org-get-valid-level (level &optional change)
6549 "Rectify a level change under the influence of `org-odd-levels-only'
6550 LEVEL is a current level, CHANGE is by how much the level should be
6551 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6552 even level numbers will become the next higher odd number."
6553 (if org-odd-levels-only
6554 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6555 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6556 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6557 (max 1 (+ level change))))
6559 (define-obsolete-function-alias 'org-get-legal-level
6560 'org-get-valid-level "23.1")
6562 (defun org-promote ()
6563 "Promote the current heading higher up the tree.
6564 If the region is active in `transient-mark-mode', promote all headings
6565 in the region."
6566 (org-back-to-heading t)
6567 (let* ((level (save-match-data (funcall outline-level)))
6568 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6569 (diff (abs (- level (length up-head) -1))))
6570 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6571 (replace-match up-head nil t)
6572 ;; Fixup tag positioning
6573 (and org-auto-align-tags (org-set-tags nil t))
6574 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6576 (defun org-demote ()
6577 "Demote the current heading lower down the tree.
6578 If the region is active in `transient-mark-mode', demote all headings
6579 in the region."
6580 (org-back-to-heading t)
6581 (let* ((level (save-match-data (funcall outline-level)))
6582 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6583 (diff (abs (- level (length down-head) -1))))
6584 (replace-match down-head nil t)
6585 ;; Fixup tag positioning
6586 (and org-auto-align-tags (org-set-tags nil t))
6587 (if org-adapt-indentation (org-fixup-indentation diff))))
6589 (defun org-map-tree (fun)
6590 "Call FUN for every heading underneath the current one."
6591 (org-back-to-heading)
6592 (let ((level (funcall outline-level)))
6593 (save-excursion
6594 (funcall fun)
6595 (while (and (progn
6596 (outline-next-heading)
6597 (> (funcall outline-level) level))
6598 (not (eobp)))
6599 (funcall fun)))))
6601 (defun org-map-region (fun beg end)
6602 "Call FUN for every heading between BEG and END."
6603 (let ((org-ignore-region t))
6604 (save-excursion
6605 (setq end (copy-marker end))
6606 (goto-char beg)
6607 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6608 (< (point) end))
6609 (funcall fun))
6610 (while (and (progn
6611 (outline-next-heading)
6612 (< (point) end))
6613 (not (eobp)))
6614 (funcall fun)))))
6616 (defun org-fixup-indentation (diff)
6617 "Change the indentation in the current entry by DIFF
6618 However, if any line in the current entry has no indentation, or if it
6619 would end up with no indentation after the change, nothing at all is done."
6620 (save-excursion
6621 (let ((end (save-excursion (outline-next-heading)
6622 (point-marker)))
6623 (prohibit (if (> diff 0)
6624 "^\\S-"
6625 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6626 col)
6627 (unless (save-excursion (end-of-line 1)
6628 (re-search-forward prohibit end t))
6629 (while (and (< (point) end)
6630 (re-search-forward "^[ \t]+" end t))
6631 (goto-char (match-end 0))
6632 (setq col (current-column))
6633 (if (< diff 0) (replace-match ""))
6634 (indent-to (+ diff col))))
6635 (move-marker end nil))))
6637 (defun org-convert-to-odd-levels ()
6638 "Convert an org-mode file with all levels allowed to one with odd levels.
6639 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6640 level 5 etc."
6641 (interactive)
6642 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6643 (let ((org-odd-levels-only nil) n)
6644 (save-excursion
6645 (goto-char (point-min))
6646 (while (re-search-forward "^\\*\\*+ " nil t)
6647 (setq n (- (length (match-string 0)) 2))
6648 (while (>= (setq n (1- n)) 0)
6649 (org-demote))
6650 (end-of-line 1))))))
6653 (defun org-convert-to-oddeven-levels ()
6654 "Convert an org-mode file with only odd levels to one with odd and even levels.
6655 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6656 section with an even level, conversion would destroy the structure of the file. An error
6657 is signaled in this case."
6658 (interactive)
6659 (goto-char (point-min))
6660 ;; First check if there are no even levels
6661 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6662 (org-show-context t)
6663 (error "Not all levels are odd in this file. Conversion not possible."))
6664 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6665 (let ((org-odd-levels-only nil) n)
6666 (save-excursion
6667 (goto-char (point-min))
6668 (while (re-search-forward "^\\*\\*+ " nil t)
6669 (setq n (/ (1- (length (match-string 0))) 2))
6670 (while (>= (setq n (1- n)) 0)
6671 (org-promote))
6672 (end-of-line 1))))))
6674 (defun org-tr-level (n)
6675 "Make N odd if required."
6676 (if org-odd-levels-only (1+ (/ n 2)) n))
6678 ;;; Vertical tree motion, cutting and pasting of subtrees
6680 (defun org-move-subtree-up (&optional arg)
6681 "Move the current subtree up past ARG headlines of the same level."
6682 (interactive "p")
6683 (org-move-subtree-down (- (prefix-numeric-value arg))))
6685 (defun org-move-subtree-down (&optional arg)
6686 "Move the current subtree down past ARG headlines of the same level."
6687 (interactive "p")
6688 (setq arg (prefix-numeric-value arg))
6689 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6690 'outline-get-last-sibling))
6691 (ins-point (make-marker))
6692 (cnt (abs arg))
6693 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6694 ;; Select the tree
6695 (org-back-to-heading)
6696 (setq beg0 (point))
6697 (save-excursion
6698 (setq ne-beg (org-back-over-empty-lines))
6699 (setq beg (point)))
6700 (save-match-data
6701 (save-excursion (outline-end-of-heading)
6702 (setq folded (org-invisible-p)))
6703 (outline-end-of-subtree))
6704 (outline-next-heading)
6705 (setq ne-end (org-back-over-empty-lines))
6706 (setq end (point))
6707 (goto-char beg0)
6708 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6709 ;; include less whitespace
6710 (save-excursion
6711 (goto-char beg)
6712 (forward-line (- ne-beg ne-end))
6713 (setq beg (point))))
6714 ;; Find insertion point, with error handling
6715 (while (> cnt 0)
6716 (or (and (funcall movfunc) (looking-at outline-regexp))
6717 (progn (goto-char beg0)
6718 (error "Cannot move past superior level or buffer limit")))
6719 (setq cnt (1- cnt)))
6720 (if (> arg 0)
6721 ;; Moving forward - still need to move over subtree
6722 (progn (org-end-of-subtree t t)
6723 (save-excursion
6724 (org-back-over-empty-lines)
6725 (or (bolp) (newline)))))
6726 (setq ne-ins (org-back-over-empty-lines))
6727 (move-marker ins-point (point))
6728 (setq txt (buffer-substring beg end))
6729 (delete-region beg end)
6730 (outline-flag-region (1- beg) beg nil)
6731 (outline-flag-region (1- (point)) (point) nil)
6732 (insert txt)
6733 (or (bolp) (insert "\n"))
6734 (setq ins-end (point))
6735 (goto-char ins-point)
6736 (org-skip-whitespace)
6737 (when (and (< arg 0)
6738 (org-first-sibling-p)
6739 (> ne-ins ne-beg))
6740 ;; Move whitespace back to beginning
6741 (save-excursion
6742 (goto-char ins-end)
6743 (let ((kill-whole-line t))
6744 (kill-line (- ne-ins ne-beg)) (point)))
6745 (insert (make-string (- ne-ins ne-beg) ?\n)))
6746 (move-marker ins-point nil)
6747 (org-compact-display-after-subtree-move)
6748 (unless folded
6749 (org-show-entry)
6750 (show-children)
6751 (org-cycle-hide-drawers 'children))))
6753 (defvar org-subtree-clip ""
6754 "Clipboard for cut and paste of subtrees.
6755 This is actually only a copy of the kill, because we use the normal kill
6756 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6758 (defvar org-subtree-clip-folded nil
6759 "Was the last copied subtree folded?
6760 This is used to fold the tree back after pasting.")
6762 (defun org-cut-subtree (&optional n)
6763 "Cut the current subtree into the clipboard.
6764 With prefix arg N, cut this many sequential subtrees.
6765 This is a short-hand for marking the subtree and then cutting it."
6766 (interactive "p")
6767 (org-copy-subtree n 'cut))
6769 (defun org-copy-subtree (&optional n cut)
6770 "Cut the current subtree into the clipboard.
6771 With prefix arg N, cut this many sequential subtrees.
6772 This is a short-hand for marking the subtree and then copying it.
6773 If CUT is non-nil, actually cut the subtree."
6774 (interactive "p")
6775 (let (beg end folded (beg0 (point)))
6776 (if (interactive-p)
6777 (org-back-to-heading nil) ; take what looks like a subtree
6778 (org-back-to-heading t)) ; take what is really there
6779 (org-back-over-empty-lines)
6780 (setq beg (point))
6781 (skip-chars-forward " \t\r\n")
6782 (save-match-data
6783 (save-excursion (outline-end-of-heading)
6784 (setq folded (org-invisible-p)))
6785 (condition-case nil
6786 (outline-forward-same-level (1- n))
6787 (error nil))
6788 (org-end-of-subtree t t))
6789 (org-back-over-empty-lines)
6790 (setq end (point))
6791 (goto-char beg0)
6792 (when (> end beg)
6793 (setq org-subtree-clip-folded folded)
6794 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6795 (setq org-subtree-clip (current-kill 0))
6796 (message "%s: Subtree(s) with %d characters"
6797 (if cut "Cut" "Copied")
6798 (length org-subtree-clip)))))
6800 (defun org-paste-subtree (&optional level tree)
6801 "Paste the clipboard as a subtree, with modification of headline level.
6802 The entire subtree is promoted or demoted in order to match a new headline
6803 level. By default, the new level is derived from the visible headings
6804 before and after the insertion point, and taken to be the inferior headline
6805 level of the two. So if the previous visible heading is level 3 and the
6806 next is level 4 (or vice versa), level 4 will be used for insertion.
6807 This makes sure that the subtree remains an independent subtree and does
6808 not swallow low level entries.
6810 You can also force a different level, either by using a numeric prefix
6811 argument, or by inserting the heading marker by hand. For example, if the
6812 cursor is after \"*****\", then the tree will be shifted to level 5.
6814 If you want to insert the tree as is, just use \\[yank].
6816 If optional TREE is given, use this text instead of the kill ring."
6817 (interactive "P")
6818 (unless (org-kill-is-subtree-p tree)
6819 (error "%s"
6820 (substitute-command-keys
6821 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6822 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6823 (^re (concat "^\\(" outline-regexp "\\)"))
6824 (re (concat "\\(" outline-regexp "\\)"))
6825 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6827 (old-level (if (string-match ^re txt)
6828 (- (match-end 0) (match-beginning 0) 1)
6829 -1))
6830 (force-level (cond (level (prefix-numeric-value level))
6831 ((string-match
6832 ^re_ (buffer-substring (point-at-bol) (point)))
6833 (- (match-end 1) (match-beginning 1)))
6834 (t nil)))
6835 (previous-level (save-excursion
6836 (condition-case nil
6837 (progn
6838 (outline-previous-visible-heading 1)
6839 (if (looking-at re)
6840 (- (match-end 0) (match-beginning 0) 1)
6842 (error 1))))
6843 (next-level (save-excursion
6844 (condition-case nil
6845 (progn
6846 (or (looking-at outline-regexp)
6847 (outline-next-visible-heading 1))
6848 (if (looking-at re)
6849 (- (match-end 0) (match-beginning 0) 1)
6851 (error 1))))
6852 (new-level (or force-level (max previous-level next-level)))
6853 (shift (if (or (= old-level -1)
6854 (= new-level -1)
6855 (= old-level new-level))
6857 (- new-level old-level)))
6858 (delta (if (> shift 0) -1 1))
6859 (func (if (> shift 0) 'org-demote 'org-promote))
6860 (org-odd-levels-only nil)
6861 beg end)
6862 ;; Remove the forced level indicator
6863 (if force-level
6864 (delete-region (point-at-bol) (point)))
6865 ;; Paste
6866 (beginning-of-line 1)
6867 (org-back-over-empty-lines) ;; FIXME: correct fix????
6868 (setq beg (point))
6869 (insert-before-markers txt) ;; FIXME: correct fix????
6870 (unless (string-match "\n\\'" txt) (insert "\n"))
6871 (setq end (point))
6872 (goto-char beg)
6873 (skip-chars-forward " \t\n\r")
6874 (setq beg (point))
6875 ;; Shift if necessary
6876 (unless (= shift 0)
6877 (save-restriction
6878 (narrow-to-region beg end)
6879 (while (not (= shift 0))
6880 (org-map-region func (point-min) (point-max))
6881 (setq shift (+ delta shift)))
6882 (goto-char (point-min))))
6883 (when (interactive-p)
6884 (message "Clipboard pasted as level %d subtree" new-level))
6885 (if (and kill-ring
6886 (eq org-subtree-clip (current-kill 0))
6887 org-subtree-clip-folded)
6888 ;; The tree was folded before it was killed/copied
6889 (hide-subtree))))
6891 (defun org-kill-is-subtree-p (&optional txt)
6892 "Check if the current kill is an outline subtree, or a set of trees.
6893 Returns nil if kill does not start with a headline, or if the first
6894 headline level is not the largest headline level in the tree.
6895 So this will actually accept several entries of equal levels as well,
6896 which is OK for `org-paste-subtree'.
6897 If optional TXT is given, check this string instead of the current kill."
6898 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6899 (start-level (and kill
6900 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6901 org-outline-regexp "\\)")
6902 kill)
6903 (- (match-end 2) (match-beginning 2) 1)))
6904 (re (concat "^" org-outline-regexp))
6905 (start (1+ (match-beginning 2))))
6906 (if (not start-level)
6907 (progn
6908 nil) ;; does not even start with a heading
6909 (catch 'exit
6910 (while (setq start (string-match re kill (1+ start)))
6911 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6912 (throw 'exit nil)))
6913 t))))
6915 (defun org-narrow-to-subtree ()
6916 "Narrow buffer to the current subtree."
6917 (interactive)
6918 (save-excursion
6919 (save-match-data
6920 (narrow-to-region
6921 (progn (org-back-to-heading) (point))
6922 (progn (org-end-of-subtree t t) (point))))))
6925 ;;; Outline Sorting
6927 (defun org-sort (with-case)
6928 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6929 Optional argument WITH-CASE means sort case-sensitively."
6930 (interactive "P")
6931 (if (org-at-table-p)
6932 (org-call-with-arg 'org-table-sort-lines with-case)
6933 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6935 (defvar org-priority-regexp) ; defined later in the file
6937 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6938 "Sort entries on a certain level of an outline tree.
6939 If there is an active region, the entries in the region are sorted.
6940 Else, if the cursor is before the first entry, sort the top-level items.
6941 Else, the children of the entry at point are sorted.
6943 Sorting can be alphabetically, numerically, and by date/time as given by
6944 the first time stamp in the entry. The command prompts for the sorting
6945 type unless it has been given to the function through the SORTING-TYPE
6946 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6947 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6948 called with point at the beginning of the record. It must return either
6949 a string or a number that should serve as the sorting key for that record.
6951 Comparing entries ignores case by default. However, with an optional argument
6952 WITH-CASE, the sorting considers case as well."
6953 (interactive "P")
6954 (let ((case-func (if with-case 'identity 'downcase))
6955 start beg end stars re re2
6956 txt what tmp plain-list-p)
6957 ;; Find beginning and end of region to sort
6958 (cond
6959 ((org-region-active-p)
6960 ;; we will sort the region
6961 (setq end (region-end)
6962 what "region")
6963 (goto-char (region-beginning))
6964 (if (not (org-on-heading-p)) (outline-next-heading))
6965 (setq start (point)))
6966 ((org-at-item-p)
6967 ;; we will sort this plain list
6968 (org-beginning-of-item-list) (setq start (point))
6969 (org-end-of-item-list) (setq end (point))
6970 (goto-char start)
6971 (setq plain-list-p t
6972 what "plain list"))
6973 ((or (org-on-heading-p)
6974 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6975 ;; we will sort the children of the current headline
6976 (org-back-to-heading)
6977 (setq start (point)
6978 end (progn (org-end-of-subtree t t)
6979 (org-back-over-empty-lines)
6980 (point))
6981 what "children")
6982 (goto-char start)
6983 (show-subtree)
6984 (outline-next-heading))
6986 ;; we will sort the top-level entries in this file
6987 (goto-char (point-min))
6988 (or (org-on-heading-p) (outline-next-heading))
6989 (setq start (point) end (point-max) what "top-level")
6990 (goto-char start)
6991 (show-all)))
6993 (setq beg (point))
6994 (if (>= beg end) (error "Nothing to sort"))
6996 (unless plain-list-p
6997 (looking-at "\\(\\*+\\)")
6998 (setq stars (match-string 1)
6999 re (concat "^" (regexp-quote stars) " +")
7000 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7001 txt (buffer-substring beg end))
7002 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7003 (if (and (not (equal stars "*")) (string-match re2 txt))
7004 (error "Region to sort contains a level above the first entry")))
7006 (unless sorting-type
7007 (message
7008 (if plain-list-p
7009 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7010 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7011 what)
7012 (setq sorting-type (read-char-exclusive))
7014 (and (= (downcase sorting-type) ?f)
7015 (setq getkey-func
7016 (completing-read "Sort using function: "
7017 obarray 'fboundp t nil nil))
7018 (setq getkey-func (intern getkey-func)))
7020 (and (= (downcase sorting-type) ?r)
7021 (setq property
7022 (completing-read "Property: "
7023 (mapcar 'list (org-buffer-property-keys t))
7024 nil t))))
7026 (message "Sorting entries...")
7028 (save-restriction
7029 (narrow-to-region start end)
7031 (let ((dcst (downcase sorting-type))
7032 (now (current-time)))
7033 (sort-subr
7034 (/= dcst sorting-type)
7035 ;; This function moves to the beginning character of the "record" to
7036 ;; be sorted.
7037 (if plain-list-p
7038 (lambda nil
7039 (if (org-at-item-p) t (goto-char (point-max))))
7040 (lambda nil
7041 (if (re-search-forward re nil t)
7042 (goto-char (match-beginning 0))
7043 (goto-char (point-max)))))
7044 ;; This function moves to the last character of the "record" being
7045 ;; sorted.
7046 (if plain-list-p
7047 'org-end-of-item
7048 (lambda nil
7049 (save-match-data
7050 (condition-case nil
7051 (outline-forward-same-level 1)
7052 (error
7053 (goto-char (point-max)))))))
7055 ;; This function returns the value that gets sorted against.
7056 (if plain-list-p
7057 (lambda nil
7058 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7059 (cond
7060 ((= dcst ?n)
7061 (string-to-number (buffer-substring (match-end 0)
7062 (point-at-eol))))
7063 ((= dcst ?a)
7064 (buffer-substring (match-end 0) (point-at-eol)))
7065 ((= dcst ?t)
7066 (if (re-search-forward org-ts-regexp
7067 (point-at-eol) t)
7068 (org-time-string-to-time (match-string 0))
7069 now))
7070 ((= dcst ?f)
7071 (if getkey-func
7072 (progn
7073 (setq tmp (funcall getkey-func))
7074 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7075 tmp)
7076 (error "Invalid key function `%s'" getkey-func)))
7077 (t (error "Invalid sorting type `%c'" sorting-type)))))
7078 (lambda nil
7079 (cond
7080 ((= dcst ?n)
7081 (if (looking-at outline-regexp)
7082 (string-to-number (buffer-substring (match-end 0)
7083 (point-at-eol)))
7084 nil))
7085 ((= dcst ?a)
7086 (funcall case-func (buffer-substring (point-at-bol)
7087 (point-at-eol))))
7088 ((= dcst ?t)
7089 (if (re-search-forward org-ts-regexp
7090 (save-excursion
7091 (forward-line 2)
7092 (point)) t)
7093 (org-time-string-to-time (match-string 0))
7094 now))
7095 ((= dcst ?p)
7096 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7097 (string-to-char (match-string 2))
7098 org-default-priority))
7099 ((= dcst ?r)
7100 (or (org-entry-get nil property) ""))
7101 ((= dcst ?f)
7102 (if getkey-func
7103 (progn
7104 (setq tmp (funcall getkey-func))
7105 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7106 tmp)
7107 (error "Invalid key function `%s'" getkey-func)))
7108 (t (error "Invalid sorting type `%c'" sorting-type)))))
7110 (cond
7111 ((= dcst ?a) 'string<)
7112 ((= dcst ?t) 'time-less-p)
7113 (t nil)))))
7114 (message "Sorting entries...done")))
7116 (defun org-do-sort (table what &optional with-case sorting-type)
7117 "Sort TABLE of WHAT according to SORTING-TYPE.
7118 The user will be prompted for the SORTING-TYPE if the call to this
7119 function does not specify it. WHAT is only for the prompt, to indicate
7120 what is being sorted. The sorting key will be extracted from
7121 the car of the elements of the table.
7122 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7123 (unless sorting-type
7124 (message
7125 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7126 what)
7127 (setq sorting-type (read-char-exclusive)))
7128 (let ((dcst (downcase sorting-type))
7129 extractfun comparefun)
7130 ;; Define the appropriate functions
7131 (cond
7132 ((= dcst ?n)
7133 (setq extractfun 'string-to-number
7134 comparefun (if (= dcst sorting-type) '< '>)))
7135 ((= dcst ?a)
7136 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7137 (lambda(x) (downcase (org-sort-remove-invisible x))))
7138 comparefun (if (= dcst sorting-type)
7139 'string<
7140 (lambda (a b) (and (not (string< a b))
7141 (not (string= a b)))))))
7142 ((= dcst ?t)
7143 (setq extractfun
7144 (lambda (x)
7145 (if (string-match org-ts-regexp x)
7146 (time-to-seconds
7147 (org-time-string-to-time (match-string 0 x)))
7149 comparefun (if (= dcst sorting-type) '< '>)))
7150 (t (error "Invalid sorting type `%c'" sorting-type)))
7152 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7153 table)
7154 (lambda (a b) (funcall comparefun (car a) (car b))))))
7156 ;;;; Plain list items, including checkboxes
7158 ;;; Plain list items
7160 (defun org-at-item-p ()
7161 "Is point in a line starting a hand-formatted item?"
7162 (let ((llt org-plain-list-ordered-item-terminator))
7163 (save-excursion
7164 (goto-char (point-at-bol))
7165 (looking-at
7166 (cond
7167 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7168 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7169 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7170 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7172 (defun org-in-item-p ()
7173 "It the cursor inside a plain list item.
7174 Does not have to be the first line."
7175 (save-excursion
7176 (condition-case nil
7177 (progn
7178 (org-beginning-of-item)
7179 (org-at-item-p)
7181 (error nil))))
7183 (defun org-insert-item (&optional checkbox)
7184 "Insert a new item at the current level.
7185 Return t when things worked, nil when we are not in an item."
7186 (when (save-excursion
7187 (condition-case nil
7188 (progn
7189 (org-beginning-of-item)
7190 (org-at-item-p)
7191 (if (org-invisible-p) (error "Invisible item"))
7193 (error nil)))
7194 (let* ((bul (match-string 0))
7195 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7196 (match-end 0)))
7197 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7198 pos)
7199 (cond
7200 ((and (org-at-item-p) (<= (point) eow))
7201 ;; before the bullet
7202 (beginning-of-line 1)
7203 (open-line (if blank 2 1)))
7204 ((<= (point) eow)
7205 (beginning-of-line 1))
7207 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7208 (end-of-line 1)
7209 (delete-horizontal-space))
7210 (newline (if blank 2 1))))
7211 (insert bul (if checkbox "[ ]" ""))
7212 (just-one-space)
7213 (setq pos (point))
7214 (end-of-line 1)
7215 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7216 (org-maybe-renumber-ordered-list)
7217 (and checkbox (org-update-checkbox-count-maybe))
7220 ;;; Checkboxes
7222 (defun org-at-item-checkbox-p ()
7223 "Is point at a line starting a plain-list item with a checklet?"
7224 (and (org-at-item-p)
7225 (save-excursion
7226 (goto-char (match-end 0))
7227 (skip-chars-forward " \t")
7228 (looking-at "\\[[- X]\\]"))))
7230 (defun org-toggle-checkbox (&optional arg)
7231 "Toggle the checkbox in the current line."
7232 (interactive "P")
7233 (catch 'exit
7234 (let (beg end status (firstnew 'unknown))
7235 (cond
7236 ((org-region-active-p)
7237 (setq beg (region-beginning) end (region-end)))
7238 ((org-on-heading-p)
7239 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7240 ((org-at-item-checkbox-p)
7241 (let ((pos (point)))
7242 (replace-match
7243 (cond (arg "[-]")
7244 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7245 (t "[ ]"))
7246 t t)
7247 (goto-char pos))
7248 (throw 'exit t))
7249 (t (error "Not at a checkbox or heading, and no active region")))
7250 (save-excursion
7251 (goto-char beg)
7252 (while (< (point) end)
7253 (when (org-at-item-checkbox-p)
7254 (setq status (equal (match-string 0) "[X]"))
7255 (when (eq firstnew 'unknown)
7256 (setq firstnew (not status)))
7257 (replace-match
7258 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7259 (beginning-of-line 2)))))
7260 (org-update-checkbox-count-maybe))
7262 (defun org-update-checkbox-count-maybe ()
7263 "Update checkbox statistics unless turned off by user."
7264 (when org-provide-checkbox-statistics
7265 (org-update-checkbox-count)))
7267 (defun org-update-checkbox-count (&optional all)
7268 "Update the checkbox statistics in the current section.
7269 This will find all statistic cookies like [57%] and [6/12] and update them
7270 with the current numbers. With optional prefix argument ALL, do this for
7271 the whole buffer."
7272 (interactive "P")
7273 (save-excursion
7274 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7275 (beg (condition-case nil
7276 (progn (outline-back-to-heading) (point))
7277 (error (point-min))))
7278 (end (move-marker (make-marker)
7279 (progn (outline-next-heading) (point))))
7280 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7281 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7282 (re-find (concat re "\\|" re-box))
7283 beg-cookie end-cookie is-percent c-on c-off lim
7284 eline curr-ind next-ind continue-from startsearch
7285 (cstat 0)
7287 (when all
7288 (goto-char (point-min))
7289 (outline-next-heading)
7290 (setq beg (point) end (point-max)))
7291 (goto-char end)
7292 ;; find each statistic cookie
7293 (while (re-search-backward re-find beg t)
7294 (setq beg-cookie (match-beginning 1)
7295 end-cookie (match-end 1)
7296 cstat (+ cstat (if end-cookie 1 0))
7297 startsearch (point-at-eol)
7298 continue-from (point-at-bol)
7299 is-percent (match-beginning 2)
7300 lim (cond
7301 ((org-on-heading-p) (outline-next-heading) (point))
7302 ((org-at-item-p) (org-end-of-item) (point))
7303 (t nil))
7304 c-on 0
7305 c-off 0)
7306 (when lim
7307 ;; find first checkbox for this cookie and gather
7308 ;; statistics from all that are at this indentation level
7309 (goto-char startsearch)
7310 (if (re-search-forward re-box lim t)
7311 (progn
7312 (org-beginning-of-item)
7313 (setq curr-ind (org-get-indentation))
7314 (setq next-ind curr-ind)
7315 (while (= curr-ind next-ind)
7316 (save-excursion (end-of-line) (setq eline (point)))
7317 (if (re-search-forward re-box eline t)
7318 (if (member (match-string 2) '("[ ]" "[-]"))
7319 (setq c-off (1+ c-off))
7320 (setq c-on (1+ c-on))
7323 (org-end-of-item)
7324 (setq next-ind (org-get-indentation))
7326 (goto-char continue-from)
7327 ;; update cookie
7328 (when end-cookie
7329 (delete-region beg-cookie end-cookie)
7330 (goto-char beg-cookie)
7331 (insert
7332 (if is-percent
7333 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7334 (format "[%d/%d]" c-on (+ c-on c-off)))))
7335 ;; update items checkbox if it has one
7336 (when (org-at-item-p)
7337 (org-beginning-of-item)
7338 (when (and (> (+ c-on c-off) 0)
7339 (re-search-forward re-box (point-at-eol) t))
7340 (setq beg-cookie (match-beginning 2)
7341 end-cookie (match-end 2))
7342 (delete-region beg-cookie end-cookie)
7343 (goto-char beg-cookie)
7344 (cond ((= c-off 0) (insert "[X]"))
7345 ((= c-on 0) (insert "[ ]"))
7346 (t (insert "[-]")))
7348 (goto-char continue-from))
7349 (when (interactive-p)
7350 (message "Checkbox satistics updated %s (%d places)"
7351 (if all "in entire file" "in current outline entry") cstat)))))
7353 (defun org-get-checkbox-statistics-face ()
7354 "Select the face for checkbox statistics.
7355 The face will be `org-done' when all relevant boxes are checked. Otherwise
7356 it will be `org-todo'."
7357 (if (match-end 1)
7358 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7359 (if (and (> (match-end 2) (match-beginning 2))
7360 (equal (match-string 2) (match-string 3)))
7361 'org-done
7362 'org-todo)))
7364 (defun org-get-indentation (&optional line)
7365 "Get the indentation of the current line, interpreting tabs.
7366 When LINE is given, assume it represents a line and compute its indentation."
7367 (if line
7368 (if (string-match "^ *" (org-remove-tabs line))
7369 (match-end 0))
7370 (save-excursion
7371 (beginning-of-line 1)
7372 (skip-chars-forward " \t")
7373 (current-column))))
7375 (defun org-remove-tabs (s &optional width)
7376 "Replace tabulators in S with spaces.
7377 Assumes that s is a single line, starting in column 0."
7378 (setq width (or width tab-width))
7379 (while (string-match "\t" s)
7380 (setq s (replace-match
7381 (make-string
7382 (- (* width (/ (+ (match-beginning 0) width) width))
7383 (match-beginning 0)) ?\ )
7384 t t s)))
7387 (defun org-fix-indentation (line ind)
7388 "Fix indentation in LINE.
7389 IND is a cons cell with target and minimum indentation.
7390 If the current indenation in LINE is smaller than the minimum,
7391 leave it alone. If it is larger than ind, set it to the target."
7392 (let* ((l (org-remove-tabs line))
7393 (i (org-get-indentation l))
7394 (i1 (car ind)) (i2 (cdr ind)))
7395 (if (>= i i2) (setq l (substring line i2)))
7396 (if (> i1 0)
7397 (concat (make-string i1 ?\ ) l)
7398 l)))
7400 (defcustom org-empty-line-terminates-plain-lists nil
7401 "Non-nil means, an empty line ends all plain list levels.
7402 When nil, empty lines are part of the preceeding item."
7403 :group 'org-plain-lists
7404 :type 'boolean)
7406 (defun org-beginning-of-item ()
7407 "Go to the beginning of the current hand-formatted item.
7408 If the cursor is not in an item, throw an error."
7409 (interactive)
7410 (let ((pos (point))
7411 (limit (save-excursion
7412 (condition-case nil
7413 (progn
7414 (org-back-to-heading)
7415 (beginning-of-line 2) (point))
7416 (error (point-min)))))
7417 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7418 ind ind1)
7419 (if (org-at-item-p)
7420 (beginning-of-line 1)
7421 (beginning-of-line 1)
7422 (skip-chars-forward " \t")
7423 (setq ind (current-column))
7424 (if (catch 'exit
7425 (while t
7426 (beginning-of-line 0)
7427 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7429 (if (looking-at "[ \t]*$")
7430 (setq ind1 ind-empty)
7431 (skip-chars-forward " \t")
7432 (setq ind1 (current-column)))
7433 (if (< ind1 ind)
7434 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7436 (goto-char pos)
7437 (error "Not in an item")))))
7439 (defun org-end-of-item ()
7440 "Go to the end of the current hand-formatted item.
7441 If the cursor is not in an item, throw an error."
7442 (interactive)
7443 (let* ((pos (point))
7444 ind1
7445 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7446 (limit (save-excursion (outline-next-heading) (point)))
7447 (ind (save-excursion
7448 (org-beginning-of-item)
7449 (skip-chars-forward " \t")
7450 (current-column)))
7451 (end (catch 'exit
7452 (while t
7453 (beginning-of-line 2)
7454 (if (eobp) (throw 'exit (point)))
7455 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7456 (if (looking-at "[ \t]*$")
7457 (setq ind1 ind-empty)
7458 (skip-chars-forward " \t")
7459 (setq ind1 (current-column)))
7460 (if (<= ind1 ind)
7461 (throw 'exit (point-at-bol)))))))
7462 (if end
7463 (goto-char end)
7464 (goto-char pos)
7465 (error "Not in an item"))))
7467 (defun org-next-item ()
7468 "Move to the beginning of the next item in the current plain list.
7469 Error if not at a plain list, or if this is the last item in the list."
7470 (interactive)
7471 (let (ind ind1 (pos (point)))
7472 (org-beginning-of-item)
7473 (setq ind (org-get-indentation))
7474 (org-end-of-item)
7475 (setq ind1 (org-get-indentation))
7476 (unless (and (org-at-item-p) (= ind ind1))
7477 (goto-char pos)
7478 (error "On last item"))))
7480 (defun org-previous-item ()
7481 "Move to the beginning of the previous item in the current plain list.
7482 Error if not at a plain list, or if this is the first item in the list."
7483 (interactive)
7484 (let (beg ind ind1 (pos (point)))
7485 (org-beginning-of-item)
7486 (setq beg (point))
7487 (setq ind (org-get-indentation))
7488 (goto-char beg)
7489 (catch 'exit
7490 (while t
7491 (beginning-of-line 0)
7492 (if (looking-at "[ \t]*$")
7494 (if (<= (setq ind1 (org-get-indentation)) ind)
7495 (throw 'exit t)))))
7496 (condition-case nil
7497 (if (or (not (org-at-item-p))
7498 (< ind1 (1- ind)))
7499 (error "")
7500 (org-beginning-of-item))
7501 (error (goto-char pos)
7502 (error "On first item")))))
7504 (defun org-first-list-item-p ()
7505 "Is this heading the item in a plain list?"
7506 (unless (org-at-item-p)
7507 (error "Not at a plain list item"))
7508 (org-beginning-of-item)
7509 (= (point) (save-excursion (org-beginning-of-item-list))))
7511 (defun org-move-item-down ()
7512 "Move the plain list item at point down, i.e. swap with following item.
7513 Subitems (items with larger indentation) are considered part of the item,
7514 so this really moves item trees."
7515 (interactive)
7516 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7517 (org-beginning-of-item)
7518 (setq beg0 (point))
7519 (save-excursion
7520 (setq ne-beg (org-back-over-empty-lines))
7521 (setq beg (point)))
7522 (goto-char beg0)
7523 (setq ind (org-get-indentation))
7524 (org-end-of-item)
7525 (setq end0 (point))
7526 (setq ind1 (org-get-indentation))
7527 (setq ne-end (org-back-over-empty-lines))
7528 (setq end (point))
7529 (goto-char beg0)
7530 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7531 ;; include less whitespace
7532 (save-excursion
7533 (goto-char beg)
7534 (forward-line (- ne-beg ne-end))
7535 (setq beg (point))))
7536 (goto-char end0)
7537 (if (and (org-at-item-p) (= ind ind1))
7538 (progn
7539 (org-end-of-item)
7540 (org-back-over-empty-lines)
7541 (setq txt (buffer-substring beg end))
7542 (save-excursion
7543 (delete-region beg end))
7544 (setq pos (point))
7545 (insert txt)
7546 (goto-char pos) (org-skip-whitespace)
7547 (org-maybe-renumber-ordered-list))
7548 (goto-char pos)
7549 (error "Cannot move this item further down"))))
7551 (defun org-move-item-up (arg)
7552 "Move the plain list item at point up, i.e. swap with previous item.
7553 Subitems (items with larger indentation) are considered part of the item,
7554 so this really moves item trees."
7555 (interactive "p")
7556 (let (beg beg0 end ind ind1 (pos (point)) txt
7557 ne-beg ne-ins ins-end)
7558 (org-beginning-of-item)
7559 (setq beg0 (point))
7560 (setq ind (org-get-indentation))
7561 (save-excursion
7562 (setq ne-beg (org-back-over-empty-lines))
7563 (setq beg (point)))
7564 (goto-char beg0)
7565 (org-end-of-item)
7566 (setq end (point))
7567 (goto-char beg0)
7568 (catch 'exit
7569 (while t
7570 (beginning-of-line 0)
7571 (if (looking-at "[ \t]*$")
7572 (if org-empty-line-terminates-plain-lists
7573 (progn
7574 (goto-char pos)
7575 (error "Cannot move this item further up"))
7576 nil)
7577 (if (<= (setq ind1 (org-get-indentation)) ind)
7578 (throw 'exit t)))))
7579 (condition-case nil
7580 (org-beginning-of-item)
7581 (error (goto-char beg)
7582 (error "Cannot move this item further up")))
7583 (setq ind1 (org-get-indentation))
7584 (if (and (org-at-item-p) (= ind ind1))
7585 (progn
7586 (setq ne-ins (org-back-over-empty-lines))
7587 (setq txt (buffer-substring beg end))
7588 (save-excursion
7589 (delete-region beg end))
7590 (setq pos (point))
7591 (insert txt)
7592 (setq ins-end (point))
7593 (goto-char pos) (org-skip-whitespace)
7595 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7596 ;; Move whitespace back to beginning
7597 (save-excursion
7598 (goto-char ins-end)
7599 (let ((kill-whole-line t))
7600 (kill-line (- ne-ins ne-beg)) (point)))
7601 (insert (make-string (- ne-ins ne-beg) ?\n)))
7603 (org-maybe-renumber-ordered-list))
7604 (goto-char pos)
7605 (error "Cannot move this item further up"))))
7607 (defun org-maybe-renumber-ordered-list ()
7608 "Renumber the ordered list at point if setup allows it.
7609 This tests the user option `org-auto-renumber-ordered-lists' before
7610 doing the renumbering."
7611 (interactive)
7612 (when (and org-auto-renumber-ordered-lists
7613 (org-at-item-p))
7614 (if (match-beginning 3)
7615 (org-renumber-ordered-list 1)
7616 (org-fix-bullet-type))))
7618 (defun org-maybe-renumber-ordered-list-safe ()
7619 (condition-case nil
7620 (save-excursion
7621 (org-maybe-renumber-ordered-list))
7622 (error nil)))
7624 (defun org-cycle-list-bullet (&optional which)
7625 "Cycle through the different itemize/enumerate bullets.
7626 This cycle the entire list level through the sequence:
7628 `-' -> `+' -> `*' -> `1.' -> `1)'
7630 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7631 0 meand `-', 1 means `+' etc."
7632 (interactive "P")
7633 (org-preserve-lc
7634 (org-beginning-of-item-list)
7635 (org-at-item-p)
7636 (beginning-of-line 1)
7637 (let ((current (match-string 0))
7638 (prevp (eq which 'previous))
7639 new)
7640 (setq new (cond
7641 ((and (numberp which)
7642 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7643 ((string-match "-" current) (if prevp "1)" "+"))
7644 ((string-match "\\+" current)
7645 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7646 ((string-match "\\*" current) (if prevp "+" "1."))
7647 ((string-match "\\." current) (if prevp "*" "1)"))
7648 ((string-match ")" current) (if prevp "1." "-"))
7649 (t (error "This should not happen"))))
7650 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7651 (org-fix-bullet-type)
7652 (org-maybe-renumber-ordered-list))))
7654 (defun org-get-string-indentation (s)
7655 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7656 (let ((n -1) (i 0) (w tab-width) c)
7657 (catch 'exit
7658 (while (< (setq n (1+ n)) (length s))
7659 (setq c (aref s n))
7660 (cond ((= c ?\ ) (setq i (1+ i)))
7661 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7662 (t (throw 'exit t)))))
7665 (defun org-renumber-ordered-list (arg)
7666 "Renumber an ordered plain list.
7667 Cursor needs to be in the first line of an item, the line that starts
7668 with something like \"1.\" or \"2)\"."
7669 (interactive "p")
7670 (unless (and (org-at-item-p)
7671 (match-beginning 3))
7672 (error "This is not an ordered list"))
7673 (let ((line (org-current-line))
7674 (col (current-column))
7675 (ind (org-get-string-indentation
7676 (buffer-substring (point-at-bol) (match-beginning 3))))
7677 ;; (term (substring (match-string 3) -1))
7678 ind1 (n (1- arg))
7679 fmt)
7680 ;; find where this list begins
7681 (org-beginning-of-item-list)
7682 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7683 (setq fmt (concat "%d" (match-string 1)))
7684 (beginning-of-line 0)
7685 ;; walk forward and replace these numbers
7686 (catch 'exit
7687 (while t
7688 (catch 'next
7689 (beginning-of-line 2)
7690 (if (eobp) (throw 'exit nil))
7691 (if (looking-at "[ \t]*$") (throw 'next nil))
7692 (skip-chars-forward " \t") (setq ind1 (current-column))
7693 (if (> ind1 ind) (throw 'next t))
7694 (if (< ind1 ind) (throw 'exit t))
7695 (if (not (org-at-item-p)) (throw 'exit nil))
7696 (delete-region (match-beginning 2) (match-end 2))
7697 (goto-char (match-beginning 2))
7698 (insert (format fmt (setq n (1+ n)))))))
7699 (goto-line line)
7700 (move-to-column col)))
7702 (defun org-fix-bullet-type ()
7703 "Make sure all items in this list have the same bullet as the firsst item."
7704 (interactive)
7705 (unless (org-at-item-p) (error "This is not a list"))
7706 (let ((line (org-current-line))
7707 (col (current-column))
7708 (ind (current-indentation))
7709 ind1 bullet)
7710 ;; find where this list begins
7711 (org-beginning-of-item-list)
7712 (beginning-of-line 1)
7713 ;; find out what the bullet type is
7714 (looking-at "[ \t]*\\(\\S-+\\)")
7715 (setq bullet (match-string 1))
7716 ;; walk forward and replace these numbers
7717 (beginning-of-line 0)
7718 (catch 'exit
7719 (while t
7720 (catch 'next
7721 (beginning-of-line 2)
7722 (if (eobp) (throw 'exit nil))
7723 (if (looking-at "[ \t]*$") (throw 'next nil))
7724 (skip-chars-forward " \t") (setq ind1 (current-column))
7725 (if (> ind1 ind) (throw 'next t))
7726 (if (< ind1 ind) (throw 'exit t))
7727 (if (not (org-at-item-p)) (throw 'exit nil))
7728 (skip-chars-forward " \t")
7729 (looking-at "\\S-+")
7730 (replace-match bullet))))
7731 (goto-line line)
7732 (move-to-column col)
7733 (if (string-match "[0-9]" bullet)
7734 (org-renumber-ordered-list 1))))
7736 (defun org-beginning-of-item-list ()
7737 "Go to the beginning of the current item list.
7738 I.e. to the first item in this list."
7739 (interactive)
7740 (org-beginning-of-item)
7741 (let ((pos (point-at-bol))
7742 (ind (org-get-indentation))
7743 ind1)
7744 ;; find where this list begins
7745 (catch 'exit
7746 (while t
7747 (catch 'next
7748 (beginning-of-line 0)
7749 (if (looking-at "[ \t]*$")
7750 (throw (if (bobp) 'exit 'next) t))
7751 (skip-chars-forward " \t") (setq ind1 (current-column))
7752 (if (or (< ind1 ind)
7753 (and (= ind1 ind)
7754 (not (org-at-item-p)))
7755 (bobp))
7756 (throw 'exit t)
7757 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7758 (goto-char pos)))
7761 (defun org-end-of-item-list ()
7762 "Go to the end of the current item list.
7763 I.e. to the text after the last item."
7764 (interactive)
7765 (org-beginning-of-item)
7766 (let ((pos (point-at-bol))
7767 (ind (org-get-indentation))
7768 ind1)
7769 ;; find where this list begins
7770 (catch 'exit
7771 (while t
7772 (catch 'next
7773 (beginning-of-line 2)
7774 (if (looking-at "[ \t]*$")
7775 (throw (if (eobp) 'exit 'next) t))
7776 (skip-chars-forward " \t") (setq ind1 (current-column))
7777 (if (or (< ind1 ind)
7778 (and (= ind1 ind)
7779 (not (org-at-item-p)))
7780 (eobp))
7781 (progn
7782 (setq pos (point-at-bol))
7783 (throw 'exit t))))))
7784 (goto-char pos)))
7787 (defvar org-last-indent-begin-marker (make-marker))
7788 (defvar org-last-indent-end-marker (make-marker))
7790 (defun org-outdent-item (arg)
7791 "Outdent a local list item."
7792 (interactive "p")
7793 (org-indent-item (- arg)))
7795 (defun org-indent-item (arg)
7796 "Indent a local list item."
7797 (interactive "p")
7798 (unless (org-at-item-p)
7799 (error "Not on an item"))
7800 (save-excursion
7801 (let (beg end ind ind1 tmp delta ind-down ind-up)
7802 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7803 (setq beg org-last-indent-begin-marker
7804 end org-last-indent-end-marker)
7805 (org-beginning-of-item)
7806 (setq beg (move-marker org-last-indent-begin-marker (point)))
7807 (org-end-of-item)
7808 (setq end (move-marker org-last-indent-end-marker (point))))
7809 (goto-char beg)
7810 (setq tmp (org-item-indent-positions)
7811 ind (car tmp)
7812 ind-down (nth 2 tmp)
7813 ind-up (nth 1 tmp)
7814 delta (if (> arg 0)
7815 (if ind-down (- ind-down ind) 2)
7816 (if ind-up (- ind-up ind) -2)))
7817 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7818 (while (< (point) end)
7819 (beginning-of-line 1)
7820 (skip-chars-forward " \t") (setq ind1 (current-column))
7821 (delete-region (point-at-bol) (point))
7822 (or (eolp) (indent-to-column (+ ind1 delta)))
7823 (beginning-of-line 2))))
7824 (org-fix-bullet-type)
7825 (org-maybe-renumber-ordered-list-safe)
7826 (save-excursion
7827 (beginning-of-line 0)
7828 (condition-case nil (org-beginning-of-item) (error nil))
7829 (org-maybe-renumber-ordered-list-safe)))
7831 (defun org-item-indent-positions ()
7832 "Return indentation for plain list items.
7833 This returns a list with three values: The current indentation, the
7834 parent indentation and the indentation a child should habe.
7835 Assumes cursor in item line."
7836 (let* ((bolpos (point-at-bol))
7837 (ind (org-get-indentation))
7838 ind-down ind-up pos)
7839 (save-excursion
7840 (org-beginning-of-item-list)
7841 (skip-chars-backward "\n\r \t")
7842 (when (org-in-item-p)
7843 (org-beginning-of-item)
7844 (setq ind-up (org-get-indentation))))
7845 (setq pos (point))
7846 (save-excursion
7847 (cond
7848 ((and (condition-case nil (progn (org-previous-item) t)
7849 (error nil))
7850 (or (forward-char 1) t)
7851 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7852 (setq ind-down (org-get-indentation)))
7853 ((and (goto-char pos)
7854 (org-at-item-p))
7855 (goto-char (match-end 0))
7856 (skip-chars-forward " \t")
7857 (setq ind-down (current-column)))))
7858 (list ind ind-up ind-down)))
7860 ;;; The orgstruct minor mode
7862 ;; Define a minor mode which can be used in other modes in order to
7863 ;; integrate the org-mode structure editing commands.
7865 ;; This is really a hack, because the org-mode structure commands use
7866 ;; keys which normally belong to the major mode. Here is how it
7867 ;; works: The minor mode defines all the keys necessary to operate the
7868 ;; structure commands, but wraps the commands into a function which
7869 ;; tests if the cursor is currently at a headline or a plain list
7870 ;; item. If that is the case, the structure command is used,
7871 ;; temporarily setting many Org-mode variables like regular
7872 ;; expressions for filling etc. However, when any of those keys is
7873 ;; used at a different location, function uses `key-binding' to look
7874 ;; up if the key has an associated command in another currently active
7875 ;; keymap (minor modes, major mode, global), and executes that
7876 ;; command. There might be problems if any of the keys is otherwise
7877 ;; used as a prefix key.
7879 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7880 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7881 ;; addresses this by checking explicitly for both bindings.
7883 (defvar orgstruct-mode-map (make-sparse-keymap)
7884 "Keymap for the minor `orgstruct-mode'.")
7886 (defvar org-local-vars nil
7887 "List of local variables, for use by `orgstruct-mode'")
7889 ;;;###autoload
7890 (define-minor-mode orgstruct-mode
7891 "Toggle the minor more `orgstruct-mode'.
7892 This mode is for using Org-mode structure commands in other modes.
7893 The following key behave as if Org-mode was active, if the cursor
7894 is on a headline, or on a plain list item (both in the definition
7895 of Org-mode).
7897 M-up Move entry/item up
7898 M-down Move entry/item down
7899 M-left Promote
7900 M-right Demote
7901 M-S-up Move entry/item up
7902 M-S-down Move entry/item down
7903 M-S-left Promote subtree
7904 M-S-right Demote subtree
7905 M-q Fill paragraph and items like in Org-mode
7906 C-c ^ Sort entries
7907 C-c - Cycle list bullet
7908 TAB Cycle item visibility
7909 M-RET Insert new heading/item
7910 S-M-RET Insert new TODO heading / Chekbox item
7911 C-c C-c Set tags / toggle checkbox"
7912 nil " OrgStruct" nil
7913 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7915 ;;;###autoload
7916 (defun turn-on-orgstruct ()
7917 "Unconditionally turn on `orgstruct-mode'."
7918 (orgstruct-mode 1))
7920 ;;;###autoload
7921 (defun turn-on-orgstruct++ ()
7922 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7923 In addition to setting orgstruct-mode, this also exports all indentation and
7924 autofilling variables from org-mode into the buffer. Note that turning
7925 off orgstruct-mode will *not* remove these additional settings."
7926 (orgstruct-mode 1)
7927 (let (var val)
7928 (mapc
7929 (lambda (x)
7930 (when (string-match
7931 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7932 (symbol-name (car x)))
7933 (setq var (car x) val (nth 1 x))
7934 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7935 org-local-vars)))
7937 (defun orgstruct-error ()
7938 "Error when there is no default binding for a structure key."
7939 (interactive)
7940 (error "This key has no function outside structure elements"))
7942 (defun orgstruct-setup ()
7943 "Setup orgstruct keymaps."
7944 (let ((nfunc 0)
7945 (bindings
7946 (list
7947 '([(meta up)] org-metaup)
7948 '([(meta down)] org-metadown)
7949 '([(meta left)] org-metaleft)
7950 '([(meta right)] org-metaright)
7951 '([(meta shift up)] org-shiftmetaup)
7952 '([(meta shift down)] org-shiftmetadown)
7953 '([(meta shift left)] org-shiftmetaleft)
7954 '([(meta shift right)] org-shiftmetaright)
7955 '([(shift up)] org-shiftup)
7956 '([(shift down)] org-shiftdown)
7957 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7958 '("\M-q" fill-paragraph)
7959 '("\C-c^" org-sort)
7960 '("\C-c-" org-cycle-list-bullet)))
7961 elt key fun cmd)
7962 (while (setq elt (pop bindings))
7963 (setq nfunc (1+ nfunc))
7964 (setq key (org-key (car elt))
7965 fun (nth 1 elt)
7966 cmd (orgstruct-make-binding fun nfunc key))
7967 (org-defkey orgstruct-mode-map key cmd))
7969 ;; Special treatment needed for TAB and RET
7970 (org-defkey orgstruct-mode-map [(tab)]
7971 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7972 (org-defkey orgstruct-mode-map "\C-i"
7973 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7975 (org-defkey orgstruct-mode-map "\M-\C-m"
7976 (orgstruct-make-binding 'org-insert-heading 105
7977 "\M-\C-m" [(meta return)]))
7978 (org-defkey orgstruct-mode-map [(meta return)]
7979 (orgstruct-make-binding 'org-insert-heading 106
7980 [(meta return)] "\M-\C-m"))
7982 (org-defkey orgstruct-mode-map [(shift meta return)]
7983 (orgstruct-make-binding 'org-insert-todo-heading 107
7984 [(meta return)] "\M-\C-m"))
7986 (unless org-local-vars
7987 (setq org-local-vars (org-get-local-variables)))
7991 (defun orgstruct-make-binding (fun n &rest keys)
7992 "Create a function for binding in the structure minor mode.
7993 FUN is the command to call inside a table. N is used to create a unique
7994 command name. KEYS are keys that should be checked in for a command
7995 to execute outside of tables."
7996 (eval
7997 (list 'defun
7998 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7999 '(arg)
8000 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8001 "Outside of structure, run the binding of `"
8002 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8003 "'.")
8004 '(interactive "p")
8005 (list 'if
8006 '(org-context-p 'headline 'item)
8007 (list 'org-run-like-in-org-mode (list 'quote fun))
8008 (list 'let '(orgstruct-mode)
8009 (list 'call-interactively
8010 (append '(or)
8011 (mapcar (lambda (k)
8012 (list 'key-binding k))
8013 keys)
8014 '('orgstruct-error))))))))
8016 (defun org-context-p (&rest contexts)
8017 "Check if local context is and of CONTEXTS.
8018 Possible values in the list of contexts are `table', `headline', and `item'."
8019 (let ((pos (point)))
8020 (goto-char (point-at-bol))
8021 (prog1 (or (and (memq 'table contexts)
8022 (looking-at "[ \t]*|"))
8023 (and (memq 'headline contexts)
8024 (looking-at "\\*+"))
8025 (and (memq 'item contexts)
8026 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8027 (goto-char pos))))
8029 (defun org-get-local-variables ()
8030 "Return a list of all local variables in an org-mode buffer."
8031 (let (varlist)
8032 (with-current-buffer (get-buffer-create "*Org tmp*")
8033 (erase-buffer)
8034 (org-mode)
8035 (setq varlist (buffer-local-variables)))
8036 (kill-buffer "*Org tmp*")
8037 (delq nil
8038 (mapcar
8039 (lambda (x)
8040 (setq x
8041 (if (symbolp x)
8042 (list x)
8043 (list (car x) (list 'quote (cdr x)))))
8044 (if (string-match
8045 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8046 (symbol-name (car x)))
8047 x nil))
8048 varlist))))
8050 ;;;###autoload
8051 (defun org-run-like-in-org-mode (cmd)
8052 (unless org-local-vars
8053 (setq org-local-vars (org-get-local-variables)))
8054 (eval (list 'let org-local-vars
8055 (list 'call-interactively (list 'quote cmd)))))
8057 ;;;; Archiving
8059 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8061 (defun org-archive-subtree (&optional find-done)
8062 "Move the current subtree to the archive.
8063 The archive can be a certain top-level heading in the current file, or in
8064 a different file. The tree will be moved to that location, the subtree
8065 heading be marked DONE, and the current time will be added.
8067 When called with prefix argument FIND-DONE, find whole trees without any
8068 open TODO items and archive them (after getting confirmation from the user).
8069 If the cursor is not at a headline when this comand is called, try all level
8070 1 trees. If the cursor is on a headline, only try the direct children of
8071 this heading."
8072 (interactive "P")
8073 (if find-done
8074 (org-archive-all-done)
8075 ;; Save all relevant TODO keyword-relatex variables
8077 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8078 (tr-org-todo-keywords-1 org-todo-keywords-1)
8079 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8080 (tr-org-done-keywords org-done-keywords)
8081 (tr-org-todo-regexp org-todo-regexp)
8082 (tr-org-todo-line-regexp org-todo-line-regexp)
8083 (tr-org-odd-levels-only org-odd-levels-only)
8084 (this-buffer (current-buffer))
8085 (org-archive-location org-archive-location)
8086 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8087 ;; start of variables that will be used for saving context
8088 ;; The compiler complains about them - keep them anyway!
8089 (file (abbreviate-file-name (buffer-file-name)))
8090 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8091 (time (format-time-string
8092 (substring (cdr org-time-stamp-formats) 1 -1)
8093 (current-time)))
8094 afile heading buffer level newfile-p
8095 category todo priority
8096 ;; start of variables that will be used for savind context
8097 ltags itags prop)
8099 ;; Try to find a local archive location
8100 (save-excursion
8101 (save-restriction
8102 (widen)
8103 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8104 (if (and prop (string-match "\\S-" prop))
8105 (setq org-archive-location prop)
8106 (if (or (re-search-backward re nil t)
8107 (re-search-forward re nil t))
8108 (setq org-archive-location (match-string 1))))))
8110 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8111 (progn
8112 (setq afile (format (match-string 1 org-archive-location)
8113 (file-name-nondirectory buffer-file-name))
8114 heading (match-string 2 org-archive-location)))
8115 (error "Invalid `org-archive-location'"))
8116 (if (> (length afile) 0)
8117 (setq newfile-p (not (file-exists-p afile))
8118 buffer (find-file-noselect afile))
8119 (setq buffer (current-buffer)))
8120 (unless buffer
8121 (error "Cannot access file \"%s\"" afile))
8122 (if (and (> (length heading) 0)
8123 (string-match "^\\*+" heading))
8124 (setq level (match-end 0))
8125 (setq heading nil level 0))
8126 (save-excursion
8127 (org-back-to-heading t)
8128 ;; Get context information that will be lost by moving the tree
8129 (org-refresh-category-properties)
8130 (setq category (org-get-category)
8131 todo (and (looking-at org-todo-line-regexp)
8132 (match-string 2))
8133 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8134 ltags (org-get-tags)
8135 itags (org-delete-all ltags (org-get-tags-at)))
8136 (setq ltags (mapconcat 'identity ltags " ")
8137 itags (mapconcat 'identity itags " "))
8138 ;; We first only copy, in case something goes wrong
8139 ;; we need to protect this-command, to avoid kill-region sets it,
8140 ;; which would lead to duplication of subtrees
8141 (let (this-command) (org-copy-subtree))
8142 (set-buffer buffer)
8143 ;; Enforce org-mode for the archive buffer
8144 (if (not (org-mode-p))
8145 ;; Force the mode for future visits.
8146 (let ((org-insert-mode-line-in-empty-file t)
8147 (org-inhibit-startup t))
8148 (call-interactively 'org-mode)))
8149 (when newfile-p
8150 (goto-char (point-max))
8151 (insert (format "\nArchived entries from file %s\n\n"
8152 (buffer-file-name this-buffer))))
8153 ;; Force the TODO keywords of the original buffer
8154 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8155 (org-todo-keywords-1 tr-org-todo-keywords-1)
8156 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8157 (org-done-keywords tr-org-done-keywords)
8158 (org-todo-regexp tr-org-todo-regexp)
8159 (org-todo-line-regexp tr-org-todo-line-regexp)
8160 (org-odd-levels-only
8161 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8162 org-odd-levels-only
8163 tr-org-odd-levels-only)))
8164 (goto-char (point-min))
8165 (show-all)
8166 (if heading
8167 (progn
8168 (if (re-search-forward
8169 (concat "^" (regexp-quote heading)
8170 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8171 nil t)
8172 (goto-char (match-end 0))
8173 ;; Heading not found, just insert it at the end
8174 (goto-char (point-max))
8175 (or (bolp) (insert "\n"))
8176 (insert "\n" heading "\n")
8177 (end-of-line 0))
8178 ;; Make the subtree visible
8179 (show-subtree)
8180 (org-end-of-subtree t)
8181 (skip-chars-backward " \t\r\n")
8182 (and (looking-at "[ \t\r\n]*")
8183 (replace-match "\n\n")))
8184 ;; No specific heading, just go to end of file.
8185 (goto-char (point-max)) (insert "\n"))
8186 ;; Paste
8187 (org-paste-subtree (org-get-valid-level level 1))
8189 ;; Mark the entry as done
8190 (when (and org-archive-mark-done
8191 (looking-at org-todo-line-regexp)
8192 (or (not (match-end 2))
8193 (not (member (match-string 2) org-done-keywords))))
8194 (let (org-log-done org-todo-log-states)
8195 (org-todo
8196 (car (or (member org-archive-mark-done org-done-keywords)
8197 org-done-keywords)))))
8199 ;; Add the context info
8200 (when org-archive-save-context-info
8201 (let ((l org-archive-save-context-info) e n v)
8202 (while (setq e (pop l))
8203 (when (and (setq v (symbol-value e))
8204 (stringp v) (string-match "\\S-" v))
8205 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8206 (org-entry-put (point) n v)))))
8208 ;; Save and kill the buffer, if it is not the same buffer.
8209 (if (not (eq this-buffer buffer))
8210 (progn (save-buffer) (kill-buffer buffer)))))
8211 ;; Here we are back in the original buffer. Everything seems to have
8212 ;; worked. So now cut the tree and finish up.
8213 (let (this-command) (org-cut-subtree))
8214 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8215 (message "Subtree archived %s"
8216 (if (eq this-buffer buffer)
8217 (concat "under heading: " heading)
8218 (concat "in file: " (abbreviate-file-name afile)))))))
8220 (defun org-refresh-category-properties ()
8221 "Refresh category text properties in teh buffer."
8222 (let ((def-cat (cond
8223 ((null org-category)
8224 (if buffer-file-name
8225 (file-name-sans-extension
8226 (file-name-nondirectory buffer-file-name))
8227 "???"))
8228 ((symbolp org-category) (symbol-name org-category))
8229 (t org-category)))
8230 beg end cat pos optionp)
8231 (org-unmodified
8232 (save-excursion
8233 (save-restriction
8234 (widen)
8235 (goto-char (point-min))
8236 (put-text-property (point) (point-max) 'org-category def-cat)
8237 (while (re-search-forward
8238 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8239 (setq pos (match-end 0)
8240 optionp (equal (char-after (match-beginning 0)) ?#)
8241 cat (org-trim (match-string 2)))
8242 (if optionp
8243 (setq beg (point-at-bol) end (point-max))
8244 (org-back-to-heading t)
8245 (setq beg (point) end (org-end-of-subtree t t)))
8246 (put-text-property beg end 'org-category cat)
8247 (goto-char pos)))))))
8249 (defun org-archive-all-done (&optional tag)
8250 "Archive sublevels of the current tree without open TODO items.
8251 If the cursor is not on a headline, try all level 1 trees. If
8252 it is on a headline, try all direct children.
8253 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8254 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8255 (rea (concat ".*:" org-archive-tag ":"))
8256 (begm (make-marker))
8257 (endm (make-marker))
8258 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8259 "Move subtree to archive (no open TODO items)? "))
8260 beg end (cntarch 0))
8261 (if (org-on-heading-p)
8262 (progn
8263 (setq re1 (concat "^" (regexp-quote
8264 (make-string
8265 (1+ (- (match-end 0) (match-beginning 0) 1))
8266 ?*))
8267 " "))
8268 (move-marker begm (point))
8269 (move-marker endm (org-end-of-subtree t)))
8270 (setq re1 "^* ")
8271 (move-marker begm (point-min))
8272 (move-marker endm (point-max)))
8273 (save-excursion
8274 (goto-char begm)
8275 (while (re-search-forward re1 endm t)
8276 (setq beg (match-beginning 0)
8277 end (save-excursion (org-end-of-subtree t) (point)))
8278 (goto-char beg)
8279 (if (re-search-forward re end t)
8280 (goto-char end)
8281 (goto-char beg)
8282 (if (and (or (not tag) (not (looking-at rea)))
8283 (y-or-n-p question))
8284 (progn
8285 (if tag
8286 (org-toggle-tag org-archive-tag 'on)
8287 (org-archive-subtree))
8288 (setq cntarch (1+ cntarch)))
8289 (goto-char end)))))
8290 (message "%d trees archived" cntarch)))
8292 (defun org-cycle-hide-drawers (state)
8293 "Re-hide all drawers after a visibility state change."
8294 (when (and (org-mode-p)
8295 (not (memq state '(overview folded))))
8296 (save-excursion
8297 (let* ((globalp (memq state '(contents all)))
8298 (beg (if globalp (point-min) (point)))
8299 (end (if globalp (point-max) (org-end-of-subtree t))))
8300 (goto-char beg)
8301 (while (re-search-forward org-drawer-regexp end t)
8302 (org-flag-drawer t))))))
8304 (defun org-flag-drawer (flag)
8305 (save-excursion
8306 (beginning-of-line 1)
8307 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8308 (let ((b (match-end 0))
8309 (outline-regexp org-outline-regexp))
8310 (if (re-search-forward
8311 "^[ \t]*:END:"
8312 (save-excursion (outline-next-heading) (point)) t)
8313 (outline-flag-region b (point-at-eol) flag)
8314 (error ":END: line missing"))))))
8316 (defun org-cycle-hide-archived-subtrees (state)
8317 "Re-hide all archived subtrees after a visibility state change."
8318 (when (and (not org-cycle-open-archived-trees)
8319 (not (memq state '(overview folded))))
8320 (save-excursion
8321 (let* ((globalp (memq state '(contents all)))
8322 (beg (if globalp (point-min) (point)))
8323 (end (if globalp (point-max) (org-end-of-subtree t))))
8324 (org-hide-archived-subtrees beg end)
8325 (goto-char beg)
8326 (if (looking-at (concat ".*:" org-archive-tag ":"))
8327 (message "%s" (substitute-command-keys
8328 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8330 (defun org-force-cycle-archived ()
8331 "Cycle subtree even if it is archived."
8332 (interactive)
8333 (setq this-command 'org-cycle)
8334 (let ((org-cycle-open-archived-trees t))
8335 (call-interactively 'org-cycle)))
8337 (defun org-hide-archived-subtrees (beg end)
8338 "Re-hide all archived subtrees after a visibility state change."
8339 (save-excursion
8340 (let* ((re (concat ":" org-archive-tag ":")))
8341 (goto-char beg)
8342 (while (re-search-forward re end t)
8343 (and (org-on-heading-p) (hide-subtree))
8344 (org-end-of-subtree t)))))
8346 (defun org-toggle-tag (tag &optional onoff)
8347 "Toggle the tag TAG for the current line.
8348 If ONOFF is `on' or `off', don't toggle but set to this state."
8349 (unless (org-on-heading-p t) (error "Not on headling"))
8350 (let (res current)
8351 (save-excursion
8352 (beginning-of-line)
8353 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8354 (point-at-eol) t)
8355 (progn
8356 (setq current (match-string 1))
8357 (replace-match ""))
8358 (setq current ""))
8359 (setq current (nreverse (org-split-string current ":")))
8360 (cond
8361 ((eq onoff 'on)
8362 (setq res t)
8363 (or (member tag current) (push tag current)))
8364 ((eq onoff 'off)
8365 (or (not (member tag current)) (setq current (delete tag current))))
8366 (t (if (member tag current)
8367 (setq current (delete tag current))
8368 (setq res t)
8369 (push tag current))))
8370 (end-of-line 1)
8371 (if current
8372 (progn
8373 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8374 (org-set-tags nil t))
8375 (delete-horizontal-space))
8376 (run-hooks 'org-after-tags-change-hook))
8377 res))
8379 (defun org-toggle-archive-tag (&optional arg)
8380 "Toggle the archive tag for the current headline.
8381 With prefix ARG, check all children of current headline and offer tagging
8382 the children that do not contain any open TODO items."
8383 (interactive "P")
8384 (if arg
8385 (org-archive-all-done 'tag)
8386 (let (set)
8387 (save-excursion
8388 (org-back-to-heading t)
8389 (setq set (org-toggle-tag org-archive-tag))
8390 (when set (hide-subtree)))
8391 (and set (beginning-of-line 1))
8392 (message "Subtree %s" (if set "archived" "unarchived")))))
8395 ;;;; Tables
8397 ;;; The table editor
8399 ;; Watch out: Here we are talking about two different kind of tables.
8400 ;; Most of the code is for the tables created with the Org-mode table editor.
8401 ;; Sometimes, we talk about tables created and edited with the table.el
8402 ;; Emacs package. We call the former org-type tables, and the latter
8403 ;; table.el-type tables.
8405 (defun org-before-change-function (beg end)
8406 "Every change indicates that a table might need an update."
8407 (setq org-table-may-need-update t))
8409 (defconst org-table-line-regexp "^[ \t]*|"
8410 "Detects an org-type table line.")
8411 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8412 "Detects an org-type table line.")
8413 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8414 "Detects a table line marked for automatic recalculation.")
8415 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8416 "Detects a table line marked for automatic recalculation.")
8417 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8418 "Detects a table line marked for automatic recalculation.")
8419 (defconst org-table-hline-regexp "^[ \t]*|-"
8420 "Detects an org-type table hline.")
8421 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8422 "Detects a table-type table hline.")
8423 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8424 "Detects an org-type or table-type table.")
8425 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8426 "Searching from within a table (any type) this finds the first line
8427 outside the table.")
8428 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8429 "Searching from within a table (any type) this finds the first line
8430 outside the table.")
8432 (defvar org-table-last-highlighted-reference nil)
8433 (defvar org-table-formula-history nil)
8435 (defvar org-table-column-names nil
8436 "Alist with column names, derived from the `!' line.")
8437 (defvar org-table-column-name-regexp nil
8438 "Regular expression matching the current column names.")
8439 (defvar org-table-local-parameters nil
8440 "Alist with parameter names, derived from the `$' line.")
8441 (defvar org-table-named-field-locations nil
8442 "Alist with locations of named fields.")
8444 (defvar org-table-current-line-types nil
8445 "Table row types, non-nil only for the duration of a comand.")
8446 (defvar org-table-current-begin-line nil
8447 "Table begin line, non-nil only for the duration of a comand.")
8448 (defvar org-table-current-begin-pos nil
8449 "Table begin position, non-nil only for the duration of a comand.")
8450 (defvar org-table-dlines nil
8451 "Vector of data line line numbers in the current table.")
8452 (defvar org-table-hlines nil
8453 "Vector of hline line numbers in the current table.")
8455 (defconst org-table-range-regexp
8456 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8457 ;; 1 2 3 4 5
8458 "Regular expression for matching ranges in formulas.")
8460 (defconst org-table-range-regexp2
8461 (concat
8462 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8463 "\\.\\."
8464 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8465 "Match a range for reference display.")
8467 (defconst org-table-translate-regexp
8468 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8469 "Match a reference that needs translation, for reference display.")
8471 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8473 (defun org-table-create-with-table.el ()
8474 "Use the table.el package to insert a new table.
8475 If there is already a table at point, convert between Org-mode tables
8476 and table.el tables."
8477 (interactive)
8478 (require 'table)
8479 (cond
8480 ((org-at-table.el-p)
8481 (if (y-or-n-p "Convert table to Org-mode table? ")
8482 (org-table-convert)))
8483 ((org-at-table-p)
8484 (if (y-or-n-p "Convert table to table.el table? ")
8485 (org-table-convert)))
8486 (t (call-interactively 'table-insert))))
8488 (defun org-table-create-or-convert-from-region (arg)
8489 "Convert region to table, or create an empty table.
8490 If there is an active region, convert it to a table, using the function
8491 `org-table-convert-region'. See the documentation of that function
8492 to learn how the prefix argument is interpreted to determine the field
8493 separator.
8494 If there is no such region, create an empty table with `org-table-create'."
8495 (interactive "P")
8496 (if (org-region-active-p)
8497 (org-table-convert-region (region-beginning) (region-end) arg)
8498 (org-table-create arg)))
8500 (defun org-table-create (&optional size)
8501 "Query for a size and insert a table skeleton.
8502 SIZE is a string Columns x Rows like for example \"3x2\"."
8503 (interactive "P")
8504 (unless size
8505 (setq size (read-string
8506 (concat "Table size Columns x Rows [e.g. "
8507 org-table-default-size "]: ")
8508 "" nil org-table-default-size)))
8510 (let* ((pos (point))
8511 (indent (make-string (current-column) ?\ ))
8512 (split (org-split-string size " *x *"))
8513 (rows (string-to-number (nth 1 split)))
8514 (columns (string-to-number (car split)))
8515 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8516 "\n")))
8517 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8518 (point-at-bol) (point)))
8519 (beginning-of-line 1)
8520 (newline))
8521 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8522 (dotimes (i rows) (insert line))
8523 (goto-char pos)
8524 (if (> rows 1)
8525 ;; Insert a hline after the first row.
8526 (progn
8527 (end-of-line 1)
8528 (insert "\n|-")
8529 (goto-char pos)))
8530 (org-table-align)))
8532 (defun org-table-convert-region (beg0 end0 &optional separator)
8533 "Convert region to a table.
8534 The region goes from BEG0 to END0, but these borders will be moved
8535 slightly, to make sure a beginning of line in the first line is included.
8537 SEPARATOR specifies the field separator in the lines. It can have the
8538 following values:
8540 '(4) Use the comma as a field separator
8541 '(16) Use a TAB as field separator
8542 integer When a number, use that many spaces as field separator
8543 nil When nil, the command tries to be smart and figure out the
8544 separator in the following way:
8545 - when each line contains a TAB, assume TAB-separated material
8546 - when each line contains a comme, assume CSV material
8547 - else, assume one or more SPACE charcters as separator."
8548 (interactive "rP")
8549 (let* ((beg (min beg0 end0))
8550 (end (max beg0 end0))
8552 (goto-char beg)
8553 (beginning-of-line 1)
8554 (setq beg (move-marker (make-marker) (point)))
8555 (goto-char end)
8556 (if (bolp) (backward-char 1) (end-of-line 1))
8557 (setq end (move-marker (make-marker) (point)))
8558 ;; Get the right field separator
8559 (unless separator
8560 (goto-char beg)
8561 (setq separator
8562 (cond
8563 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8564 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8565 (t 1))))
8566 (setq re (cond
8567 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8568 ((equal separator '(16)) "^\\|\t")
8569 ((integerp separator)
8570 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8571 (t (error "This should not happen"))))
8572 (goto-char beg)
8573 (while (re-search-forward re end t)
8574 (replace-match "| " t t))
8575 (goto-char beg)
8576 (insert " ")
8577 (org-table-align)))
8579 (defun org-table-import (file arg)
8580 "Import FILE as a table.
8581 The file is assumed to be tab-separated. Such files can be produced by most
8582 spreadsheet and database applications. If no tabs (at least one per line)
8583 are found, lines will be split on whitespace into fields."
8584 (interactive "f\nP")
8585 (or (bolp) (newline))
8586 (let ((beg (point))
8587 (pm (point-max)))
8588 (insert-file-contents file)
8589 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8591 (defun org-table-export ()
8592 "Export table as a tab-separated file.
8593 Such a file can be imported into a spreadsheet program like Excel."
8594 (interactive)
8595 (let* ((beg (org-table-begin))
8596 (end (org-table-end))
8597 (table (buffer-substring beg end))
8598 (file (read-file-name "Export table to: "))
8599 buf)
8600 (unless (or (not (file-exists-p file))
8601 (y-or-n-p (format "Overwrite file %s? " file)))
8602 (error "Abort"))
8603 (with-current-buffer (find-file-noselect file)
8604 (setq buf (current-buffer))
8605 (erase-buffer)
8606 (fundamental-mode)
8607 (insert table)
8608 (goto-char (point-min))
8609 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8610 (replace-match "" t t)
8611 (end-of-line 1))
8612 (goto-char (point-min))
8613 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8614 (replace-match "" t t)
8615 (goto-char (min (1+ (point)) (point-max))))
8616 (goto-char (point-min))
8617 (while (re-search-forward "^-[-+]*$" nil t)
8618 (replace-match "")
8619 (if (looking-at "\n")
8620 (delete-char 1)))
8621 (goto-char (point-min))
8622 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8623 (replace-match "\t" t t))
8624 (save-buffer))
8625 (kill-buffer buf)))
8627 (defvar org-table-aligned-begin-marker (make-marker)
8628 "Marker at the beginning of the table last aligned.
8629 Used to check if cursor still is in that table, to minimize realignment.")
8630 (defvar org-table-aligned-end-marker (make-marker)
8631 "Marker at the end of the table last aligned.
8632 Used to check if cursor still is in that table, to minimize realignment.")
8633 (defvar org-table-last-alignment nil
8634 "List of flags for flushright alignment, from the last re-alignment.
8635 This is being used to correctly align a single field after TAB or RET.")
8636 (defvar org-table-last-column-widths nil
8637 "List of max width of fields in each column.
8638 This is being used to correctly align a single field after TAB or RET.")
8639 (defvar org-table-overlay-coordinates nil
8640 "Overlay coordinates after each align of a table.")
8641 (make-variable-buffer-local 'org-table-overlay-coordinates)
8643 (defvar org-last-recalc-line nil)
8644 (defconst org-narrow-column-arrow "=>"
8645 "Used as display property in narrowed table columns.")
8647 (defun org-table-align ()
8648 "Align the table at point by aligning all vertical bars."
8649 (interactive)
8650 (let* (
8651 ;; Limits of table
8652 (beg (org-table-begin))
8653 (end (org-table-end))
8654 ;; Current cursor position
8655 (linepos (org-current-line))
8656 (colpos (org-table-current-column))
8657 (winstart (window-start))
8658 (winstartline (org-current-line (min winstart (1- (point-max)))))
8659 lines (new "") lengths l typenums ty fields maxfields i
8660 column
8661 (indent "") cnt frac
8662 rfmt hfmt
8663 (spaces '(1 . 1))
8664 (sp1 (car spaces))
8665 (sp2 (cdr spaces))
8666 (rfmt1 (concat
8667 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8668 (hfmt1 (concat
8669 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8670 emptystrings links dates emph narrow fmax f1 len c e)
8671 (untabify beg end)
8672 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8673 ;; Check if we have links or dates
8674 (goto-char beg)
8675 (setq links (re-search-forward org-bracket-link-regexp end t))
8676 (goto-char beg)
8677 (setq emph (and org-hide-emphasis-markers
8678 (re-search-forward org-emph-re end t)))
8679 (goto-char beg)
8680 (setq dates (and org-display-custom-times
8681 (re-search-forward org-ts-regexp-both end t)))
8682 ;; Make sure the link properties are right
8683 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8684 ;; Make sure the date properties are right
8685 (when dates (goto-char beg) (while (org-activate-dates end)))
8686 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8688 ;; Check if we are narrowing any columns
8689 (goto-char beg)
8690 (setq narrow (and org-format-transports-properties-p
8691 (re-search-forward "<[0-9]+>" end t)))
8692 ;; Get the rows
8693 (setq lines (org-split-string
8694 (buffer-substring beg end) "\n"))
8695 ;; Store the indentation of the first line
8696 (if (string-match "^ *" (car lines))
8697 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8698 ;; Mark the hlines by setting the corresponding element to nil
8699 ;; At the same time, we remove trailing space.
8700 (setq lines (mapcar (lambda (l)
8701 (if (string-match "^ *|-" l)
8703 (if (string-match "[ \t]+$" l)
8704 (substring l 0 (match-beginning 0))
8705 l)))
8706 lines))
8707 ;; Get the data fields by splitting the lines.
8708 (setq fields (mapcar
8709 (lambda (l)
8710 (org-split-string l " *| *"))
8711 (delq nil (copy-sequence lines))))
8712 ;; How many fields in the longest line?
8713 (condition-case nil
8714 (setq maxfields (apply 'max (mapcar 'length fields)))
8715 (error
8716 (kill-region beg end)
8717 (org-table-create org-table-default-size)
8718 (error "Empty table - created default table")))
8719 ;; A list of empty strings to fill any short rows on output
8720 (setq emptystrings (make-list maxfields ""))
8721 ;; Check for special formatting.
8722 (setq i -1)
8723 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8724 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8725 ;; Check if there is an explicit width specified
8726 (when narrow
8727 (setq c column fmax nil)
8728 (while c
8729 (setq e (pop c))
8730 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8731 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8732 ;; Find fields that are wider than fmax, and shorten them
8733 (when fmax
8734 (loop for xx in column do
8735 (when (and (stringp xx)
8736 (> (org-string-width xx) fmax))
8737 (org-add-props xx nil
8738 'help-echo
8739 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8740 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8741 (unless (> f1 1)
8742 (error "Cannot narrow field starting with wide link \"%s\""
8743 (match-string 0 xx)))
8744 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8745 (add-text-properties (- f1 2) f1
8746 (list 'display org-narrow-column-arrow)
8747 xx)))))
8748 ;; Get the maximum width for each column
8749 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8750 ;; Get the fraction of numbers, to decide about alignment of the column
8751 (setq cnt 0 frac 0.0)
8752 (loop for x in column do
8753 (if (equal x "")
8755 (setq frac ( / (+ (* frac cnt)
8756 (if (string-match org-table-number-regexp x) 1 0))
8757 (setq cnt (1+ cnt))))))
8758 (push (>= frac org-table-number-fraction) typenums))
8759 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8761 ;; Store the alignment of this table, for later editing of single fields
8762 (setq org-table-last-alignment typenums
8763 org-table-last-column-widths lengths)
8765 ;; With invisible characters, `format' does not get the field width right
8766 ;; So we need to make these fields wide by hand.
8767 (when (or links emph)
8768 (loop for i from 0 upto (1- maxfields) do
8769 (setq len (nth i lengths))
8770 (loop for j from 0 upto (1- (length fields)) do
8771 (setq c (nthcdr i (car (nthcdr j fields))))
8772 (if (and (stringp (car c))
8773 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8774 ; (string-match org-bracket-link-regexp (car c))
8775 (< (org-string-width (car c)) len))
8776 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8778 ;; Compute the formats needed for output of the table
8779 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8780 (while (setq l (pop lengths))
8781 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8782 (setq rfmt (concat rfmt (format rfmt1 ty l))
8783 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8784 (setq rfmt (concat rfmt "\n")
8785 hfmt (concat (substring hfmt 0 -1) "|\n"))
8787 (setq new (mapconcat
8788 (lambda (l)
8789 (if l (apply 'format rfmt
8790 (append (pop fields) emptystrings))
8791 hfmt))
8792 lines ""))
8793 ;; Replace the old one
8794 (delete-region beg end)
8795 (move-marker end nil)
8796 (move-marker org-table-aligned-begin-marker (point))
8797 (insert new)
8798 (move-marker org-table-aligned-end-marker (point))
8799 (when (and orgtbl-mode (not (org-mode-p)))
8800 (goto-char org-table-aligned-begin-marker)
8801 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8802 ;; Try to move to the old location
8803 (goto-line winstartline)
8804 (setq winstart (point-at-bol))
8805 (goto-line linepos)
8806 (set-window-start (selected-window) winstart 'noforce)
8807 (org-table-goto-column colpos)
8808 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8809 (setq org-table-may-need-update nil)
8812 (defun org-string-width (s)
8813 "Compute width of string, ignoring invisible characters.
8814 This ignores character with invisibility property `org-link', and also
8815 characters with property `org-cwidth', because these will become invisible
8816 upon the next fontification round."
8817 (let (b l)
8818 (when (or (eq t buffer-invisibility-spec)
8819 (assq 'org-link buffer-invisibility-spec))
8820 (while (setq b (text-property-any 0 (length s)
8821 'invisible 'org-link s))
8822 (setq s (concat (substring s 0 b)
8823 (substring s (or (next-single-property-change
8824 b 'invisible s) (length s)))))))
8825 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8826 (setq s (concat (substring s 0 b)
8827 (substring s (or (next-single-property-change
8828 b 'org-cwidth s) (length s))))))
8829 (setq l (string-width s) b -1)
8830 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8831 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8834 (defun org-table-begin (&optional table-type)
8835 "Find the beginning of the table and return its position.
8836 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8837 (save-excursion
8838 (if (not (re-search-backward
8839 (if table-type org-table-any-border-regexp
8840 org-table-border-regexp)
8841 nil t))
8842 (progn (goto-char (point-min)) (point))
8843 (goto-char (match-beginning 0))
8844 (beginning-of-line 2)
8845 (point))))
8847 (defun org-table-end (&optional table-type)
8848 "Find the end of the table and return its position.
8849 With argument TABLE-TYPE, go to the end of a table.el-type table."
8850 (save-excursion
8851 (if (not (re-search-forward
8852 (if table-type org-table-any-border-regexp
8853 org-table-border-regexp)
8854 nil t))
8855 (goto-char (point-max))
8856 (goto-char (match-beginning 0)))
8857 (point-marker)))
8859 (defun org-table-justify-field-maybe (&optional new)
8860 "Justify the current field, text to left, number to right.
8861 Optional argument NEW may specify text to replace the current field content."
8862 (cond
8863 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8864 ((org-at-table-hline-p))
8865 ((and (not new)
8866 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8867 (current-buffer)))
8868 (< (point) org-table-aligned-begin-marker)
8869 (>= (point) org-table-aligned-end-marker)))
8870 ;; This is not the same table, force a full re-align
8871 (setq org-table-may-need-update t))
8872 (t ;; realign the current field, based on previous full realign
8873 (let* ((pos (point)) s
8874 (col (org-table-current-column))
8875 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8876 l f n o e)
8877 (when (> col 0)
8878 (skip-chars-backward "^|\n")
8879 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8880 (progn
8881 (setq s (match-string 1)
8882 o (match-string 0)
8883 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8884 e (not (= (match-beginning 2) (match-end 2))))
8885 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8886 l (if e "|" (setq org-table-may-need-update t) ""))
8887 n (format f s))
8888 (if new
8889 (if (<= (length new) l) ;; FIXME: length -> str-width?
8890 (setq n (format f new))
8891 (setq n (concat new "|") org-table-may-need-update t)))
8892 (or (equal n o)
8893 (let (org-table-may-need-update)
8894 (replace-match n t t))))
8895 (setq org-table-may-need-update t))
8896 (goto-char pos))))))
8898 (defun org-table-next-field ()
8899 "Go to the next field in the current table, creating new lines as needed.
8900 Before doing so, re-align the table if necessary."
8901 (interactive)
8902 (org-table-maybe-eval-formula)
8903 (org-table-maybe-recalculate-line)
8904 (if (and org-table-automatic-realign
8905 org-table-may-need-update)
8906 (org-table-align))
8907 (let ((end (org-table-end)))
8908 (if (org-at-table-hline-p)
8909 (end-of-line 1))
8910 (condition-case nil
8911 (progn
8912 (re-search-forward "|" end)
8913 (if (looking-at "[ \t]*$")
8914 (re-search-forward "|" end))
8915 (if (and (looking-at "-")
8916 org-table-tab-jumps-over-hlines
8917 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8918 (goto-char (match-beginning 1)))
8919 (if (looking-at "-")
8920 (progn
8921 (beginning-of-line 0)
8922 (org-table-insert-row 'below))
8923 (if (looking-at " ") (forward-char 1))))
8924 (error
8925 (org-table-insert-row 'below)))))
8927 (defun org-table-previous-field ()
8928 "Go to the previous field in the table.
8929 Before doing so, re-align the table if necessary."
8930 (interactive)
8931 (org-table-justify-field-maybe)
8932 (org-table-maybe-recalculate-line)
8933 (if (and org-table-automatic-realign
8934 org-table-may-need-update)
8935 (org-table-align))
8936 (if (org-at-table-hline-p)
8937 (end-of-line 1))
8938 (re-search-backward "|" (org-table-begin))
8939 (re-search-backward "|" (org-table-begin))
8940 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8941 (re-search-backward "|" (org-table-begin)))
8942 (if (looking-at "| ?")
8943 (goto-char (match-end 0))))
8945 (defun org-table-next-row ()
8946 "Go to the next row (same column) in the current table.
8947 Before doing so, re-align the table if necessary."
8948 (interactive)
8949 (org-table-maybe-eval-formula)
8950 (org-table-maybe-recalculate-line)
8951 (if (or (looking-at "[ \t]*$")
8952 (save-excursion (skip-chars-backward " \t") (bolp)))
8953 (newline)
8954 (if (and org-table-automatic-realign
8955 org-table-may-need-update)
8956 (org-table-align))
8957 (let ((col (org-table-current-column)))
8958 (beginning-of-line 2)
8959 (if (or (not (org-at-table-p))
8960 (org-at-table-hline-p))
8961 (progn
8962 (beginning-of-line 0)
8963 (org-table-insert-row 'below)))
8964 (org-table-goto-column col)
8965 (skip-chars-backward "^|\n\r")
8966 (if (looking-at " ") (forward-char 1)))))
8968 (defun org-table-copy-down (n)
8969 "Copy a field down in the current column.
8970 If the field at the cursor is empty, copy into it the content of the nearest
8971 non-empty field above. With argument N, use the Nth non-empty field.
8972 If the current field is not empty, it is copied down to the next row, and
8973 the cursor is moved with it. Therefore, repeating this command causes the
8974 column to be filled row-by-row.
8975 If the variable `org-table-copy-increment' is non-nil and the field is an
8976 integer or a timestamp, it will be incremented while copying. In the case of
8977 a timestamp, if the cursor is on the year, change the year. If it is on the
8978 month or the day, change that. Point will stay on the current date field
8979 in order to easily repeat the interval."
8980 (interactive "p")
8981 (let* ((colpos (org-table-current-column))
8982 (col (current-column))
8983 (field (org-table-get-field))
8984 (non-empty (string-match "[^ \t]" field))
8985 (beg (org-table-begin))
8986 txt)
8987 (org-table-check-inside-data-field)
8988 (if non-empty
8989 (progn
8990 (setq txt (org-trim field))
8991 (org-table-next-row)
8992 (org-table-blank-field))
8993 (save-excursion
8994 (setq txt
8995 (catch 'exit
8996 (while (progn (beginning-of-line 1)
8997 (re-search-backward org-table-dataline-regexp
8998 beg t))
8999 (org-table-goto-column colpos t)
9000 (if (and (looking-at
9001 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9002 (= (setq n (1- n)) 0))
9003 (throw 'exit (match-string 1))))))))
9004 (if txt
9005 (progn
9006 (if (and org-table-copy-increment
9007 (string-match "^[0-9]+$" txt))
9008 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9009 (insert txt)
9010 (move-to-column col)
9011 (if (and org-table-copy-increment (org-at-timestamp-p t))
9012 (org-timestamp-up 1)
9013 (org-table-maybe-recalculate-line))
9014 (org-table-align)
9015 (move-to-column col))
9016 (error "No non-empty field found"))))
9018 (defun org-table-check-inside-data-field ()
9019 "Is point inside a table data field?
9020 I.e. not on a hline or before the first or after the last column?
9021 This actually throws an error, so it aborts the current command."
9022 (if (or (not (org-at-table-p))
9023 (= (org-table-current-column) 0)
9024 (org-at-table-hline-p)
9025 (looking-at "[ \t]*$"))
9026 (error "Not in table data field")))
9028 (defvar org-table-clip nil
9029 "Clipboard for table regions.")
9031 (defun org-table-blank-field ()
9032 "Blank the current table field or active region."
9033 (interactive)
9034 (org-table-check-inside-data-field)
9035 (if (and (interactive-p) (org-region-active-p))
9036 (let (org-table-clip)
9037 (org-table-cut-region (region-beginning) (region-end)))
9038 (skip-chars-backward "^|")
9039 (backward-char 1)
9040 (if (looking-at "|[^|\n]+")
9041 (let* ((pos (match-beginning 0))
9042 (match (match-string 0))
9043 (len (org-string-width match)))
9044 (replace-match (concat "|" (make-string (1- len) ?\ )))
9045 (goto-char (+ 2 pos))
9046 (substring match 1)))))
9048 (defun org-table-get-field (&optional n replace)
9049 "Return the value of the field in column N of current row.
9050 N defaults to current field.
9051 If REPLACE is a string, replace field with this value. The return value
9052 is always the old value."
9053 (and n (org-table-goto-column n))
9054 (skip-chars-backward "^|\n")
9055 (backward-char 1)
9056 (if (looking-at "|[^|\r\n]*")
9057 (let* ((pos (match-beginning 0))
9058 (val (buffer-substring (1+ pos) (match-end 0))))
9059 (if replace
9060 (replace-match (concat "|" replace) t t))
9061 (goto-char (min (point-at-eol) (+ 2 pos)))
9062 val)
9063 (forward-char 1) ""))
9065 (defun org-table-field-info (arg)
9066 "Show info about the current field, and highlight any reference at point."
9067 (interactive "P")
9068 (org-table-get-specials)
9069 (save-excursion
9070 (let* ((pos (point))
9071 (col (org-table-current-column))
9072 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9073 (name (car (rassoc (list (org-current-line) col)
9074 org-table-named-field-locations)))
9075 (eql (org-table-get-stored-formulas))
9076 (dline (org-table-current-dline))
9077 (ref (format "@%d$%d" dline col))
9078 (ref1 (org-table-convert-refs-to-an ref))
9079 (fequation (or (assoc name eql) (assoc ref eql)))
9080 (cequation (assoc (int-to-string col) eql))
9081 (eqn (or fequation cequation)))
9082 (goto-char pos)
9083 (condition-case nil
9084 (org-table-show-reference 'local)
9085 (error nil))
9086 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9087 dline col
9088 (if cname (concat " or $" cname) "")
9089 dline col ref1
9090 (if name (concat " or $" name) "")
9091 ;; FIXME: formula info not correct if special table line
9092 (if eqn
9093 (concat ", formula: "
9094 (org-table-formula-to-user
9095 (concat
9096 (if (string-match "^[$@]"(car eqn)) "" "$")
9097 (car eqn) "=" (cdr eqn))))
9098 "")))))
9100 (defun org-table-current-column ()
9101 "Find out which column we are in.
9102 When called interactively, column is also displayed in echo area."
9103 (interactive)
9104 (if (interactive-p) (org-table-check-inside-data-field))
9105 (save-excursion
9106 (let ((cnt 0) (pos (point)))
9107 (beginning-of-line 1)
9108 (while (search-forward "|" pos t)
9109 (setq cnt (1+ cnt)))
9110 (if (interactive-p) (message "This is table column %d" cnt))
9111 cnt)))
9113 (defun org-table-current-dline ()
9114 "Find out what table data line we are in.
9115 Only datalins count for this."
9116 (interactive)
9117 (if (interactive-p) (org-table-check-inside-data-field))
9118 (save-excursion
9119 (let ((cnt 0) (pos (point)))
9120 (goto-char (org-table-begin))
9121 (while (<= (point) pos)
9122 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9123 (beginning-of-line 2))
9124 (if (interactive-p) (message "This is table line %d" cnt))
9125 cnt)))
9127 (defun org-table-goto-column (n &optional on-delim force)
9128 "Move the cursor to the Nth column in the current table line.
9129 With optional argument ON-DELIM, stop with point before the left delimiter
9130 of the field.
9131 If there are less than N fields, just go to after the last delimiter.
9132 However, when FORCE is non-nil, create new columns if necessary."
9133 (interactive "p")
9134 (let ((pos (point-at-eol)))
9135 (beginning-of-line 1)
9136 (when (> n 0)
9137 (while (and (> (setq n (1- n)) -1)
9138 (or (search-forward "|" pos t)
9139 (and force
9140 (progn (end-of-line 1)
9141 (skip-chars-backward "^|")
9142 (insert " | "))))))
9143 ; (backward-char 2) t)))))
9144 (when (and force (not (looking-at ".*|")))
9145 (save-excursion (end-of-line 1) (insert " | ")))
9146 (if on-delim
9147 (backward-char 1)
9148 (if (looking-at " ") (forward-char 1))))))
9150 (defun org-at-table-p (&optional table-type)
9151 "Return t if the cursor is inside an org-type table.
9152 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9153 (if org-enable-table-editor
9154 (save-excursion
9155 (beginning-of-line 1)
9156 (looking-at (if table-type org-table-any-line-regexp
9157 org-table-line-regexp)))
9158 nil))
9160 (defun org-at-table.el-p ()
9161 "Return t if and only if we are at a table.el table."
9162 (and (org-at-table-p 'any)
9163 (save-excursion
9164 (goto-char (org-table-begin 'any))
9165 (looking-at org-table1-hline-regexp))))
9167 (defun org-table-recognize-table.el ()
9168 "If there is a table.el table nearby, recognize it and move into it."
9169 (if org-table-tab-recognizes-table.el
9170 (if (org-at-table.el-p)
9171 (progn
9172 (beginning-of-line 1)
9173 (if (looking-at org-table-dataline-regexp)
9175 (if (looking-at org-table1-hline-regexp)
9176 (progn
9177 (beginning-of-line 2)
9178 (if (looking-at org-table-any-border-regexp)
9179 (beginning-of-line -1)))))
9180 (if (re-search-forward "|" (org-table-end t) t)
9181 (progn
9182 (require 'table)
9183 (if (table--at-cell-p (point))
9185 (message "recognizing table.el table...")
9186 (table-recognize-table)
9187 (message "recognizing table.el table...done")))
9188 (error "This should not happen..."))
9190 nil)
9191 nil))
9193 (defun org-at-table-hline-p ()
9194 "Return t if the cursor is inside a hline in a table."
9195 (if org-enable-table-editor
9196 (save-excursion
9197 (beginning-of-line 1)
9198 (looking-at org-table-hline-regexp))
9199 nil))
9201 (defun org-table-insert-column ()
9202 "Insert a new column into the table."
9203 (interactive)
9204 (if (not (org-at-table-p))
9205 (error "Not at a table"))
9206 (org-table-find-dataline)
9207 (let* ((col (max 1 (org-table-current-column)))
9208 (beg (org-table-begin))
9209 (end (org-table-end))
9210 ;; Current cursor position
9211 (linepos (org-current-line))
9212 (colpos col))
9213 (goto-char beg)
9214 (while (< (point) end)
9215 (if (org-at-table-hline-p)
9217 (org-table-goto-column col t)
9218 (insert "| "))
9219 (beginning-of-line 2))
9220 (move-marker end nil)
9221 (goto-line linepos)
9222 (org-table-goto-column colpos)
9223 (org-table-align)
9224 (org-table-fix-formulas "$" nil (1- col) 1)))
9226 (defun org-table-find-dataline ()
9227 "Find a dataline in the current table, which is needed for column commands."
9228 (if (and (org-at-table-p)
9229 (not (org-at-table-hline-p)))
9231 (let ((col (current-column))
9232 (end (org-table-end)))
9233 (move-to-column col)
9234 (while (and (< (point) end)
9235 (or (not (= (current-column) col))
9236 (org-at-table-hline-p)))
9237 (beginning-of-line 2)
9238 (move-to-column col))
9239 (if (and (org-at-table-p)
9240 (not (org-at-table-hline-p)))
9242 (error
9243 "Please position cursor in a data line for column operations")))))
9245 (defun org-table-delete-column ()
9246 "Delete a column from the table."
9247 (interactive)
9248 (if (not (org-at-table-p))
9249 (error "Not at a table"))
9250 (org-table-find-dataline)
9251 (org-table-check-inside-data-field)
9252 (let* ((col (org-table-current-column))
9253 (beg (org-table-begin))
9254 (end (org-table-end))
9255 ;; Current cursor position
9256 (linepos (org-current-line))
9257 (colpos col))
9258 (goto-char beg)
9259 (while (< (point) end)
9260 (if (org-at-table-hline-p)
9262 (org-table-goto-column col t)
9263 (and (looking-at "|[^|\n]+|")
9264 (replace-match "|")))
9265 (beginning-of-line 2))
9266 (move-marker end nil)
9267 (goto-line linepos)
9268 (org-table-goto-column colpos)
9269 (org-table-align)
9270 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9271 col -1 col)))
9273 (defun org-table-move-column-right ()
9274 "Move column to the right."
9275 (interactive)
9276 (org-table-move-column nil))
9277 (defun org-table-move-column-left ()
9278 "Move column to the left."
9279 (interactive)
9280 (org-table-move-column 'left))
9282 (defun org-table-move-column (&optional left)
9283 "Move the current column to the right. With arg LEFT, move to the left."
9284 (interactive "P")
9285 (if (not (org-at-table-p))
9286 (error "Not at a table"))
9287 (org-table-find-dataline)
9288 (org-table-check-inside-data-field)
9289 (let* ((col (org-table-current-column))
9290 (col1 (if left (1- col) col))
9291 (beg (org-table-begin))
9292 (end (org-table-end))
9293 ;; Current cursor position
9294 (linepos (org-current-line))
9295 (colpos (if left (1- col) (1+ col))))
9296 (if (and left (= col 1))
9297 (error "Cannot move column further left"))
9298 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9299 (error "Cannot move column further right"))
9300 (goto-char beg)
9301 (while (< (point) end)
9302 (if (org-at-table-hline-p)
9304 (org-table-goto-column col1 t)
9305 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9306 (replace-match "|\\2|\\1|")))
9307 (beginning-of-line 2))
9308 (move-marker end nil)
9309 (goto-line linepos)
9310 (org-table-goto-column colpos)
9311 (org-table-align)
9312 (org-table-fix-formulas
9313 "$" (list (cons (number-to-string col) (number-to-string colpos))
9314 (cons (number-to-string colpos) (number-to-string col))))))
9316 (defun org-table-move-row-down ()
9317 "Move table row down."
9318 (interactive)
9319 (org-table-move-row nil))
9320 (defun org-table-move-row-up ()
9321 "Move table row up."
9322 (interactive)
9323 (org-table-move-row 'up))
9325 (defun org-table-move-row (&optional up)
9326 "Move the current table line down. With arg UP, move it up."
9327 (interactive "P")
9328 (let* ((col (current-column))
9329 (pos (point))
9330 (hline1p (save-excursion (beginning-of-line 1)
9331 (looking-at org-table-hline-regexp)))
9332 (dline1 (org-table-current-dline))
9333 (dline2 (+ dline1 (if up -1 1)))
9334 (tonew (if up 0 2))
9335 txt hline2p)
9336 (beginning-of-line tonew)
9337 (unless (org-at-table-p)
9338 (goto-char pos)
9339 (error "Cannot move row further"))
9340 (setq hline2p (looking-at org-table-hline-regexp))
9341 (goto-char pos)
9342 (beginning-of-line 1)
9343 (setq pos (point))
9344 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9345 (delete-region (point) (1+ (point-at-eol)))
9346 (beginning-of-line tonew)
9347 (insert txt)
9348 (beginning-of-line 0)
9349 (move-to-column col)
9350 (unless (or hline1p hline2p)
9351 (org-table-fix-formulas
9352 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9353 (cons (number-to-string dline2) (number-to-string dline1)))))))
9355 (defun org-table-insert-row (&optional arg)
9356 "Insert a new row above the current line into the table.
9357 With prefix ARG, insert below the current line."
9358 (interactive "P")
9359 (if (not (org-at-table-p))
9360 (error "Not at a table"))
9361 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9362 (new (org-table-clean-line line)))
9363 ;; Fix the first field if necessary
9364 (if (string-match "^[ \t]*| *[#$] *|" line)
9365 (setq new (replace-match (match-string 0 line) t t new)))
9366 (beginning-of-line (if arg 2 1))
9367 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9368 (beginning-of-line 0)
9369 (re-search-forward "| ?" (point-at-eol) t)
9370 (and (or org-table-may-need-update org-table-overlay-coordinates)
9371 (org-table-align))
9372 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9374 (defun org-table-insert-hline (&optional above)
9375 "Insert a horizontal-line below the current line into the table.
9376 With prefix ABOVE, insert above the current line."
9377 (interactive "P")
9378 (if (not (org-at-table-p))
9379 (error "Not at a table"))
9380 (let ((line (org-table-clean-line
9381 (buffer-substring (point-at-bol) (point-at-eol))))
9382 (col (current-column)))
9383 (while (string-match "|\\( +\\)|" line)
9384 (setq line (replace-match
9385 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9386 ?-) "|") t t line)))
9387 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9388 (beginning-of-line (if above 1 2))
9389 (insert line "\n")
9390 (beginning-of-line (if above 1 -1))
9391 (move-to-column col)
9392 (and org-table-overlay-coordinates (org-table-align))))
9394 (defun org-table-hline-and-move (&optional same-column)
9395 "Insert a hline and move to the row below that line."
9396 (interactive "P")
9397 (let ((col (org-table-current-column)))
9398 (org-table-maybe-eval-formula)
9399 (org-table-maybe-recalculate-line)
9400 (org-table-insert-hline)
9401 (end-of-line 2)
9402 (if (looking-at "\n[ \t]*|-")
9403 (progn (insert "\n|") (org-table-align))
9404 (org-table-next-field))
9405 (if same-column (org-table-goto-column col))))
9407 (defun org-table-clean-line (s)
9408 "Convert a table line S into a string with only \"|\" and space.
9409 In particular, this does handle wide and invisible characters."
9410 (if (string-match "^[ \t]*|-" s)
9411 ;; It's a hline, just map the characters
9412 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9413 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9414 (setq s (replace-match
9415 (concat "|" (make-string (org-string-width (match-string 1 s))
9416 ?\ ) "|")
9417 t t s)))
9420 (defun org-table-kill-row ()
9421 "Delete the current row or horizontal line from the table."
9422 (interactive)
9423 (if (not (org-at-table-p))
9424 (error "Not at a table"))
9425 (let ((col (current-column))
9426 (dline (org-table-current-dline)))
9427 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9428 (if (not (org-at-table-p)) (beginning-of-line 0))
9429 (move-to-column col)
9430 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9431 dline -1 dline)))
9433 (defun org-table-sort-lines (with-case &optional sorting-type)
9434 "Sort table lines according to the column at point.
9436 The position of point indicates the column to be used for
9437 sorting, and the range of lines is the range between the nearest
9438 horizontal separator lines, or the entire table of no such lines
9439 exist. If point is before the first column, you will be prompted
9440 for the sorting column. If there is an active region, the mark
9441 specifies the first line and the sorting column, while point
9442 should be in the last line to be included into the sorting.
9444 The command then prompts for the sorting type which can be
9445 alphabetically, numerically, or by time (as given in a time stamp
9446 in the field). Sorting in reverse order is also possible.
9448 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9450 If SORTING-TYPE is specified when this function is called from a Lisp
9451 program, no prompting will take place. SORTING-TYPE must be a character,
9452 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9453 should be done in reverse order."
9454 (interactive "P")
9455 (let* ((thisline (org-current-line))
9456 (thiscol (org-table-current-column))
9457 beg end bcol ecol tend tbeg column lns pos)
9458 (when (equal thiscol 0)
9459 (if (interactive-p)
9460 (setq thiscol
9461 (string-to-number
9462 (read-string "Use column N for sorting: ")))
9463 (setq thiscol 1))
9464 (org-table-goto-column thiscol))
9465 (org-table-check-inside-data-field)
9466 (if (org-region-active-p)
9467 (progn
9468 (setq beg (region-beginning) end (region-end))
9469 (goto-char beg)
9470 (setq column (org-table-current-column)
9471 beg (point-at-bol))
9472 (goto-char end)
9473 (setq end (point-at-bol 2)))
9474 (setq column (org-table-current-column)
9475 pos (point)
9476 tbeg (org-table-begin)
9477 tend (org-table-end))
9478 (if (re-search-backward org-table-hline-regexp tbeg t)
9479 (setq beg (point-at-bol 2))
9480 (goto-char tbeg)
9481 (setq beg (point-at-bol 1)))
9482 (goto-char pos)
9483 (if (re-search-forward org-table-hline-regexp tend t)
9484 (setq end (point-at-bol 1))
9485 (goto-char tend)
9486 (setq end (point-at-bol))))
9487 (setq beg (move-marker (make-marker) beg)
9488 end (move-marker (make-marker) end))
9489 (untabify beg end)
9490 (goto-char beg)
9491 (org-table-goto-column column)
9492 (skip-chars-backward "^|")
9493 (setq bcol (current-column))
9494 (org-table-goto-column (1+ column))
9495 (skip-chars-backward "^|")
9496 (setq ecol (1- (current-column)))
9497 (org-table-goto-column column)
9498 (setq lns (mapcar (lambda(x) (cons
9499 (org-sort-remove-invisible
9500 (nth (1- column)
9501 (org-split-string x "[ \t]*|[ \t]*")))
9503 (org-split-string (buffer-substring beg end) "\n")))
9504 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9505 (delete-region beg end)
9506 (move-marker beg nil)
9507 (move-marker end nil)
9508 (insert (mapconcat 'cdr lns "\n") "\n")
9509 (goto-line thisline)
9510 (org-table-goto-column thiscol)
9511 (message "%d lines sorted, based on column %d" (length lns) column)))
9513 ;; FIXME: maybe we will not need this? Table sorting is broken....
9514 (defun org-sort-remove-invisible (s)
9515 (remove-text-properties 0 (length s) org-rm-props s)
9516 (while (string-match org-bracket-link-regexp s)
9517 (setq s (replace-match (if (match-end 2)
9518 (match-string 3 s)
9519 (match-string 1 s)) t t s)))
9522 (defun org-table-cut-region (beg end)
9523 "Copy region in table to the clipboard and blank all relevant fields."
9524 (interactive "r")
9525 (org-table-copy-region beg end 'cut))
9527 (defun org-table-copy-region (beg end &optional cut)
9528 "Copy rectangular region in table to clipboard.
9529 A special clipboard is used which can only be accessed
9530 with `org-table-paste-rectangle'."
9531 (interactive "rP")
9532 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9533 region cols
9534 (rpl (if cut " " nil)))
9535 (goto-char beg)
9536 (org-table-check-inside-data-field)
9537 (setq l01 (org-current-line)
9538 c01 (org-table-current-column))
9539 (goto-char end)
9540 (org-table-check-inside-data-field)
9541 (setq l02 (org-current-line)
9542 c02 (org-table-current-column))
9543 (setq l1 (min l01 l02) l2 (max l01 l02)
9544 c1 (min c01 c02) c2 (max c01 c02))
9545 (catch 'exit
9546 (while t
9547 (catch 'nextline
9548 (if (> l1 l2) (throw 'exit t))
9549 (goto-line l1)
9550 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9551 (setq cols nil ic1 c1 ic2 c2)
9552 (while (< ic1 (1+ ic2))
9553 (push (org-table-get-field ic1 rpl) cols)
9554 (setq ic1 (1+ ic1)))
9555 (push (nreverse cols) region)
9556 (setq l1 (1+ l1)))))
9557 (setq org-table-clip (nreverse region))
9558 (if cut (org-table-align))
9559 org-table-clip))
9561 (defun org-table-paste-rectangle ()
9562 "Paste a rectangular region into a table.
9563 The upper right corner ends up in the current field. All involved fields
9564 will be overwritten. If the rectangle does not fit into the present table,
9565 the table is enlarged as needed. The process ignores horizontal separator
9566 lines."
9567 (interactive)
9568 (unless (and org-table-clip (listp org-table-clip))
9569 (error "First cut/copy a region to paste!"))
9570 (org-table-check-inside-data-field)
9571 (let* ((clip org-table-clip)
9572 (line (org-current-line))
9573 (col (org-table-current-column))
9574 (org-enable-table-editor t)
9575 (org-table-automatic-realign nil)
9576 c cols field)
9577 (while (setq cols (pop clip))
9578 (while (org-at-table-hline-p) (beginning-of-line 2))
9579 (if (not (org-at-table-p))
9580 (progn (end-of-line 0) (org-table-next-field)))
9581 (setq c col)
9582 (while (setq field (pop cols))
9583 (org-table-goto-column c nil 'force)
9584 (org-table-get-field nil field)
9585 (setq c (1+ c)))
9586 (beginning-of-line 2))
9587 (goto-line line)
9588 (org-table-goto-column col)
9589 (org-table-align)))
9591 (defun org-table-convert ()
9592 "Convert from `org-mode' table to table.el and back.
9593 Obviously, this only works within limits. When an Org-mode table is
9594 converted to table.el, all horizontal separator lines get lost, because
9595 table.el uses these as cell boundaries and has no notion of horizontal lines.
9596 A table.el table can be converted to an Org-mode table only if it does not
9597 do row or column spanning. Multiline cells will become multiple cells.
9598 Beware, Org-mode does not test if the table can be successfully converted - it
9599 blindly applies a recipe that works for simple tables."
9600 (interactive)
9601 (require 'table)
9602 (if (org-at-table.el-p)
9603 ;; convert to Org-mode table
9604 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9605 (end (move-marker (make-marker) (org-table-end t))))
9606 (table-unrecognize-region beg end)
9607 (goto-char beg)
9608 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9609 (replace-match ""))
9610 (goto-char beg))
9611 (if (org-at-table-p)
9612 ;; convert to table.el table
9613 (let ((beg (move-marker (make-marker) (org-table-begin)))
9614 (end (move-marker (make-marker) (org-table-end))))
9615 ;; first, get rid of all horizontal lines
9616 (goto-char beg)
9617 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9618 (replace-match ""))
9619 ;; insert a hline before first
9620 (goto-char beg)
9621 (org-table-insert-hline 'above)
9622 (beginning-of-line -1)
9623 ;; insert a hline after each line
9624 (while (progn (beginning-of-line 3) (< (point) end))
9625 (org-table-insert-hline))
9626 (goto-char beg)
9627 (setq end (move-marker end (org-table-end)))
9628 ;; replace "+" at beginning and ending of hlines
9629 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9630 (replace-match "\\1+-"))
9631 (goto-char beg)
9632 (while (re-search-forward "-|[ \t]*$" end t)
9633 (replace-match "-+"))
9634 (goto-char beg)))))
9636 (defun org-table-wrap-region (arg)
9637 "Wrap several fields in a column like a paragraph.
9638 This is useful if you'd like to spread the contents of a field over several
9639 lines, in order to keep the table compact.
9641 If there is an active region, and both point and mark are in the same column,
9642 the text in the column is wrapped to minimum width for the given number of
9643 lines. Generally, this makes the table more compact. A prefix ARG may be
9644 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9645 formats the selected text to two lines. If the region was longer than two
9646 lines, the remaining lines remain empty. A negative prefix argument reduces
9647 the current number of lines by that amount. The wrapped text is pasted back
9648 into the table. If you formatted it to more lines than it was before, fields
9649 further down in the table get overwritten - so you might need to make space in
9650 the table first.
9652 If there is no region, the current field is split at the cursor position and
9653 the text fragment to the right of the cursor is prepended to the field one
9654 line down.
9656 If there is no region, but you specify a prefix ARG, the current field gets
9657 blank, and the content is appended to the field above."
9658 (interactive "P")
9659 (org-table-check-inside-data-field)
9660 (if (org-region-active-p)
9661 ;; There is a region: fill as a paragraph
9662 (let* ((beg (region-beginning))
9663 (cline (save-excursion (goto-char beg) (org-current-line)))
9664 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9665 nlines)
9666 (org-table-cut-region (region-beginning) (region-end))
9667 (if (> (length (car org-table-clip)) 1)
9668 (error "Region must be limited to single column"))
9669 (setq nlines (if arg
9670 (if (< arg 1)
9671 (+ (length org-table-clip) arg)
9672 arg)
9673 (length org-table-clip)))
9674 (setq org-table-clip
9675 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9676 nil nlines)))
9677 (goto-line cline)
9678 (org-table-goto-column ccol)
9679 (org-table-paste-rectangle))
9680 ;; No region, split the current field at point
9681 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9682 (skip-chars-forward "^\r\n|"))
9683 (if arg
9684 ;; combine with field above
9685 (let ((s (org-table-blank-field))
9686 (col (org-table-current-column)))
9687 (beginning-of-line 0)
9688 (while (org-at-table-hline-p) (beginning-of-line 0))
9689 (org-table-goto-column col)
9690 (skip-chars-forward "^|")
9691 (skip-chars-backward " ")
9692 (insert " " (org-trim s))
9693 (org-table-align))
9694 ;; split field
9695 (if (looking-at "\\([^|]+\\)+|")
9696 (let ((s (match-string 1)))
9697 (replace-match " |")
9698 (goto-char (match-beginning 0))
9699 (org-table-next-row)
9700 (insert (org-trim s) " ")
9701 (org-table-align))
9702 (org-table-next-row)))))
9704 (defvar org-field-marker nil)
9706 (defun org-table-edit-field (arg)
9707 "Edit table field in a different window.
9708 This is mainly useful for fields that contain hidden parts.
9709 When called with a \\[universal-argument] prefix, just make the full field visible so that
9710 it can be edited in place."
9711 (interactive "P")
9712 (if arg
9713 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9714 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9715 (remove-text-properties b e '(org-cwidth t invisible t
9716 display t intangible t))
9717 (if (and (boundp 'font-lock-mode) font-lock-mode)
9718 (font-lock-fontify-block)))
9719 (let ((pos (move-marker (make-marker) (point)))
9720 (field (org-table-get-field))
9721 (cw (current-window-configuration))
9723 (org-switch-to-buffer-other-window "*Org tmp*")
9724 (erase-buffer)
9725 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9726 (let ((org-inhibit-startup t)) (org-mode))
9727 (goto-char (setq p (point-max)))
9728 (insert (org-trim field))
9729 (remove-text-properties p (point-max)
9730 '(invisible t org-cwidth t display t
9731 intangible t))
9732 (goto-char p)
9733 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9734 (org-set-local 'org-window-configuration cw)
9735 (org-set-local 'org-field-marker pos)
9736 (message "Edit and finish with C-c C-c"))))
9738 (defun org-table-finish-edit-field ()
9739 "Finish editing a table data field.
9740 Remove all newline characters, insert the result into the table, realign
9741 the table and kill the editing buffer."
9742 (let ((pos org-field-marker)
9743 (cw org-window-configuration)
9744 (cb (current-buffer))
9745 text)
9746 (goto-char (point-min))
9747 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9748 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9749 (replace-match " "))
9750 (setq text (org-trim (buffer-string)))
9751 (set-window-configuration cw)
9752 (kill-buffer cb)
9753 (select-window (get-buffer-window (marker-buffer pos)))
9754 (goto-char pos)
9755 (move-marker pos nil)
9756 (org-table-check-inside-data-field)
9757 (org-table-get-field nil text)
9758 (org-table-align)
9759 (message "New field value inserted")))
9761 (defun org-trim (s)
9762 "Remove whitespace at beginning and end of string."
9763 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9764 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9767 (defun org-wrap (string &optional width lines)
9768 "Wrap string to either a number of lines, or a width in characters.
9769 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9770 that costs. If there is a word longer than WIDTH, the text is actually
9771 wrapped to the length of that word.
9772 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9773 many lines, whatever width that takes.
9774 The return value is a list of lines, without newlines at the end."
9775 (let* ((words (org-split-string string "[ \t\n]+"))
9776 (maxword (apply 'max (mapcar 'org-string-width words)))
9777 w ll)
9778 (cond (width
9779 (org-do-wrap words (max maxword width)))
9780 (lines
9781 (setq w maxword)
9782 (setq ll (org-do-wrap words maxword))
9783 (if (<= (length ll) lines)
9785 (setq ll words)
9786 (while (> (length ll) lines)
9787 (setq w (1+ w))
9788 (setq ll (org-do-wrap words w)))
9789 ll))
9790 (t (error "Cannot wrap this")))))
9793 (defun org-do-wrap (words width)
9794 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9795 (let (lines line)
9796 (while words
9797 (setq line (pop words))
9798 (while (and words (< (+ (length line) (length (car words))) width))
9799 (setq line (concat line " " (pop words))))
9800 (setq lines (push line lines)))
9801 (nreverse lines)))
9803 (defun org-split-string (string &optional separators)
9804 "Splits STRING into substrings at SEPARATORS.
9805 No empty strings are returned if there are matches at the beginning
9806 and end of string."
9807 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9808 (start 0)
9809 notfirst
9810 (list nil))
9811 (while (and (string-match rexp string
9812 (if (and notfirst
9813 (= start (match-beginning 0))
9814 (< start (length string)))
9815 (1+ start) start))
9816 (< (match-beginning 0) (length string)))
9817 (setq notfirst t)
9818 (or (eq (match-beginning 0) 0)
9819 (and (eq (match-beginning 0) (match-end 0))
9820 (eq (match-beginning 0) start))
9821 (setq list
9822 (cons (substring string start (match-beginning 0))
9823 list)))
9824 (setq start (match-end 0)))
9825 (or (eq start (length string))
9826 (setq list
9827 (cons (substring string start)
9828 list)))
9829 (nreverse list)))
9831 (defun org-table-map-tables (function)
9832 "Apply FUNCTION to the start of all tables in the buffer."
9833 (save-excursion
9834 (save-restriction
9835 (widen)
9836 (goto-char (point-min))
9837 (while (re-search-forward org-table-any-line-regexp nil t)
9838 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9839 (beginning-of-line 1)
9840 (if (looking-at org-table-line-regexp)
9841 (save-excursion (funcall function)))
9842 (re-search-forward org-table-any-border-regexp nil 1))))
9843 (message "Mapping tables: done"))
9845 (defvar org-timecnt) ; dynamically scoped parameter
9847 (defun org-table-sum (&optional beg end nlast)
9848 "Sum numbers in region of current table column.
9849 The result will be displayed in the echo area, and will be available
9850 as kill to be inserted with \\[yank].
9852 If there is an active region, it is interpreted as a rectangle and all
9853 numbers in that rectangle will be summed. If there is no active
9854 region and point is located in a table column, sum all numbers in that
9855 column.
9857 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9858 numbers are assumed to be times as well (in decimal hours) and the
9859 numbers are added as such.
9861 If NLAST is a number, only the NLAST fields will actually be summed."
9862 (interactive)
9863 (save-excursion
9864 (let (col (org-timecnt 0) diff h m s org-table-clip)
9865 (cond
9866 ((and beg end)) ; beg and end given explicitly
9867 ((org-region-active-p)
9868 (setq beg (region-beginning) end (region-end)))
9870 (setq col (org-table-current-column))
9871 (goto-char (org-table-begin))
9872 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9873 (error "No table data"))
9874 (org-table-goto-column col)
9875 (setq beg (point))
9876 (goto-char (org-table-end))
9877 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9878 (error "No table data"))
9879 (org-table-goto-column col)
9880 (setq end (point))))
9881 (let* ((items (apply 'append (org-table-copy-region beg end)))
9882 (items1 (cond ((not nlast) items)
9883 ((>= nlast (length items)) items)
9884 (t (setq items (reverse items))
9885 (setcdr (nthcdr (1- nlast) items) nil)
9886 (nreverse items))))
9887 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9888 items1)))
9889 (res (apply '+ numbers))
9890 (sres (if (= org-timecnt 0)
9891 (format "%g" res)
9892 (setq diff (* 3600 res)
9893 h (floor (/ diff 3600)) diff (mod diff 3600)
9894 m (floor (/ diff 60)) diff (mod diff 60)
9895 s diff)
9896 (format "%d:%02d:%02d" h m s))))
9897 (kill-new sres)
9898 (if (interactive-p)
9899 (message "%s"
9900 (substitute-command-keys
9901 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9902 (length numbers) sres))))
9903 sres))))
9905 (defun org-table-get-number-for-summing (s)
9906 (let (n)
9907 (if (string-match "^ *|? *" s)
9908 (setq s (replace-match "" nil nil s)))
9909 (if (string-match " *|? *$" s)
9910 (setq s (replace-match "" nil nil s)))
9911 (setq n (string-to-number s))
9912 (cond
9913 ((and (string-match "0" s)
9914 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9915 ((string-match "\\`[ \t]+\\'" s) nil)
9916 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9917 (let ((h (string-to-number (or (match-string 1 s) "0")))
9918 (m (string-to-number (or (match-string 2 s) "0")))
9919 (s (string-to-number (or (match-string 4 s) "0"))))
9920 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9921 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9922 ((equal n 0) nil)
9923 (t n))))
9925 (defun org-table-current-field-formula (&optional key noerror)
9926 "Return the formula active for the current field.
9927 Assumes that specials are in place.
9928 If KEY is given, return the key to this formula.
9929 Otherwise return the formula preceeded with \"=\" or \":=\"."
9930 (let* ((name (car (rassoc (list (org-current-line)
9931 (org-table-current-column))
9932 org-table-named-field-locations)))
9933 (col (org-table-current-column))
9934 (scol (int-to-string col))
9935 (ref (format "@%d$%d" (org-table-current-dline) col))
9936 (stored-list (org-table-get-stored-formulas noerror))
9937 (ass (or (assoc name stored-list)
9938 (assoc ref stored-list)
9939 (assoc scol stored-list))))
9940 (if key
9941 (car ass)
9942 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9943 (cdr ass))))))
9945 (defun org-table-get-formula (&optional equation named)
9946 "Read a formula from the minibuffer, offer stored formula as default.
9947 When NAMED is non-nil, look for a named equation."
9948 (let* ((stored-list (org-table-get-stored-formulas))
9949 (name (car (rassoc (list (org-current-line)
9950 (org-table-current-column))
9951 org-table-named-field-locations)))
9952 (ref (format "@%d$%d" (org-table-current-dline)
9953 (org-table-current-column)))
9954 (refass (assoc ref stored-list))
9955 (scol (if named
9956 (if name name ref)
9957 (int-to-string (org-table-current-column))))
9958 (dummy (and (or name refass) (not named)
9959 (not (y-or-n-p "Replace field formula with column formula? " ))
9960 (error "Abort")))
9961 (name (or name ref))
9962 (org-table-may-need-update nil)
9963 (stored (cdr (assoc scol stored-list)))
9964 (eq (cond
9965 ((and stored equation (string-match "^ *=? *$" equation))
9966 stored)
9967 ((stringp equation)
9968 equation)
9969 (t (org-table-formula-from-user
9970 (read-string
9971 (org-table-formula-to-user
9972 (format "%s formula %s%s="
9973 (if named "Field" "Column")
9974 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9975 scol))
9976 (if stored (org-table-formula-to-user stored) "")
9977 'org-table-formula-history
9978 )))))
9979 mustsave)
9980 (when (not (string-match "\\S-" eq))
9981 ;; remove formula
9982 (setq stored-list (delq (assoc scol stored-list) stored-list))
9983 (org-table-store-formulas stored-list)
9984 (error "Formula removed"))
9985 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9986 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9987 (if (and name (not named))
9988 ;; We set the column equation, delete the named one.
9989 (setq stored-list (delq (assoc name stored-list) stored-list)
9990 mustsave t))
9991 (if stored
9992 (setcdr (assoc scol stored-list) eq)
9993 (setq stored-list (cons (cons scol eq) stored-list)))
9994 (if (or mustsave (not (equal stored eq)))
9995 (org-table-store-formulas stored-list))
9996 eq))
9998 (defun org-table-store-formulas (alist)
9999 "Store the list of formulas below the current table."
10000 (setq alist (sort alist 'org-table-formula-less-p))
10001 (save-excursion
10002 (goto-char (org-table-end))
10003 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
10004 (progn
10005 ;; don't overwrite TBLFM, we might use text properties to store stuff
10006 (goto-char (match-beginning 2))
10007 (delete-region (match-beginning 2) (match-end 0)))
10008 (insert "#+TBLFM:"))
10009 (insert " "
10010 (mapconcat (lambda (x)
10011 (concat
10012 (if (equal (string-to-char (car x)) ?@) "" "$")
10013 (car x) "=" (cdr x)))
10014 alist "::")
10015 "\n")))
10017 (defsubst org-table-formula-make-cmp-string (a)
10018 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10019 (concat
10020 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10021 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10022 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10024 (defun org-table-formula-less-p (a b)
10025 "Compare two formulas for sorting."
10026 (let ((as (org-table-formula-make-cmp-string (car a)))
10027 (bs (org-table-formula-make-cmp-string (car b))))
10028 (and as bs (string< as bs))))
10030 (defun org-table-get-stored-formulas (&optional noerror)
10031 "Return an alist with the stored formulas directly after current table."
10032 (interactive)
10033 (let (scol eq eq-alist strings string seen)
10034 (save-excursion
10035 (goto-char (org-table-end))
10036 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10037 (setq strings (org-split-string (match-string 2) " *:: *"))
10038 (while (setq string (pop strings))
10039 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10040 (setq scol (if (match-end 2)
10041 (match-string 2 string)
10042 (match-string 1 string))
10043 eq (match-string 3 string)
10044 eq-alist (cons (cons scol eq) eq-alist))
10045 (if (member scol seen)
10046 (if noerror
10047 (progn
10048 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10049 (ding)
10050 (sit-for 2))
10051 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10052 (push scol seen))))))
10053 (nreverse eq-alist)))
10055 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10056 "Modify the equations after the table structure has been edited.
10057 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10058 For all numbers larger than LIMIT, shift them by DELTA."
10059 (save-excursion
10060 (goto-char (org-table-end))
10061 (when (looking-at "#\\+TBLFM:")
10062 (let ((re (concat key "\\([0-9]+\\)"))
10063 (re2
10064 (when remove
10065 (if (equal key "$")
10066 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10067 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10068 s n a)
10069 (when remove
10070 (while (re-search-forward re2 (point-at-eol) t)
10071 (replace-match "")))
10072 (while (re-search-forward re (point-at-eol) t)
10073 (setq s (match-string 1) n (string-to-number s))
10074 (cond
10075 ((setq a (assoc s replace))
10076 (replace-match (concat key (cdr a)) t t))
10077 ((and limit (> n limit))
10078 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10080 (defun org-table-get-specials ()
10081 "Get the column names and local parameters for this table."
10082 (save-excursion
10083 (let ((beg (org-table-begin)) (end (org-table-end))
10084 names name fields fields1 field cnt
10085 c v l line col types dlines hlines)
10086 (setq org-table-column-names nil
10087 org-table-local-parameters nil
10088 org-table-named-field-locations nil
10089 org-table-current-begin-line nil
10090 org-table-current-begin-pos nil
10091 org-table-current-line-types nil)
10092 (goto-char beg)
10093 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10094 (setq names (org-split-string (match-string 1) " *| *")
10095 cnt 1)
10096 (while (setq name (pop names))
10097 (setq cnt (1+ cnt))
10098 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10099 (push (cons name (int-to-string cnt)) org-table-column-names))))
10100 (setq org-table-column-names (nreverse org-table-column-names))
10101 (setq org-table-column-name-regexp
10102 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10103 (goto-char beg)
10104 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10105 (setq fields (org-split-string (match-string 1) " *| *"))
10106 (while (setq field (pop fields))
10107 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10108 (push (cons (match-string 1 field) (match-string 2 field))
10109 org-table-local-parameters))))
10110 (goto-char beg)
10111 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10112 (setq c (match-string 1)
10113 fields (org-split-string (match-string 2) " *| *"))
10114 (save-excursion
10115 (beginning-of-line (if (equal c "_") 2 0))
10116 (setq line (org-current-line) col 1)
10117 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10118 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10119 (while (and fields1 (setq field (pop fields)))
10120 (setq v (pop fields1) col (1+ col))
10121 (when (and (stringp field) (stringp v)
10122 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10123 (push (cons field v) org-table-local-parameters)
10124 (push (list field line col) org-table-named-field-locations))))
10125 ;; Analyse the line types
10126 (goto-char beg)
10127 (setq org-table-current-begin-line (org-current-line)
10128 org-table-current-begin-pos (point)
10129 l org-table-current-begin-line)
10130 (while (looking-at "[ \t]*|\\(-\\)?")
10131 (push (if (match-end 1) 'hline 'dline) types)
10132 (if (match-end 1) (push l hlines) (push l dlines))
10133 (beginning-of-line 2)
10134 (setq l (1+ l)))
10135 (setq org-table-current-line-types (apply 'vector (nreverse types))
10136 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10137 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10139 (defun org-table-maybe-eval-formula ()
10140 "Check if the current field starts with \"=\" or \":=\".
10141 If yes, store the formula and apply it."
10142 ;; We already know we are in a table. Get field will only return a formula
10143 ;; when appropriate. It might return a separator line, but no problem.
10144 (when org-table-formula-evaluate-inline
10145 (let* ((field (org-trim (or (org-table-get-field) "")))
10146 named eq)
10147 (when (string-match "^:?=\\(.*\\)" field)
10148 (setq named (equal (string-to-char field) ?:)
10149 eq (match-string 1 field))
10150 (if (or (fboundp 'calc-eval)
10151 (equal (substring eq 0 (min 2 (length eq))) "'("))
10152 (org-table-eval-formula (if named '(4) nil)
10153 (org-table-formula-from-user eq))
10154 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10156 (defvar org-recalc-commands nil
10157 "List of commands triggering the recalculation of a line.
10158 Will be filled automatically during use.")
10160 (defvar org-recalc-marks
10161 '((" " . "Unmarked: no special line, no automatic recalculation")
10162 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10163 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10164 ("!" . "Column name definition line. Reference in formula as $name.")
10165 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10166 ("_" . "Names for values in row below this one.")
10167 ("^" . "Names for values in row above this one.")))
10169 (defun org-table-rotate-recalc-marks (&optional newchar)
10170 "Rotate the recalculation mark in the first column.
10171 If in any row, the first field is not consistent with a mark,
10172 insert a new column for the markers.
10173 When there is an active region, change all the lines in the region,
10174 after prompting for the marking character.
10175 After each change, a message will be displayed indicating the meaning
10176 of the new mark."
10177 (interactive)
10178 (unless (org-at-table-p) (error "Not at a table"))
10179 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10180 (beg (org-table-begin))
10181 (end (org-table-end))
10182 (l (org-current-line))
10183 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10184 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10185 (have-col
10186 (save-excursion
10187 (goto-char beg)
10188 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10189 (col (org-table-current-column))
10190 (forcenew (car (assoc newchar org-recalc-marks)))
10191 epos new)
10192 (when l1
10193 (message "Change region to what mark? Type # * ! $ or SPC: ")
10194 (setq newchar (char-to-string (read-char-exclusive))
10195 forcenew (car (assoc newchar org-recalc-marks))))
10196 (if (and newchar (not forcenew))
10197 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10198 newchar))
10199 (if l1 (goto-line l1))
10200 (save-excursion
10201 (beginning-of-line 1)
10202 (unless (looking-at org-table-dataline-regexp)
10203 (error "Not at a table data line")))
10204 (unless have-col
10205 (org-table-goto-column 1)
10206 (org-table-insert-column)
10207 (org-table-goto-column (1+ col)))
10208 (setq epos (point-at-eol))
10209 (save-excursion
10210 (beginning-of-line 1)
10211 (org-table-get-field
10212 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10213 (concat " "
10214 (setq new (or forcenew
10215 (cadr (member (match-string 1) marks))))
10216 " ")
10217 " # ")))
10218 (if (and l1 l2)
10219 (progn
10220 (goto-line l1)
10221 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10222 (and (looking-at org-table-dataline-regexp)
10223 (org-table-get-field 1 (concat " " new " "))))
10224 (goto-line l1)))
10225 (if (not (= epos (point-at-eol))) (org-table-align))
10226 (goto-line l)
10227 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10229 (defun org-table-maybe-recalculate-line ()
10230 "Recompute the current line if marked for it, and if we haven't just done it."
10231 (interactive)
10232 (and org-table-allow-automatic-line-recalculation
10233 (not (and (memq last-command org-recalc-commands)
10234 (equal org-last-recalc-line (org-current-line))))
10235 (save-excursion (beginning-of-line 1)
10236 (looking-at org-table-auto-recalculate-regexp))
10237 (org-table-recalculate) t))
10239 (defvar org-table-formula-debug nil
10240 "Non-nil means, debug table formulas.
10241 When nil, simply write \"#ERROR\" in corrupted fields.")
10242 (make-variable-buffer-local 'org-table-formula-debug)
10244 (defvar modes)
10245 (defsubst org-set-calc-mode (var &optional value)
10246 (if (stringp var)
10247 (setq var (assoc var '(("D" calc-angle-mode deg)
10248 ("R" calc-angle-mode rad)
10249 ("F" calc-prefer-frac t)
10250 ("S" calc-symbolic-mode t)))
10251 value (nth 2 var) var (nth 1 var)))
10252 (if (memq var modes)
10253 (setcar (cdr (memq var modes)) value)
10254 (cons var (cons value modes)))
10255 modes)
10257 (defun org-table-eval-formula (&optional arg equation
10258 suppress-align suppress-const
10259 suppress-store suppress-analysis)
10260 "Replace the table field value at the cursor by the result of a calculation.
10262 This function makes use of Dave Gillespie's Calc package, in my view the
10263 most exciting program ever written for GNU Emacs. So you need to have Calc
10264 installed in order to use this function.
10266 In a table, this command replaces the value in the current field with the
10267 result of a formula. It also installs the formula as the \"current\" column
10268 formula, by storing it in a special line below the table. When called
10269 with a `C-u' prefix, the current field must ba a named field, and the
10270 formula is installed as valid in only this specific field.
10272 When called with two `C-u' prefixes, insert the active equation
10273 for the field back into the current field, so that it can be
10274 edited there. This is useful in order to use \\[org-table-show-reference]
10275 to check the referenced fields.
10277 When called, the command first prompts for a formula, which is read in
10278 the minibuffer. Previously entered formulas are available through the
10279 history list, and the last used formula is offered as a default.
10280 These stored formulas are adapted correctly when moving, inserting, or
10281 deleting columns with the corresponding commands.
10283 The formula can be any algebraic expression understood by the Calc package.
10284 For details, see the Org-mode manual.
10286 This function can also be called from Lisp programs and offers
10287 additional arguments: EQUATION can be the formula to apply. If this
10288 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10289 used to speed-up recursive calls by by-passing unnecessary aligns.
10290 SUPPRESS-CONST suppresses the interpretation of constants in the
10291 formula, assuming that this has been done already outside the function.
10292 SUPPRESS-STORE means the formula should not be stored, either because
10293 it is already stored, or because it is a modified equation that should
10294 not overwrite the stored one."
10295 (interactive "P")
10296 (org-table-check-inside-data-field)
10297 (or suppress-analysis (org-table-get-specials))
10298 (if (equal arg '(16))
10299 (let ((eq (org-table-current-field-formula)))
10300 (or eq (error "No equation active for current field"))
10301 (org-table-get-field nil eq)
10302 (org-table-align)
10303 (setq org-table-may-need-update t))
10304 (let* (fields
10305 (ndown (if (integerp arg) arg 1))
10306 (org-table-automatic-realign nil)
10307 (case-fold-search nil)
10308 (down (> ndown 1))
10309 (formula (if (and equation suppress-store)
10310 equation
10311 (org-table-get-formula equation (equal arg '(4)))))
10312 (n0 (org-table-current-column))
10313 (modes (copy-sequence org-calc-default-modes))
10314 (numbers nil) ; was a variable, now fixed default
10315 (keep-empty nil)
10316 n form form0 bw fmt x ev orig c lispp literal)
10317 ;; Parse the format string. Since we have a lot of modes, this is
10318 ;; a lot of work. However, I think calc still uses most of the time.
10319 (if (string-match ";" formula)
10320 (let ((tmp (org-split-string formula ";")))
10321 (setq formula (car tmp)
10322 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10323 (nth 1 tmp)))
10324 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10325 (setq c (string-to-char (match-string 1 fmt))
10326 n (string-to-number (match-string 2 fmt)))
10327 (if (= c ?p)
10328 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10329 (setq modes (org-set-calc-mode
10330 'calc-float-format
10331 (list (cdr (assoc c '((?n . float) (?f . fix)
10332 (?s . sci) (?e . eng))))
10333 n))))
10334 (setq fmt (replace-match "" t t fmt)))
10335 (if (string-match "[NT]" fmt)
10336 (setq numbers (equal (match-string 0 fmt) "N")
10337 fmt (replace-match "" t t fmt)))
10338 (if (string-match "L" fmt)
10339 (setq literal t
10340 fmt (replace-match "" t t fmt)))
10341 (if (string-match "E" fmt)
10342 (setq keep-empty t
10343 fmt (replace-match "" t t fmt)))
10344 (while (string-match "[DRFS]" fmt)
10345 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10346 (setq fmt (replace-match "" t t fmt)))
10347 (unless (string-match "\\S-" fmt)
10348 (setq fmt nil))))
10349 (if (and (not suppress-const) org-table-formula-use-constants)
10350 (setq formula (org-table-formula-substitute-names formula)))
10351 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10352 (while (> ndown 0)
10353 (setq fields (org-split-string
10354 (org-no-properties
10355 (buffer-substring (point-at-bol) (point-at-eol)))
10356 " *| *"))
10357 (if (eq numbers t)
10358 (setq fields (mapcar
10359 (lambda (x) (number-to-string (string-to-number x)))
10360 fields)))
10361 (setq ndown (1- ndown))
10362 (setq form (copy-sequence formula)
10363 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10364 (if (and lispp literal) (setq lispp 'literal))
10365 ;; Check for old vertical references
10366 (setq form (org-rewrite-old-row-references form))
10367 ;; Insert complex ranges
10368 (while (string-match org-table-range-regexp form)
10369 (setq form
10370 (replace-match
10371 (save-match-data
10372 (org-table-make-reference
10373 (org-table-get-range (match-string 0 form) nil n0)
10374 keep-empty numbers lispp))
10375 t t form)))
10376 ;; Insert simple ranges
10377 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10378 (setq form
10379 (replace-match
10380 (save-match-data
10381 (org-table-make-reference
10382 (org-sublist
10383 fields (string-to-number (match-string 1 form))
10384 (string-to-number (match-string 2 form)))
10385 keep-empty numbers lispp))
10386 t t form)))
10387 (setq form0 form)
10388 ;; Insert the references to fields in same row
10389 (while (string-match "\\$\\([0-9]+\\)" form)
10390 (setq n (string-to-number (match-string 1 form))
10391 x (nth (1- (if (= n 0) n0 n)) fields))
10392 (unless x (error "Invalid field specifier \"%s\""
10393 (match-string 0 form)))
10394 (setq form (replace-match
10395 (save-match-data
10396 (org-table-make-reference x nil numbers lispp))
10397 t t form)))
10399 (if lispp
10400 (setq ev (condition-case nil
10401 (eval (eval (read form)))
10402 (error "#ERROR"))
10403 ev (if (numberp ev) (number-to-string ev) ev))
10404 (or (fboundp 'calc-eval)
10405 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10406 (setq ev (calc-eval (cons form modes)
10407 (if numbers 'num))))
10409 (when org-table-formula-debug
10410 (with-output-to-temp-buffer "*Substitution History*"
10411 (princ (format "Substitution history of formula
10412 Orig: %s
10413 $xyz-> %s
10414 @r$c-> %s
10415 $1-> %s\n" orig formula form0 form))
10416 (if (listp ev)
10417 (princ (format " %s^\nError: %s"
10418 (make-string (car ev) ?\-) (nth 1 ev)))
10419 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10420 ev (or fmt "NONE")
10421 (if fmt (format fmt (string-to-number ev)) ev)))))
10422 (setq bw (get-buffer-window "*Substitution History*"))
10423 (shrink-window-if-larger-than-buffer bw)
10424 (unless (and (interactive-p) (not ndown))
10425 (unless (let (inhibit-redisplay)
10426 (y-or-n-p "Debugging Formula. Continue to next? "))
10427 (org-table-align)
10428 (error "Abort"))
10429 (delete-window bw)
10430 (message "")))
10431 (if (listp ev) (setq fmt nil ev "#ERROR"))
10432 (org-table-justify-field-maybe
10433 (if fmt (format fmt (string-to-number ev)) ev))
10434 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10435 (call-interactively 'org-return)
10436 (setq ndown 0)))
10437 (and down (org-table-maybe-recalculate-line))
10438 (or suppress-align (and org-table-may-need-update
10439 (org-table-align))))))
10441 (defun org-table-put-field-property (prop value)
10442 (save-excursion
10443 (put-text-property (progn (skip-chars-backward "^|") (point))
10444 (progn (skip-chars-forward "^|") (point))
10445 prop value)))
10447 (defun org-table-get-range (desc &optional tbeg col highlight)
10448 "Get a calc vector from a column, accorting to descriptor DESC.
10449 Optional arguments TBEG and COL can give the beginning of the table and
10450 the current column, to avoid unnecessary parsing.
10451 HIGHLIGHT means, just highlight the range."
10452 (if (not (equal (string-to-char desc) ?@))
10453 (setq desc (concat "@" desc)))
10454 (save-excursion
10455 (or tbeg (setq tbeg (org-table-begin)))
10456 (or col (setq col (org-table-current-column)))
10457 (let ((thisline (org-current-line))
10458 beg end c1 c2 r1 r2 rangep tmp)
10459 (unless (string-match org-table-range-regexp desc)
10460 (error "Invalid table range specifier `%s'" desc))
10461 (setq rangep (match-end 3)
10462 r1 (and (match-end 1) (match-string 1 desc))
10463 r2 (and (match-end 4) (match-string 4 desc))
10464 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10465 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10467 (and c1 (setq c1 (+ (string-to-number c1)
10468 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10469 (and c2 (setq c2 (+ (string-to-number c2)
10470 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10471 (if (equal r1 "") (setq r1 nil))
10472 (if (equal r2 "") (setq r2 nil))
10473 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10474 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10475 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10476 (if (not r1) (setq r1 thisline))
10477 (if (not r2) (setq r2 thisline))
10478 (if (not c1) (setq c1 col))
10479 (if (not c2) (setq c2 col))
10480 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10481 ;; just one field
10482 (progn
10483 (goto-line r1)
10484 (while (not (looking-at org-table-dataline-regexp))
10485 (beginning-of-line 2))
10486 (prog1 (org-trim (org-table-get-field c1))
10487 (if highlight (org-table-highlight-rectangle (point) (point)))))
10488 ;; A range, return a vector
10489 ;; First sort the numbers to get a regular ractangle
10490 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10491 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10492 (goto-line r1)
10493 (while (not (looking-at org-table-dataline-regexp))
10494 (beginning-of-line 2))
10495 (org-table-goto-column c1)
10496 (setq beg (point))
10497 (goto-line r2)
10498 (while (not (looking-at org-table-dataline-regexp))
10499 (beginning-of-line 0))
10500 (org-table-goto-column c2)
10501 (setq end (point))
10502 (if highlight
10503 (org-table-highlight-rectangle
10504 beg (progn (skip-chars-forward "^|\n") (point))))
10505 ;; return string representation of calc vector
10506 (mapcar 'org-trim
10507 (apply 'append (org-table-copy-region beg end)))))))
10509 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10510 "Analyze descriptor DESC and retrieve the corresponding line number.
10511 The cursor is currently in line CLINE, the table begins in line BLINE,
10512 and TABLE is a vector with line types."
10513 (if (string-match "^[0-9]+$" desc)
10514 (aref org-table-dlines (string-to-number desc))
10515 (setq cline (or cline (org-current-line))
10516 bline (or bline org-table-current-begin-line)
10517 table (or table org-table-current-line-types))
10518 (if (or
10519 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10520 ;; 1 2 3 4 5 6
10521 (and (not (match-end 3)) (not (match-end 6)))
10522 (and (match-end 3) (match-end 6) (not (match-end 5))))
10523 (error "invalid row descriptor `%s'" desc))
10524 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10525 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10526 (odir (and (match-end 5) (match-string 5 desc)))
10527 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10528 (i (- cline bline))
10529 (rel (and (match-end 6)
10530 (or (and (match-end 1) (not (match-end 3)))
10531 (match-end 5)))))
10532 (if (and hn (not hdir))
10533 (progn
10534 (setq i 0 hdir "+")
10535 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10536 (if (and (not hn) on (not odir))
10537 (error "should never happen");;(aref org-table-dlines on)
10538 (if (and hn (> hn 0))
10539 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10540 (if on
10541 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10542 (+ bline i)))))
10544 (defun org-find-row-type (table i type backwards relative n)
10545 (let ((l (length table)))
10546 (while (> n 0)
10547 (while (and (setq i (+ i (if backwards -1 1)))
10548 (>= i 0) (< i l)
10549 (not (eq (aref table i) type))
10550 (if (and relative (eq (aref table i) 'hline))
10551 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10552 t)))
10553 (setq n (1- n)))
10554 (if (or (< i 0) (>= i l))
10555 (error "Row descriptior leads outside table")
10556 i)))
10558 (defun org-rewrite-old-row-references (s)
10559 (if (string-match "&[-+0-9I]" s)
10560 (error "Formula contains old &row reference, please rewrite using @-syntax")
10563 (defun org-table-make-reference (elements keep-empty numbers lispp)
10564 "Convert list ELEMENTS to something appropriate to insert into formula.
10565 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10566 NUMBERS indicates that everything should be converted to numbers.
10567 LISPP means to return something appropriate for a Lisp list."
10568 (if (stringp elements) ; just a single val
10569 (if lispp
10570 (if (eq lispp 'literal)
10571 elements
10572 (prin1-to-string (if numbers (string-to-number elements) elements)))
10573 (if (equal elements "") (setq elements "0"))
10574 (if numbers (number-to-string (string-to-number elements)) elements))
10575 (unless keep-empty
10576 (setq elements
10577 (delq nil
10578 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10579 elements))))
10580 (setq elements (or elements '("0")))
10581 (if lispp
10582 (mapconcat
10583 (lambda (x)
10584 (if (eq lispp 'literal)
10586 (prin1-to-string (if numbers (string-to-number x) x))))
10587 elements " ")
10588 (concat "[" (mapconcat
10589 (lambda (x)
10590 (if numbers (number-to-string (string-to-number x)) x))
10591 elements
10592 ",") "]"))))
10594 (defun org-table-recalculate (&optional all noalign)
10595 "Recalculate the current table line by applying all stored formulas.
10596 With prefix arg ALL, do this for all lines in the table."
10597 (interactive "P")
10598 (or (memq this-command org-recalc-commands)
10599 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10600 (unless (org-at-table-p) (error "Not at a table"))
10601 (if (equal all '(16))
10602 (org-table-iterate)
10603 (org-table-get-specials)
10604 (let* ((eqlist (sort (org-table-get-stored-formulas)
10605 (lambda (a b) (string< (car a) (car b)))))
10606 (inhibit-redisplay (not debug-on-error))
10607 (line-re org-table-dataline-regexp)
10608 (thisline (org-current-line))
10609 (thiscol (org-table-current-column))
10610 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10611 ;; Insert constants in all formulas
10612 (setq eqlist
10613 (mapcar (lambda (x)
10614 (setcdr x (org-table-formula-substitute-names (cdr x)))
10616 eqlist))
10617 ;; Split the equation list
10618 (while (setq eq (pop eqlist))
10619 (if (<= (string-to-char (car eq)) ?9)
10620 (push eq eqlnum)
10621 (push eq eqlname)))
10622 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10623 (if all
10624 (progn
10625 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10626 (goto-char (setq beg (org-table-begin)))
10627 (if (re-search-forward org-table-calculate-mark-regexp end t)
10628 ;; This is a table with marked lines, compute selected lines
10629 (setq line-re org-table-recalculate-regexp)
10630 ;; Move forward to the first non-header line
10631 (if (and (re-search-forward org-table-dataline-regexp end t)
10632 (re-search-forward org-table-hline-regexp end t)
10633 (re-search-forward org-table-dataline-regexp end t))
10634 (setq beg (match-beginning 0))
10635 nil))) ;; just leave beg where it is
10636 (setq beg (point-at-bol)
10637 end (move-marker (make-marker) (1+ (point-at-eol)))))
10638 (goto-char beg)
10639 (and all (message "Re-applying formulas to full table..."))
10641 ;; First find the named fields, and mark them untouchanble
10642 (remove-text-properties beg end '(org-untouchable t))
10643 (while (setq eq (pop eqlname))
10644 (setq name (car eq)
10645 a (assoc name org-table-named-field-locations))
10646 (and (not a)
10647 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10648 (setq a (list name
10649 (aref org-table-dlines
10650 (string-to-number (match-string 1 name)))
10651 (string-to-number (match-string 2 name)))))
10652 (when (and a (or all (equal (nth 1 a) thisline)))
10653 (message "Re-applying formula to field: %s" name)
10654 (goto-line (nth 1 a))
10655 (org-table-goto-column (nth 2 a))
10656 (push (append a (list (cdr eq))) eqlname1)
10657 (org-table-put-field-property :org-untouchable t)))
10659 ;; Now evauluate the column formulas, but skip fields covered by
10660 ;; field formulas
10661 (goto-char beg)
10662 (while (re-search-forward line-re end t)
10663 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10664 ;; Unprotected line, recalculate
10665 (and all (message "Re-applying formulas to full table...(line %d)"
10666 (setq cnt (1+ cnt))))
10667 (setq org-last-recalc-line (org-current-line))
10668 (setq eql eqlnum)
10669 (while (setq entry (pop eql))
10670 (goto-line org-last-recalc-line)
10671 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10672 (unless (get-text-property (point) :org-untouchable)
10673 (org-table-eval-formula nil (cdr entry)
10674 'noalign 'nocst 'nostore 'noanalysis)))))
10676 ;; Now evaluate the field formulas
10677 (while (setq eq (pop eqlname1))
10678 (message "Re-applying formula to field: %s" (car eq))
10679 (goto-line (nth 1 eq))
10680 (org-table-goto-column (nth 2 eq))
10681 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10682 'nostore 'noanalysis))
10684 (goto-line thisline)
10685 (org-table-goto-column thiscol)
10686 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10687 (or noalign (and org-table-may-need-update (org-table-align))
10688 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10690 ;; back to initial position
10691 (message "Re-applying formulas...done")
10692 (goto-line thisline)
10693 (org-table-goto-column thiscol)
10694 (or noalign (and org-table-may-need-update (org-table-align))
10695 (and all (message "Re-applying formulas...done"))))))
10697 (defun org-table-iterate (&optional arg)
10698 "Recalculate the table until it does not change anymore."
10699 (interactive "P")
10700 (let ((imax (if arg (prefix-numeric-value arg) 10))
10701 (i 0)
10702 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10703 thistbl)
10704 (catch 'exit
10705 (while (< i imax)
10706 (setq i (1+ i))
10707 (org-table-recalculate 'all)
10708 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10709 (if (not (string= lasttbl thistbl))
10710 (setq lasttbl thistbl)
10711 (if (> i 1)
10712 (message "Convergence after %d iterations" i)
10713 (message "Table was already stable"))
10714 (throw 'exit t)))
10715 (error "No convergence after %d iterations" i))))
10717 (defun org-table-formula-substitute-names (f)
10718 "Replace $const with values in string F."
10719 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10720 ;; First, check for column names
10721 (while (setq start (string-match org-table-column-name-regexp f start))
10722 (setq start (1+ start))
10723 (setq a (assoc (match-string 1 f) org-table-column-names))
10724 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10725 ;; Parameters and constants
10726 (setq start 0)
10727 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10728 (setq start (1+ start))
10729 (if (setq a (save-match-data
10730 (org-table-get-constant (match-string 1 f))))
10731 (setq f (replace-match
10732 (concat (if pp "(") a (if pp ")")) t t f))))
10733 (if org-table-formula-debug
10734 (put-text-property 0 (length f) :orig-formula f1 f))
10737 (defun org-table-get-constant (const)
10738 "Find the value for a parameter or constant in a formula.
10739 Parameters get priority."
10740 (or (cdr (assoc const org-table-local-parameters))
10741 (cdr (assoc const org-table-formula-constants-local))
10742 (cdr (assoc const org-table-formula-constants))
10743 (and (fboundp 'constants-get) (constants-get const))
10744 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10745 (org-entry-get nil (substring const 5) 'inherit))
10746 "#UNDEFINED_NAME"))
10748 (defvar org-table-fedit-map
10749 (let ((map (make-sparse-keymap)))
10750 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10751 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10752 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10753 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10754 (org-defkey map "\C-c?" 'org-table-show-reference)
10755 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10756 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10757 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10758 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10759 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10760 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10761 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10762 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10763 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10764 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10765 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10766 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10767 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10768 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10769 map))
10771 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10772 '("Edit-Formulas"
10773 ["Finish and Install" org-table-fedit-finish t]
10774 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10775 ["Abort" org-table-fedit-abort t]
10776 "--"
10777 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10778 ["Complete Lisp Symbol" lisp-complete-symbol t]
10779 "--"
10780 "Shift Reference at Point"
10781 ["Up" org-table-fedit-ref-up t]
10782 ["Down" org-table-fedit-ref-down t]
10783 ["Left" org-table-fedit-ref-left t]
10784 ["Right" org-table-fedit-ref-right t]
10786 "Change Test Row for Column Formulas"
10787 ["Up" org-table-fedit-line-up t]
10788 ["Down" org-table-fedit-line-down t]
10789 "--"
10790 ["Scroll Table Window" org-table-fedit-scroll t]
10791 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10792 ["Show Table Grid" org-table-fedit-toggle-coordinates
10793 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10794 org-table-overlay-coordinates)]
10795 "--"
10796 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10797 :style toggle :selected org-table-buffer-is-an]))
10799 (defvar org-pos)
10801 (defun org-table-edit-formulas ()
10802 "Edit the formulas of the current table in a separate buffer."
10803 (interactive)
10804 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10805 (beginning-of-line 0))
10806 (unless (org-at-table-p) (error "Not at a table"))
10807 (org-table-get-specials)
10808 (let ((key (org-table-current-field-formula 'key 'noerror))
10809 (eql (sort (org-table-get-stored-formulas 'noerror)
10810 'org-table-formula-less-p))
10811 (pos (move-marker (make-marker) (point)))
10812 (startline 1)
10813 (wc (current-window-configuration))
10814 (titles '((column . "# Column Formulas\n")
10815 (field . "# Field Formulas\n")
10816 (named . "# Named Field Formulas\n")))
10817 entry s type title)
10818 (org-switch-to-buffer-other-window "*Edit Formulas*")
10819 (erase-buffer)
10820 ;; Keep global-font-lock-mode from turning on font-lock-mode
10821 (let ((font-lock-global-modes '(not fundamental-mode)))
10822 (fundamental-mode))
10823 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10824 (org-set-local 'org-pos pos)
10825 (org-set-local 'org-window-configuration wc)
10826 (use-local-map org-table-fedit-map)
10827 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10828 (easy-menu-add org-table-fedit-menu)
10829 (setq startline (org-current-line))
10830 (while (setq entry (pop eql))
10831 (setq type (cond
10832 ((equal (string-to-char (car entry)) ?@) 'field)
10833 ((string-match "^[0-9]" (car entry)) 'column)
10834 (t 'named)))
10835 (when (setq title (assq type titles))
10836 (or (bobp) (insert "\n"))
10837 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10838 (setq titles (delq title titles)))
10839 (if (equal key (car entry)) (setq startline (org-current-line)))
10840 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10841 (car entry) " = " (cdr entry) "\n"))
10842 (remove-text-properties 0 (length s) '(face nil) s)
10843 (insert s))
10844 (if (eq org-table-use-standard-references t)
10845 (org-table-fedit-toggle-ref-type))
10846 (goto-line startline)
10847 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10849 (defun org-table-fedit-post-command ()
10850 (when (not (memq this-command '(lisp-complete-symbol)))
10851 (let ((win (selected-window)))
10852 (save-excursion
10853 (condition-case nil
10854 (org-table-show-reference)
10855 (error nil))
10856 (select-window win)))))
10858 (defun org-table-formula-to-user (s)
10859 "Convert a formula from internal to user representation."
10860 (if (eq org-table-use-standard-references t)
10861 (org-table-convert-refs-to-an s)
10864 (defun org-table-formula-from-user (s)
10865 "Convert a formula from user to internal representation."
10866 (if org-table-use-standard-references
10867 (org-table-convert-refs-to-rc s)
10870 (defun org-table-convert-refs-to-rc (s)
10871 "Convert spreadsheet references from AB7 to @7$28.
10872 Works for single references, but also for entire formulas and even the
10873 full TBLFM line."
10874 (let ((start 0))
10875 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10876 (cond
10877 ((match-end 3)
10878 ;; format match, just advance
10879 (setq start (match-end 0)))
10880 ((and (> (match-beginning 0) 0)
10881 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10882 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10883 ;; 3.e5 or something like this.
10884 (setq start (match-end 0)))
10886 (setq start (match-beginning 0)
10887 s (replace-match
10888 (if (equal (match-string 2 s) "&")
10889 (format "$%d" (org-letters-to-number (match-string 1 s)))
10890 (format "@%d$%d"
10891 (string-to-number (match-string 2 s))
10892 (org-letters-to-number (match-string 1 s))))
10893 t t s)))))
10896 (defun org-table-convert-refs-to-an (s)
10897 "Convert spreadsheet references from to @7$28 to AB7.
10898 Works for single references, but also for entire formulas and even the
10899 full TBLFM line."
10900 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10901 (setq s (replace-match
10902 (format "%s%d"
10903 (org-number-to-letters
10904 (string-to-number (match-string 2 s)))
10905 (string-to-number (match-string 1 s)))
10906 t t s)))
10907 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10908 (setq s (replace-match (concat "\\1"
10909 (org-number-to-letters
10910 (string-to-number (match-string 2 s))) "&")
10911 t nil s)))
10914 (defun org-letters-to-number (s)
10915 "Convert a base 26 number represented by letters into an integer.
10916 For example: AB -> 28."
10917 (let ((n 0))
10918 (setq s (upcase s))
10919 (while (> (length s) 0)
10920 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10921 s (substring s 1)))
10924 (defun org-number-to-letters (n)
10925 "Convert an integer into a base 26 number represented by letters.
10926 For example: 28 -> AB."
10927 (let ((s ""))
10928 (while (> n 0)
10929 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10930 n (/ (1- n) 26)))
10933 (defun org-table-fedit-convert-buffer (function)
10934 "Convert all references in this buffer, using FUNTION."
10935 (let ((line (org-current-line)))
10936 (goto-char (point-min))
10937 (while (not (eobp))
10938 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10939 (delete-region (point) (point-at-eol))
10940 (or (eobp) (forward-char 1)))
10941 (goto-line line)))
10943 (defun org-table-fedit-toggle-ref-type ()
10944 "Convert all references in the buffer from B3 to @3$2 and back."
10945 (interactive)
10946 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10947 (org-table-fedit-convert-buffer
10948 (if org-table-buffer-is-an
10949 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10950 (message "Reference type switched to %s"
10951 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10953 (defun org-table-fedit-ref-up ()
10954 "Shift the reference at point one row/hline up."
10955 (interactive)
10956 (org-table-fedit-shift-reference 'up))
10957 (defun org-table-fedit-ref-down ()
10958 "Shift the reference at point one row/hline down."
10959 (interactive)
10960 (org-table-fedit-shift-reference 'down))
10961 (defun org-table-fedit-ref-left ()
10962 "Shift the reference at point one field to the left."
10963 (interactive)
10964 (org-table-fedit-shift-reference 'left))
10965 (defun org-table-fedit-ref-right ()
10966 "Shift the reference at point one field to the right."
10967 (interactive)
10968 (org-table-fedit-shift-reference 'right))
10970 (defun org-table-fedit-shift-reference (dir)
10971 (cond
10972 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10973 (if (memq dir '(left right))
10974 (org-rematch-and-replace 1 (eq dir 'left))
10975 (error "Cannot shift reference in this direction")))
10976 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10977 ;; A B3-like reference
10978 (if (memq dir '(up down))
10979 (org-rematch-and-replace 2 (eq dir 'up))
10980 (org-rematch-and-replace 1 (eq dir 'left))))
10981 ((org-at-regexp-p
10982 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10983 ;; An internal reference
10984 (if (memq dir '(up down))
10985 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10986 (org-rematch-and-replace 5 (eq dir 'left))))))
10988 (defun org-rematch-and-replace (n &optional decr hline)
10989 "Re-match the group N, and replace it with the shifted refrence."
10990 (or (match-end n) (error "Cannot shift reference in this direction"))
10991 (goto-char (match-beginning n))
10992 (and (looking-at (regexp-quote (match-string n)))
10993 (replace-match (org-shift-refpart (match-string 0) decr hline)
10994 t t)))
10996 (defun org-shift-refpart (ref &optional decr hline)
10997 "Shift a refrence part REF.
10998 If DECR is set, decrease the references row/column, else increase.
10999 If HLINE is set, this may be a hline reference, it certainly is not
11000 a translation reference."
11001 (save-match-data
11002 (let* ((sign (string-match "^[-+]" ref)) n)
11004 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
11005 (cond
11006 ((and hline (string-match "^I+" ref))
11007 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11008 (setq n (+ n (if decr -1 1)))
11009 (if (= n 0) (setq n (+ n (if decr -1 1))))
11010 (if sign
11011 (setq sign (if (< n 0) "-" "+") n (abs n))
11012 (setq n (max 1 n)))
11013 (concat sign (make-string n ?I)))
11015 ((string-match "^[0-9]+" ref)
11016 (setq n (string-to-number (concat sign ref)))
11017 (setq n (+ n (if decr -1 1)))
11018 (if sign
11019 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11020 (number-to-string (max 1 n))))
11022 ((string-match "^[a-zA-Z]+" ref)
11023 (org-number-to-letters
11024 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11026 (t (error "Cannot shift reference"))))))
11028 (defun org-table-fedit-toggle-coordinates ()
11029 "Toggle the display of coordinates in the refrenced table."
11030 (interactive)
11031 (let ((pos (marker-position org-pos)))
11032 (with-current-buffer (marker-buffer org-pos)
11033 (save-excursion
11034 (goto-char pos)
11035 (org-table-toggle-coordinate-overlays)))))
11037 (defun org-table-fedit-finish (&optional arg)
11038 "Parse the buffer for formula definitions and install them.
11039 With prefix ARG, apply the new formulas to the table."
11040 (interactive "P")
11041 (org-table-remove-rectangle-highlight)
11042 (if org-table-use-standard-references
11043 (progn
11044 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11045 (setq org-table-buffer-is-an nil)))
11046 (let ((pos org-pos) eql var form)
11047 (goto-char (point-min))
11048 (while (re-search-forward
11049 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11050 nil t)
11051 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11052 form (match-string 3))
11053 (setq form (org-trim form))
11054 (when (not (equal form ""))
11055 (while (string-match "[ \t]*\n[ \t]*" form)
11056 (setq form (replace-match " " t t form)))
11057 (when (assoc var eql)
11058 (error "Double formulas for %s" var))
11059 (push (cons var form) eql)))
11060 (setq org-pos nil)
11061 (set-window-configuration org-window-configuration)
11062 (select-window (get-buffer-window (marker-buffer pos)))
11063 (goto-char pos)
11064 (unless (org-at-table-p)
11065 (error "Lost table position - cannot install formulae"))
11066 (org-table-store-formulas eql)
11067 (move-marker pos nil)
11068 (kill-buffer "*Edit Formulas*")
11069 (if arg
11070 (org-table-recalculate 'all)
11071 (message "New formulas installed - press C-u C-c C-c to apply."))))
11073 (defun org-table-fedit-abort ()
11074 "Abort editing formulas, without installing the changes."
11075 (interactive)
11076 (org-table-remove-rectangle-highlight)
11077 (let ((pos org-pos))
11078 (set-window-configuration org-window-configuration)
11079 (select-window (get-buffer-window (marker-buffer pos)))
11080 (goto-char pos)
11081 (move-marker pos nil)
11082 (message "Formula editing aborted without installing changes")))
11084 (defun org-table-fedit-lisp-indent ()
11085 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11086 (interactive)
11087 (let ((pos (point)) beg end ind)
11088 (beginning-of-line 1)
11089 (cond
11090 ((looking-at "[ \t]")
11091 (goto-char pos)
11092 (call-interactively 'lisp-indent-line))
11093 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11094 ((not (fboundp 'pp-buffer))
11095 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11096 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11097 (goto-char (- (match-end 0) 2))
11098 (setq beg (point))
11099 (setq ind (make-string (current-column) ?\ ))
11100 (condition-case nil (forward-sexp 1)
11101 (error
11102 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11103 (setq end (point))
11104 (save-restriction
11105 (narrow-to-region beg end)
11106 (if (eq last-command this-command)
11107 (progn
11108 (goto-char (point-min))
11109 (setq this-command nil)
11110 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11111 (replace-match " ")))
11112 (pp-buffer)
11113 (untabify (point-min) (point-max))
11114 (goto-char (1+ (point-min)))
11115 (while (re-search-forward "^." nil t)
11116 (beginning-of-line 1)
11117 (insert ind))
11118 (goto-char (point-max))
11119 (backward-delete-char 1)))
11120 (goto-char beg))
11121 (t nil))))
11123 (defvar org-show-positions nil)
11125 (defun org-table-show-reference (&optional local)
11126 "Show the location/value of the $ expression at point."
11127 (interactive)
11128 (org-table-remove-rectangle-highlight)
11129 (catch 'exit
11130 (let ((pos (if local (point) org-pos))
11131 (face2 'highlight)
11132 (org-inhibit-highlight-removal t)
11133 (win (selected-window))
11134 (org-show-positions nil)
11135 var name e what match dest)
11136 (if local (org-table-get-specials))
11137 (setq what (cond
11138 ((or (org-at-regexp-p org-table-range-regexp2)
11139 (org-at-regexp-p org-table-translate-regexp)
11140 (org-at-regexp-p org-table-range-regexp))
11141 (setq match
11142 (save-match-data
11143 (org-table-convert-refs-to-rc (match-string 0))))
11144 'range)
11145 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11146 ((org-at-regexp-p "\\$[0-9]+") 'column)
11147 ((not local) nil)
11148 (t (error "No reference at point")))
11149 match (and what (or match (match-string 0))))
11150 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11151 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11152 'secondary-selection))
11153 (org-add-hook 'before-change-functions
11154 'org-table-remove-rectangle-highlight)
11155 (if (eq what 'name) (setq var (substring match 1)))
11156 (when (eq what 'range)
11157 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11158 (setq match (org-table-formula-substitute-names match)))
11159 (unless local
11160 (save-excursion
11161 (end-of-line 1)
11162 (re-search-backward "^\\S-" nil t)
11163 (beginning-of-line 1)
11164 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11165 (setq dest
11166 (save-match-data
11167 (org-table-convert-refs-to-rc (match-string 1))))
11168 (org-table-add-rectangle-overlay
11169 (match-beginning 1) (match-end 1) face2))))
11170 (if (and (markerp pos) (marker-buffer pos))
11171 (if (get-buffer-window (marker-buffer pos))
11172 (select-window (get-buffer-window (marker-buffer pos)))
11173 (org-switch-to-buffer-other-window (get-buffer-window
11174 (marker-buffer pos)))))
11175 (goto-char pos)
11176 (org-table-force-dataline)
11177 (when dest
11178 (setq name (substring dest 1))
11179 (cond
11180 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11181 (setq e (assoc name org-table-named-field-locations))
11182 (goto-line (nth 1 e))
11183 (org-table-goto-column (nth 2 e)))
11184 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11185 (let ((l (string-to-number (match-string 1 dest)))
11186 (c (string-to-number (match-string 2 dest))))
11187 (goto-line (aref org-table-dlines l))
11188 (org-table-goto-column c)))
11189 (t (org-table-goto-column (string-to-number name))))
11190 (move-marker pos (point))
11191 (org-table-highlight-rectangle nil nil face2))
11192 (cond
11193 ((equal dest match))
11194 ((not match))
11195 ((eq what 'range)
11196 (condition-case nil
11197 (save-excursion
11198 (org-table-get-range match nil nil 'highlight))
11199 (error nil)))
11200 ((setq e (assoc var org-table-named-field-locations))
11201 (goto-line (nth 1 e))
11202 (org-table-goto-column (nth 2 e))
11203 (org-table-highlight-rectangle (point) (point))
11204 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11205 ((setq e (assoc var org-table-column-names))
11206 (org-table-goto-column (string-to-number (cdr e)))
11207 (org-table-highlight-rectangle (point) (point))
11208 (goto-char (org-table-begin))
11209 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11210 (org-table-end) t)
11211 (progn
11212 (goto-char (match-beginning 1))
11213 (org-table-highlight-rectangle)
11214 (message "Named column (column %s)" (cdr e)))
11215 (error "Column name not found")))
11216 ((eq what 'column)
11217 ;; column number
11218 (org-table-goto-column (string-to-number (substring match 1)))
11219 (org-table-highlight-rectangle (point) (point))
11220 (message "Column %s" (substring match 1)))
11221 ((setq e (assoc var org-table-local-parameters))
11222 (goto-char (org-table-begin))
11223 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11224 (progn
11225 (goto-char (match-beginning 1))
11226 (org-table-highlight-rectangle)
11227 (message "Local parameter."))
11228 (error "Parameter not found")))
11230 (cond
11231 ((not var) (error "No reference at point"))
11232 ((setq e (assoc var org-table-formula-constants-local))
11233 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11234 var (cdr e)))
11235 ((setq e (assoc var org-table-formula-constants))
11236 (message "Constant: $%s=%s in `org-table-formula-constants'."
11237 var (cdr e)))
11238 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11239 (message "Constant: $%s=%s, from `constants.el'%s."
11240 var e (format " (%s units)" constants-unit-system)))
11241 (t (error "Undefined name $%s" var)))))
11242 (goto-char pos)
11243 (when (and org-show-positions
11244 (not (memq this-command '(org-table-fedit-scroll
11245 org-table-fedit-scroll-down))))
11246 (push pos org-show-positions)
11247 (push org-table-current-begin-pos org-show-positions)
11248 (let ((min (apply 'min org-show-positions))
11249 (max (apply 'max org-show-positions)))
11250 (goto-char min) (recenter 0)
11251 (goto-char max)
11252 (or (pos-visible-in-window-p max) (recenter -1))))
11253 (select-window win))))
11255 (defun org-table-force-dataline ()
11256 "Make sure the cursor is in a dataline in a table."
11257 (unless (save-excursion
11258 (beginning-of-line 1)
11259 (looking-at org-table-dataline-regexp))
11260 (let* ((re org-table-dataline-regexp)
11261 (p1 (save-excursion (re-search-forward re nil 'move)))
11262 (p2 (save-excursion (re-search-backward re nil 'move))))
11263 (cond ((and p1 p2)
11264 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11265 p1 p2)))
11266 ((or p1 p2) (goto-char (or p1 p2)))
11267 (t (error "No table dataline around here"))))))
11269 (defun org-table-fedit-line-up ()
11270 "Move cursor one line up in the window showing the table."
11271 (interactive)
11272 (org-table-fedit-move 'previous-line))
11274 (defun org-table-fedit-line-down ()
11275 "Move cursor one line down in the window showing the table."
11276 (interactive)
11277 (org-table-fedit-move 'next-line))
11279 (defun org-table-fedit-move (command)
11280 "Move the cursor in the window shoinw the table.
11281 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11282 (let ((org-table-allow-automatic-line-recalculation nil)
11283 (pos org-pos) (win (selected-window)) p)
11284 (select-window (get-buffer-window (marker-buffer org-pos)))
11285 (setq p (point))
11286 (call-interactively command)
11287 (while (and (org-at-table-p)
11288 (org-at-table-hline-p))
11289 (call-interactively command))
11290 (or (org-at-table-p) (goto-char p))
11291 (move-marker pos (point))
11292 (select-window win)))
11294 (defun org-table-fedit-scroll (N)
11295 (interactive "p")
11296 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11297 (scroll-other-window N)))
11299 (defun org-table-fedit-scroll-down (N)
11300 (interactive "p")
11301 (org-table-fedit-scroll (- N)))
11303 (defvar org-table-rectangle-overlays nil)
11305 (defun org-table-add-rectangle-overlay (beg end &optional face)
11306 "Add a new overlay."
11307 (let ((ov (org-make-overlay beg end)))
11308 (org-overlay-put ov 'face (or face 'secondary-selection))
11309 (push ov org-table-rectangle-overlays)))
11311 (defun org-table-highlight-rectangle (&optional beg end face)
11312 "Highlight rectangular region in a table."
11313 (setq beg (or beg (point)) end (or end (point)))
11314 (let ((b (min beg end))
11315 (e (max beg end))
11316 l1 c1 l2 c2 tmp)
11317 (and (boundp 'org-show-positions)
11318 (setq org-show-positions (cons b (cons e org-show-positions))))
11319 (goto-char (min beg end))
11320 (setq l1 (org-current-line)
11321 c1 (org-table-current-column))
11322 (goto-char (max beg end))
11323 (setq l2 (org-current-line)
11324 c2 (org-table-current-column))
11325 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11326 (goto-line l1)
11327 (beginning-of-line 1)
11328 (loop for line from l1 to l2 do
11329 (when (looking-at org-table-dataline-regexp)
11330 (org-table-goto-column c1)
11331 (skip-chars-backward "^|\n") (setq beg (point))
11332 (org-table-goto-column c2)
11333 (skip-chars-forward "^|\n") (setq end (point))
11334 (org-table-add-rectangle-overlay beg end face))
11335 (beginning-of-line 2))
11336 (goto-char b))
11337 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11339 (defun org-table-remove-rectangle-highlight (&rest ignore)
11340 "Remove the rectangle overlays."
11341 (unless org-inhibit-highlight-removal
11342 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11343 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11344 (setq org-table-rectangle-overlays nil)))
11346 (defvar org-table-coordinate-overlays nil
11347 "Collects the cooordinate grid overlays, so that they can be removed.")
11348 (make-variable-buffer-local 'org-table-coordinate-overlays)
11350 (defun org-table-overlay-coordinates ()
11351 "Add overlays to the table at point, to show row/column coordinates."
11352 (interactive)
11353 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11354 (setq org-table-coordinate-overlays nil)
11355 (save-excursion
11356 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11357 (goto-char (org-table-begin))
11358 (while (org-at-table-p)
11359 (setq eol (point-at-eol))
11360 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11361 (push ov org-table-coordinate-overlays)
11362 (setq hline (looking-at org-table-hline-regexp))
11363 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11364 (format "%4d" (setq id (1+ id)))))
11365 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11366 (when hline
11367 (setq ic 0)
11368 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11369 (setq beg (1+ (match-beginning 0))
11370 ic (1+ ic)
11371 s1 (concat "$" (int-to-string ic))
11372 s2 (org-number-to-letters ic)
11373 str (if (eq org-table-use-standard-references t) s2 s1))
11374 (setq ov (org-make-overlay beg (+ beg (length str))))
11375 (push ov org-table-coordinate-overlays)
11376 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11377 (beginning-of-line 2)))))
11379 (defun org-table-toggle-coordinate-overlays ()
11380 "Toggle the display of Row/Column numbers in tables."
11381 (interactive)
11382 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11383 (message "Row/Column number display turned %s"
11384 (if org-table-overlay-coordinates "on" "off"))
11385 (if (and (org-at-table-p) org-table-overlay-coordinates)
11386 (org-table-align))
11387 (unless org-table-overlay-coordinates
11388 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11389 (setq org-table-coordinate-overlays nil)))
11391 (defun org-table-toggle-formula-debugger ()
11392 "Toggle the formula debugger in tables."
11393 (interactive)
11394 (setq org-table-formula-debug (not org-table-formula-debug))
11395 (message "Formula debugging has been turned %s"
11396 (if org-table-formula-debug "on" "off")))
11398 ;;; The orgtbl minor mode
11400 ;; Define a minor mode which can be used in other modes in order to
11401 ;; integrate the org-mode table editor.
11403 ;; This is really a hack, because the org-mode table editor uses several
11404 ;; keys which normally belong to the major mode, for example the TAB and
11405 ;; RET keys. Here is how it works: The minor mode defines all the keys
11406 ;; necessary to operate the table editor, but wraps the commands into a
11407 ;; function which tests if the cursor is currently inside a table. If that
11408 ;; is the case, the table editor command is executed. However, when any of
11409 ;; those keys is used outside a table, the function uses `key-binding' to
11410 ;; look up if the key has an associated command in another currently active
11411 ;; keymap (minor modes, major mode, global), and executes that command.
11412 ;; There might be problems if any of the keys used by the table editor is
11413 ;; otherwise used as a prefix key.
11415 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11416 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11417 ;; addresses this by checking explicitly for both bindings.
11419 ;; The optimized version (see variable `orgtbl-optimized') takes over
11420 ;; all keys which are bound to `self-insert-command' in the *global map*.
11421 ;; Some modes bind other commands to simple characters, for example
11422 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11423 ;; active, this binding is ignored inside tables and replaced with a
11424 ;; modified self-insert.
11426 (defvar orgtbl-mode nil
11427 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11428 table editor in arbitrary modes.")
11429 (make-variable-buffer-local 'orgtbl-mode)
11431 (defvar orgtbl-mode-map (make-keymap)
11432 "Keymap for `orgtbl-mode'.")
11434 ;;;###autoload
11435 (defun turn-on-orgtbl ()
11436 "Unconditionally turn on `orgtbl-mode'."
11437 (orgtbl-mode 1))
11439 (defvar org-old-auto-fill-inhibit-regexp nil
11440 "Local variable used by `orgtbl-mode'")
11442 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11443 "Matches a line belonging to an orgtbl.")
11445 (defconst orgtbl-extra-font-lock-keywords
11446 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11447 0 (quote 'org-table) 'prepend))
11448 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11450 ;;;###autoload
11451 (defun orgtbl-mode (&optional arg)
11452 "The `org-mode' table editor as a minor mode for use in other modes."
11453 (interactive)
11454 (if (org-mode-p)
11455 ;; Exit without error, in case some hook functions calls this
11456 ;; by accident in org-mode.
11457 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11458 (setq orgtbl-mode
11459 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11460 (if orgtbl-mode
11461 (progn
11462 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11463 ;; Make sure we are first in minor-mode-map-alist
11464 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11465 (and c (setq minor-mode-map-alist
11466 (cons c (delq c minor-mode-map-alist)))))
11467 (org-set-local (quote org-table-may-need-update) t)
11468 (org-add-hook 'before-change-functions 'org-before-change-function
11469 nil 'local)
11470 (org-set-local 'org-old-auto-fill-inhibit-regexp
11471 auto-fill-inhibit-regexp)
11472 (org-set-local 'auto-fill-inhibit-regexp
11473 (if auto-fill-inhibit-regexp
11474 (concat orgtbl-line-start-regexp "\\|"
11475 auto-fill-inhibit-regexp)
11476 orgtbl-line-start-regexp))
11477 (org-add-to-invisibility-spec '(org-cwidth))
11478 (when (fboundp 'font-lock-add-keywords)
11479 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11480 (org-restart-font-lock))
11481 (easy-menu-add orgtbl-mode-menu)
11482 (run-hooks 'orgtbl-mode-hook))
11483 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11484 (org-cleanup-narrow-column-properties)
11485 (org-remove-from-invisibility-spec '(org-cwidth))
11486 (remove-hook 'before-change-functions 'org-before-change-function t)
11487 (when (fboundp 'font-lock-remove-keywords)
11488 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11489 (org-restart-font-lock))
11490 (easy-menu-remove orgtbl-mode-menu)
11491 (force-mode-line-update 'all))))
11493 (defun org-cleanup-narrow-column-properties ()
11494 "Remove all properties related to narrow-column invisibility."
11495 (let ((s 1))
11496 (while (setq s (text-property-any s (point-max)
11497 'display org-narrow-column-arrow))
11498 (remove-text-properties s (1+ s) '(display t)))
11499 (setq s 1)
11500 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11501 (remove-text-properties s (1+ s) '(org-cwidth t)))
11502 (setq s 1)
11503 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11504 (remove-text-properties s (1+ s) '(invisible t)))))
11506 ;; Install it as a minor mode.
11507 (put 'orgtbl-mode :included t)
11508 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11509 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11511 (defun orgtbl-make-binding (fun n &rest keys)
11512 "Create a function for binding in the table minor mode.
11513 FUN is the command to call inside a table. N is used to create a unique
11514 command name. KEYS are keys that should be checked in for a command
11515 to execute outside of tables."
11516 (eval
11517 (list 'defun
11518 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11519 '(arg)
11520 (concat "In tables, run `" (symbol-name fun) "'.\n"
11521 "Outside of tables, run the binding of `"
11522 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11523 "'.")
11524 '(interactive "p")
11525 (list 'if
11526 '(org-at-table-p)
11527 (list 'call-interactively (list 'quote fun))
11528 (list 'let '(orgtbl-mode)
11529 (list 'call-interactively
11530 (append '(or)
11531 (mapcar (lambda (k)
11532 (list 'key-binding k))
11533 keys)
11534 '('orgtbl-error))))))))
11536 (defun orgtbl-error ()
11537 "Error when there is no default binding for a table key."
11538 (interactive)
11539 (error "This key has no function outside tables"))
11541 (defun orgtbl-setup ()
11542 "Setup orgtbl keymaps."
11543 (let ((nfunc 0)
11544 (bindings
11545 (list
11546 '([(meta shift left)] org-table-delete-column)
11547 '([(meta left)] org-table-move-column-left)
11548 '([(meta right)] org-table-move-column-right)
11549 '([(meta shift right)] org-table-insert-column)
11550 '([(meta shift up)] org-table-kill-row)
11551 '([(meta shift down)] org-table-insert-row)
11552 '([(meta up)] org-table-move-row-up)
11553 '([(meta down)] org-table-move-row-down)
11554 '("\C-c\C-w" org-table-cut-region)
11555 '("\C-c\M-w" org-table-copy-region)
11556 '("\C-c\C-y" org-table-paste-rectangle)
11557 '("\C-c-" org-table-insert-hline)
11558 '("\C-c}" org-table-toggle-coordinate-overlays)
11559 '("\C-c{" org-table-toggle-formula-debugger)
11560 '("\C-m" org-table-next-row)
11561 '([(shift return)] org-table-copy-down)
11562 '("\C-c\C-q" org-table-wrap-region)
11563 '("\C-c?" org-table-field-info)
11564 '("\C-c " org-table-blank-field)
11565 '("\C-c+" org-table-sum)
11566 '("\C-c=" org-table-eval-formula)
11567 '("\C-c'" org-table-edit-formulas)
11568 '("\C-c`" org-table-edit-field)
11569 '("\C-c*" org-table-recalculate)
11570 '("\C-c|" org-table-create-or-convert-from-region)
11571 '("\C-c^" org-table-sort-lines)
11572 '([(control ?#)] org-table-rotate-recalc-marks)))
11573 elt key fun cmd)
11574 (while (setq elt (pop bindings))
11575 (setq nfunc (1+ nfunc))
11576 (setq key (org-key (car elt))
11577 fun (nth 1 elt)
11578 cmd (orgtbl-make-binding fun nfunc key))
11579 (org-defkey orgtbl-mode-map key cmd))
11581 ;; Special treatment needed for TAB and RET
11582 (org-defkey orgtbl-mode-map [(return)]
11583 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11584 (org-defkey orgtbl-mode-map "\C-m"
11585 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11587 (org-defkey orgtbl-mode-map [(tab)]
11588 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11589 (org-defkey orgtbl-mode-map "\C-i"
11590 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11592 (org-defkey orgtbl-mode-map [(shift tab)]
11593 (orgtbl-make-binding 'org-table-previous-field 104
11594 [(shift tab)] [(tab)] "\C-i"))
11596 (org-defkey orgtbl-mode-map "\M-\C-m"
11597 (orgtbl-make-binding 'org-table-wrap-region 105
11598 "\M-\C-m" [(meta return)]))
11599 (org-defkey orgtbl-mode-map [(meta return)]
11600 (orgtbl-make-binding 'org-table-wrap-region 106
11601 [(meta return)] "\M-\C-m"))
11603 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11604 (when orgtbl-optimized
11605 ;; If the user wants maximum table support, we need to hijack
11606 ;; some standard editing functions
11607 (org-remap orgtbl-mode-map
11608 'self-insert-command 'orgtbl-self-insert-command
11609 'delete-char 'org-delete-char
11610 'delete-backward-char 'org-delete-backward-char)
11611 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11612 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11613 '("OrgTbl"
11614 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11615 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11616 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11617 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11618 "--"
11619 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11620 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11621 ["Copy Field from Above"
11622 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11623 "--"
11624 ("Column"
11625 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11626 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11627 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11628 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11629 ("Row"
11630 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11631 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11632 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11633 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11634 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11635 "--"
11636 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11637 ("Rectangle"
11638 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11639 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11640 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11641 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11642 "--"
11643 ("Radio tables"
11644 ["Insert table template" orgtbl-insert-radio-table
11645 (assq major-mode orgtbl-radio-table-templates)]
11646 ["Comment/uncomment table" orgtbl-toggle-comment t])
11647 "--"
11648 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11649 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11650 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11651 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11652 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11653 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11654 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11655 ["Sum Column/Rectangle" org-table-sum
11656 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11657 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11658 ["Debug Formulas"
11659 org-table-toggle-formula-debugger :active (org-at-table-p)
11660 :keys "C-c {"
11661 :style toggle :selected org-table-formula-debug]
11662 ["Show Col/Row Numbers"
11663 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11664 :keys "C-c }"
11665 :style toggle :selected org-table-overlay-coordinates]
11669 (defun orgtbl-ctrl-c-ctrl-c (arg)
11670 "If the cursor is inside a table, realign the table.
11671 It it is a table to be sent away to a receiver, do it.
11672 With prefix arg, also recompute table."
11673 (interactive "P")
11674 (let ((pos (point)) action)
11675 (save-excursion
11676 (beginning-of-line 1)
11677 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11678 ((looking-at "[ \t]*|") pos)
11679 ((looking-at "#\\+TBLFM:") 'recalc))))
11680 (cond
11681 ((integerp action)
11682 (goto-char action)
11683 (org-table-maybe-eval-formula)
11684 (if arg
11685 (call-interactively 'org-table-recalculate)
11686 (org-table-maybe-recalculate-line))
11687 (call-interactively 'org-table-align)
11688 (orgtbl-send-table 'maybe))
11689 ((eq action 'recalc)
11690 (save-excursion
11691 (beginning-of-line 1)
11692 (skip-chars-backward " \r\n\t")
11693 (if (org-at-table-p)
11694 (org-call-with-arg 'org-table-recalculate t))))
11695 (t (let (orgtbl-mode)
11696 (call-interactively (key-binding "\C-c\C-c")))))))
11698 (defun orgtbl-tab (arg)
11699 "Justification and field motion for `orgtbl-mode'."
11700 (interactive "P")
11701 (if arg (org-table-edit-field t)
11702 (org-table-justify-field-maybe)
11703 (org-table-next-field)))
11705 (defun orgtbl-ret ()
11706 "Justification and field motion for `orgtbl-mode'."
11707 (interactive)
11708 (org-table-justify-field-maybe)
11709 (org-table-next-row))
11711 (defun orgtbl-self-insert-command (N)
11712 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11713 If the cursor is in a table looking at whitespace, the whitespace is
11714 overwritten, and the table is not marked as requiring realignment."
11715 (interactive "p")
11716 (if (and (org-at-table-p)
11718 (and org-table-auto-blank-field
11719 (member last-command
11720 '(orgtbl-hijacker-command-100
11721 orgtbl-hijacker-command-101
11722 orgtbl-hijacker-command-102
11723 orgtbl-hijacker-command-103
11724 orgtbl-hijacker-command-104
11725 orgtbl-hijacker-command-105))
11726 (org-table-blank-field))
11728 (eq N 1)
11729 (looking-at "[^|\n]* +|"))
11730 (let (org-table-may-need-update)
11731 (goto-char (1- (match-end 0)))
11732 (delete-backward-char 1)
11733 (goto-char (match-beginning 0))
11734 (self-insert-command N))
11735 (setq org-table-may-need-update t)
11736 (let (orgtbl-mode)
11737 (call-interactively (key-binding (vector last-input-event))))))
11739 (defun org-force-self-insert (N)
11740 "Needed to enforce self-insert under remapping."
11741 (interactive "p")
11742 (self-insert-command N))
11744 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11745 "Regula expression matching exponentials as produced by calc.")
11747 (defvar org-table-clean-did-remove-column nil)
11749 (defun orgtbl-export (table target)
11750 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11751 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11752 org-table-last-alignment org-table-last-column-widths
11753 maxcol column)
11754 (if (not (fboundp func))
11755 (error "Cannot export orgtbl table to %s" target))
11756 (setq lines (org-table-clean-before-export lines))
11757 (setq table
11758 (mapcar
11759 (lambda (x)
11760 (if (string-match org-table-hline-regexp x)
11761 'hline
11762 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11763 lines))
11764 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11765 table)))
11766 (loop for i from (1- maxcol) downto 0 do
11767 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11768 (setq column (delq nil column))
11769 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11770 (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))
11771 (funcall func table nil)))
11773 (defun orgtbl-send-table (&optional maybe)
11774 "Send a tranformed version of this table to the receiver position.
11775 With argument MAYBE, fail quietly if no transformation is defined for
11776 this table."
11777 (interactive)
11778 (catch 'exit
11779 (unless (org-at-table-p) (error "Not at a table"))
11780 ;; when non-interactive, we assume align has just happened.
11781 (when (interactive-p) (org-table-align))
11782 (save-excursion
11783 (goto-char (org-table-begin))
11784 (beginning-of-line 0)
11785 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11786 (if maybe
11787 (throw 'exit nil)
11788 (error "Don't know how to transform this table."))))
11789 (let* ((name (match-string 1))
11791 (transform (intern (match-string 2)))
11792 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11793 (skip (plist-get params :skip))
11794 (skipcols (plist-get params :skipcols))
11795 (txt (buffer-substring-no-properties
11796 (org-table-begin) (org-table-end)))
11797 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11798 (lines (org-table-clean-before-export lines))
11799 (i0 (if org-table-clean-did-remove-column 2 1))
11800 (table (mapcar
11801 (lambda (x)
11802 (if (string-match org-table-hline-regexp x)
11803 'hline
11804 (org-remove-by-index
11805 (org-split-string (org-trim x) "\\s-*|\\s-*")
11806 skipcols i0)))
11807 lines))
11808 (fun (if (= i0 2) 'cdr 'identity))
11809 (org-table-last-alignment
11810 (org-remove-by-index (funcall fun org-table-last-alignment)
11811 skipcols i0))
11812 (org-table-last-column-widths
11813 (org-remove-by-index (funcall fun org-table-last-column-widths)
11814 skipcols i0)))
11816 (unless (fboundp transform)
11817 (error "No such transformation function %s" transform))
11818 (setq txt (funcall transform table params))
11819 ;; Find the insertion place
11820 (save-excursion
11821 (goto-char (point-min))
11822 (unless (re-search-forward
11823 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11824 (error "Don't know where to insert translated table"))
11825 (goto-char (match-beginning 0))
11826 (beginning-of-line 2)
11827 (setq beg (point))
11828 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11829 (error "Cannot find end of insertion region"))
11830 (beginning-of-line 1)
11831 (delete-region beg (point))
11832 (goto-char beg)
11833 (insert txt "\n"))
11834 (message "Table converted and installed at receiver location"))))
11836 (defun org-remove-by-index (list indices &optional i0)
11837 "Remove the elements in LIST with indices in INDICES.
11838 First element has index 0, or I0 if given."
11839 (if (not indices)
11840 list
11841 (if (integerp indices) (setq indices (list indices)))
11842 (setq i0 (1- (or i0 0)))
11843 (delq :rm (mapcar (lambda (x)
11844 (setq i0 (1+ i0))
11845 (if (memq i0 indices) :rm x))
11846 list))))
11848 (defun orgtbl-toggle-comment ()
11849 "Comment or uncomment the orgtbl at point."
11850 (interactive)
11851 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11852 (re2 (concat "^" orgtbl-line-start-regexp))
11853 (commented (save-excursion (beginning-of-line 1)
11854 (cond ((looking-at re1) t)
11855 ((looking-at re2) nil)
11856 (t (error "Not at an org table")))))
11857 (re (if commented re1 re2))
11858 beg end)
11859 (save-excursion
11860 (beginning-of-line 1)
11861 (while (looking-at re) (beginning-of-line 0))
11862 (beginning-of-line 2)
11863 (setq beg (point))
11864 (while (looking-at re) (beginning-of-line 2))
11865 (setq end (point)))
11866 (comment-region beg end (if commented '(4) nil))))
11868 (defun orgtbl-insert-radio-table ()
11869 "Insert a radio table template appropriate for this major mode."
11870 (interactive)
11871 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11872 (txt (nth 1 e))
11873 name pos)
11874 (unless e (error "No radio table setup defined for %s" major-mode))
11875 (setq name (read-string "Table name: "))
11876 (while (string-match "%n" txt)
11877 (setq txt (replace-match name t t txt)))
11878 (or (bolp) (insert "\n"))
11879 (setq pos (point))
11880 (insert txt)
11881 (goto-char pos)))
11883 (defun org-get-param (params header i sym &optional hsym)
11884 "Get parameter value for symbol SYM.
11885 If this is a header line, actually get the value for the symbol with an
11886 additional \"h\" inserted after the colon.
11887 If the value is a protperty list, get the element for the current column.
11888 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11889 (let ((val (plist-get params sym)))
11890 (and hsym header (setq val (or (plist-get params hsym) val)))
11891 (if (consp val) (plist-get val i) val)))
11893 (defun orgtbl-to-generic (table params)
11894 "Convert the orgtbl-mode TABLE to some other format.
11895 This generic routine can be used for many standard cases.
11896 TABLE is a list, each entry either the symbol `hline' for a horizontal
11897 separator line, or a list of fields for that line.
11898 PARAMS is a property list of parameters that can influence the conversion.
11899 For the generic converter, some parameters are obligatory: You need to
11900 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11901 :splice, you must have :tstart and :tend.
11903 Valid parameters are
11905 :tstart String to start the table. Ignored when :splice is t.
11906 :tend String to end the table. Ignored when :splice is t.
11908 :splice When set to t, return only table body lines, don't wrap
11909 them into :tstart and :tend. Default is nil.
11911 :hline String to be inserted on horizontal separation lines.
11912 May be nil to ignore hlines.
11914 :lstart String to start a new table line.
11915 :lend String to end a table line
11916 :sep Separator between two fields
11917 :lfmt Format for entire line, with enough %s to capture all fields.
11918 If this is present, :lstart, :lend, and :sep are ignored.
11919 :fmt A format to be used to wrap the field, should contain
11920 %s for the original field value. For example, to wrap
11921 everything in dollars, you could use :fmt \"$%s$\".
11922 This may also be a property list with column numbers and
11923 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11925 :hlstart :hlend :hlsep :hlfmt :hfmt
11926 Same as above, specific for the header lines in the table.
11927 All lines before the first hline are treated as header.
11928 If any of these is not present, the data line value is used.
11930 :efmt Use this format to print numbers with exponentials.
11931 The format should have %s twice for inserting mantissa
11932 and exponent, for example \"%s\\\\times10^{%s}\". This
11933 may also be a property list with column numbers and
11934 formats. :fmt will still be applied after :efmt.
11936 In addition to this, the parameters :skip and :skipcols are always handled
11937 directly by `orgtbl-send-table'. See manual."
11938 (interactive)
11939 (let* ((p params)
11940 (splicep (plist-get p :splice))
11941 (hline (plist-get p :hline))
11942 rtn line i fm efm lfmt h)
11944 ;; Do we have a header?
11945 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11946 (setq h t))
11948 ;; Put header
11949 (unless splicep
11950 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11952 ;; Now loop over all lines
11953 (while (setq line (pop table))
11954 (if (eq line 'hline)
11955 ;; A horizontal separator line
11956 (progn (if hline (push hline rtn))
11957 (setq h nil)) ; no longer in header
11958 ;; A normal line. Convert the fields, push line onto the result list
11959 (setq i 0)
11960 (setq line
11961 (mapcar
11962 (lambda (f)
11963 (setq i (1+ i)
11964 fm (org-get-param p h i :fmt :hfmt)
11965 efm (org-get-param p h i :efmt))
11966 (if (and efm (string-match orgtbl-exp-regexp f))
11967 (setq f (format
11968 efm (match-string 1 f) (match-string 2 f))))
11969 (if fm (setq f (format fm f)))
11971 line))
11972 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11973 (push (apply 'format lfmt line) rtn)
11974 (push (concat
11975 (org-get-param p h i :lstart :hlstart)
11976 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11977 (org-get-param p h i :lend :hlend))
11978 rtn))))
11980 (unless splicep
11981 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11983 (mapconcat 'identity (nreverse rtn) "\n")))
11985 (defun orgtbl-to-latex (table params)
11986 "Convert the orgtbl-mode TABLE to LaTeX.
11987 TABLE is a list, each entry either the symbol `hline' for a horizontal
11988 separator line, or a list of fields for that line.
11989 PARAMS is a property list of parameters that can influence the conversion.
11990 Supports all parameters from `orgtbl-to-generic'. Most important for
11991 LaTeX are:
11993 :splice When set to t, return only table body lines, don't wrap
11994 them into a tabular environment. Default is nil.
11996 :fmt A format to be used to wrap the field, should contain %s for the
11997 original field value. For example, to wrap everything in dollars,
11998 use :fmt \"$%s$\". This may also be a property list with column
11999 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
12001 :efmt Format for transforming numbers with exponentials. The format
12002 should have %s twice for inserting mantissa and exponent, for
12003 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
12004 This may also be a property list with column numbers and formats.
12006 The general parameters :skip and :skipcols have already been applied when
12007 this function is called."
12008 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12009 org-table-last-alignment ""))
12010 (params2
12011 (list
12012 :tstart (concat "\\begin{tabular}{" alignment "}")
12013 :tend "\\end{tabular}"
12014 :lstart "" :lend " \\\\" :sep " & "
12015 :efmt "%s\\,(%s)" :hline "\\hline")))
12016 (orgtbl-to-generic table (org-combine-plists params2 params))))
12018 (defun orgtbl-to-html (table params)
12019 "Convert the orgtbl-mode TABLE to LaTeX.
12020 TABLE is a list, each entry either the symbol `hline' for a horizontal
12021 separator line, or a list of fields for that line.
12022 PARAMS is a property list of parameters that can influence the conversion.
12023 Currently this function recognizes the following parameters:
12025 :splice When set to t, return only table body lines, don't wrap
12026 them into a <table> environment. Default is nil.
12028 The general parameters :skip and :skipcols have already been applied when
12029 this function is called. The function does *not* use `orgtbl-to-generic',
12030 so you cannot specify parameters for it."
12031 (let* ((splicep (plist-get params :splice))
12032 html)
12033 ;; Just call the formatter we already have
12034 ;; We need to make text lines for it, so put the fields back together.
12035 (setq html (org-format-org-table-html
12036 (mapcar
12037 (lambda (x)
12038 (if (eq x 'hline)
12039 "|----+----|"
12040 (concat "| " (mapconcat 'identity x " | ") " |")))
12041 table)
12042 splicep))
12043 (if (string-match "\n+\\'" html)
12044 (setq html (replace-match "" t t html)))
12045 html))
12047 (defun orgtbl-to-texinfo (table params)
12048 "Convert the orgtbl-mode TABLE to TeXInfo.
12049 TABLE is a list, each entry either the symbol `hline' for a horizontal
12050 separator line, or a list of fields for that line.
12051 PARAMS is a property list of parameters that can influence the conversion.
12052 Supports all parameters from `orgtbl-to-generic'. Most important for
12053 TeXInfo are:
12055 :splice nil/t When set to t, return only table body lines, don't wrap
12056 them into a multitable environment. Default is nil.
12058 :fmt fmt A format to be used to wrap the field, should contain
12059 %s for the original field value. For example, to wrap
12060 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12061 This may also be a property list with column numbers and
12062 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12064 :cf \"f1 f2..\" The column fractions for the table. By default these
12065 are computed automatically from the width of the columns
12066 under org-mode.
12068 The general parameters :skip and :skipcols have already been applied when
12069 this function is called."
12070 (let* ((total (float (apply '+ org-table-last-column-widths)))
12071 (colfrac (or (plist-get params :cf)
12072 (mapconcat
12073 (lambda (x) (format "%.3f" (/ (float x) total)))
12074 org-table-last-column-widths " ")))
12075 (params2
12076 (list
12077 :tstart (concat "@multitable @columnfractions " colfrac)
12078 :tend "@end multitable"
12079 :lstart "@item " :lend "" :sep " @tab "
12080 :hlstart "@headitem ")))
12081 (orgtbl-to-generic table (org-combine-plists params2 params))))
12083 ;;;; Link Stuff
12085 ;;; Link abbreviations
12087 (defun org-link-expand-abbrev (link)
12088 "Apply replacements as defined in `org-link-abbrev-alist."
12089 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12090 (let* ((key (match-string 1 link))
12091 (as (or (assoc key org-link-abbrev-alist-local)
12092 (assoc key org-link-abbrev-alist)))
12093 (tag (and (match-end 2) (match-string 3 link)))
12094 rpl)
12095 (if (not as)
12096 link
12097 (setq rpl (cdr as))
12098 (cond
12099 ((symbolp rpl) (funcall rpl tag))
12100 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12101 (t (concat rpl tag)))))
12102 link))
12104 ;;; Storing and inserting links
12106 (defvar org-insert-link-history nil
12107 "Minibuffer history for links inserted with `org-insert-link'.")
12109 (defvar org-stored-links nil
12110 "Contains the links stored with `org-store-link'.")
12112 (defvar org-store-link-plist nil
12113 "Plist with info about the most recently link created with `org-store-link'.")
12115 (defvar org-link-protocols nil
12116 "Link protocols added to Org-mode using `org-add-link-type'.")
12118 (defvar org-store-link-functions nil
12119 "List of functions that are called to create and store a link.
12120 Each function will be called in turn until one returns a non-nil
12121 value. Each function should check if it is responsible for creating
12122 this link (for example by looking at the major mode).
12123 If not, it must exit and return nil.
12124 If yes, it should return a non-nil value after a calling
12125 `org-store-link-props' with a list of properties and values.
12126 Special properties are:
12128 :type The link prefix. like \"http\". This must be given.
12129 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12130 This is obligatory as well.
12131 :description Optional default description for the second pair
12132 of brackets in an Org-mode link. The user can still change
12133 this when inserting this link into an Org-mode buffer.
12135 In addition to these, any additional properties can be specified
12136 and then used in remember templates.")
12138 (defun org-add-link-type (type &optional follow publish)
12139 "Add TYPE to the list of `org-link-types'.
12140 Re-compute all regular expressions depending on `org-link-types'
12141 FOLLOW and PUBLISH are two functions. Both take the link path as
12142 an argument.
12143 FOLLOW should do whatever is necessary to follow the link, for example
12144 to find a file or display a mail message.
12146 PUBLISH takes the path and retuns the string that should be used when
12147 this document is published. FIMXE: This is actually not yet implemented."
12148 (add-to-list 'org-link-types type t)
12149 (org-make-link-regexps)
12150 (add-to-list 'org-link-protocols
12151 (list type follow publish)))
12153 (defun org-add-agenda-custom-command (entry)
12154 "Replace or add a command in `org-agenda-custom-commands'.
12155 This is mostly for hacking and trying a new command - once the command
12156 works you probably want to add it to `org-agenda-custom-commands' for good."
12157 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12158 (if ass
12159 (setcdr ass (cdr entry))
12160 (push entry org-agenda-custom-commands))))
12162 ;;;###autoload
12163 (defun org-store-link (arg)
12164 "\\<org-mode-map>Store an org-link to the current location.
12165 This link is added to `org-stored-links' and can later be inserted
12166 into an org-buffer with \\[org-insert-link].
12168 For some link types, a prefix arg is interpreted:
12169 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12170 For file links, arg negates `org-context-in-file-links'."
12171 (interactive "P")
12172 (setq org-store-link-plist nil) ; reset
12173 (let (link cpltxt desc description search txt)
12174 (cond
12176 ((run-hook-with-args-until-success 'org-store-link-functions)
12177 (setq link (plist-get org-store-link-plist :link)
12178 desc (or (plist-get org-store-link-plist :description) link)))
12180 ((eq major-mode 'bbdb-mode)
12181 (let ((name (bbdb-record-name (bbdb-current-record)))
12182 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12183 (setq cpltxt (concat "bbdb:" (or name company))
12184 link (org-make-link cpltxt))
12185 (org-store-link-props :type "bbdb" :name name :company company)))
12187 ((eq major-mode 'Info-mode)
12188 (setq link (org-make-link "info:"
12189 (file-name-nondirectory Info-current-file)
12190 ":" Info-current-node))
12191 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12192 ":" Info-current-node))
12193 (org-store-link-props :type "info" :file Info-current-file
12194 :node Info-current-node))
12196 ((eq major-mode 'calendar-mode)
12197 (let ((cd (calendar-cursor-to-date)))
12198 (setq link
12199 (format-time-string
12200 (car org-time-stamp-formats)
12201 (apply 'encode-time
12202 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12203 nil nil nil))))
12204 (org-store-link-props :type "calendar" :date cd)))
12206 ((or (eq major-mode 'vm-summary-mode)
12207 (eq major-mode 'vm-presentation-mode))
12208 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12209 (vm-follow-summary-cursor)
12210 (save-excursion
12211 (vm-select-folder-buffer)
12212 (let* ((message (car vm-message-pointer))
12213 (folder buffer-file-name)
12214 (subject (vm-su-subject message))
12215 (to (vm-get-header-contents message "To"))
12216 (from (vm-get-header-contents message "From"))
12217 (message-id (vm-su-message-id message)))
12218 (org-store-link-props :type "vm" :from from :to to :subject subject
12219 :message-id message-id)
12220 (setq message-id (org-remove-angle-brackets message-id))
12221 (setq folder (abbreviate-file-name folder))
12222 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12223 folder)
12224 (setq folder (replace-match "" t t folder)))
12225 (setq cpltxt (org-email-link-description))
12226 (setq link (org-make-link "vm:" folder "#" message-id)))))
12228 ((eq major-mode 'wl-summary-mode)
12229 (let* ((msgnum (wl-summary-message-number))
12230 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12231 msgnum 'message-id))
12232 (wl-message-entity
12233 (if (fboundp 'elmo-message-entity)
12234 (elmo-message-entity
12235 wl-summary-buffer-elmo-folder msgnum)
12236 (elmo-msgdb-overview-get-entity
12237 msgnum (wl-summary-buffer-msgdb))))
12238 (from (wl-summary-line-from))
12239 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12240 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12241 (wl-summary-line-subject))))
12242 (org-store-link-props :type "wl" :from from :to to
12243 :subject subject :message-id message-id)
12244 (setq message-id (org-remove-angle-brackets message-id))
12245 (setq cpltxt (org-email-link-description))
12246 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12247 "#" message-id))))
12249 ((or (equal major-mode 'mh-folder-mode)
12250 (equal major-mode 'mh-show-mode))
12251 (let ((from (org-mhe-get-header "From:"))
12252 (to (org-mhe-get-header "To:"))
12253 (message-id (org-mhe-get-header "Message-Id:"))
12254 (subject (org-mhe-get-header "Subject:")))
12255 (org-store-link-props :type "mh" :from from :to to
12256 :subject subject :message-id message-id)
12257 (setq cpltxt (org-email-link-description))
12258 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12259 (org-remove-angle-brackets message-id)))))
12261 ((or (eq major-mode 'rmail-mode)
12262 (eq major-mode 'rmail-summary-mode))
12263 (save-window-excursion
12264 (save-restriction
12265 (when (eq major-mode 'rmail-summary-mode)
12266 (rmail-show-message rmail-current-message))
12267 (rmail-narrow-to-non-pruned-header)
12268 (let ((folder buffer-file-name)
12269 (message-id (mail-fetch-field "message-id"))
12270 (from (mail-fetch-field "from"))
12271 (to (mail-fetch-field "to"))
12272 (subject (mail-fetch-field "subject")))
12273 (org-store-link-props
12274 :type "rmail" :from from :to to
12275 :subject subject :message-id message-id)
12276 (setq message-id (org-remove-angle-brackets message-id))
12277 (setq cpltxt (org-email-link-description))
12278 (setq link (org-make-link "rmail:" folder "#" message-id)))
12279 (rmail-show-message rmail-current-message))))
12281 ((eq major-mode 'gnus-group-mode)
12282 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12283 (gnus-group-group-name)) ; version
12284 ((fboundp 'gnus-group-name)
12285 (gnus-group-name))
12286 (t "???"))))
12287 (unless group (error "Not on a group"))
12288 (org-store-link-props :type "gnus" :group group)
12289 (setq cpltxt (concat
12290 (if (org-xor arg org-usenet-links-prefer-google)
12291 "http://groups.google.com/groups?group="
12292 "gnus:")
12293 group)
12294 link (org-make-link cpltxt))))
12296 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12297 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12298 (let* ((group gnus-newsgroup-name)
12299 (article (gnus-summary-article-number))
12300 (header (gnus-summary-article-header article))
12301 (from (mail-header-from header))
12302 (message-id (mail-header-id header))
12303 (date (mail-header-date header))
12304 (subject (gnus-summary-subject-string)))
12305 (org-store-link-props :type "gnus" :from from :subject subject
12306 :message-id message-id :group group)
12307 (setq cpltxt (org-email-link-description))
12308 (if (org-xor arg org-usenet-links-prefer-google)
12309 (setq link
12310 (concat
12311 cpltxt "\n "
12312 (format "http://groups.google.com/groups?as_umsgid=%s"
12313 (org-fixup-message-id-for-http message-id))))
12314 (setq link (org-make-link "gnus:" group
12315 "#" (number-to-string article))))))
12317 ((eq major-mode 'w3-mode)
12318 (setq cpltxt (url-view-url t)
12319 link (org-make-link cpltxt))
12320 (org-store-link-props :type "w3" :url (url-view-url t)))
12322 ((eq major-mode 'w3m-mode)
12323 (setq cpltxt (or w3m-current-title w3m-current-url)
12324 link (org-make-link w3m-current-url))
12325 (org-store-link-props :type "w3m" :url (url-view-url t)))
12327 ((setq search (run-hook-with-args-until-success
12328 'org-create-file-search-functions))
12329 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12330 "::" search))
12331 (setq cpltxt (or description link)))
12333 ((eq major-mode 'image-mode)
12334 (setq cpltxt (concat "file:"
12335 (abbreviate-file-name buffer-file-name))
12336 link (org-make-link cpltxt))
12337 (org-store-link-props :type "image" :file buffer-file-name))
12339 ((eq major-mode 'dired-mode)
12340 ;; link to the file in the current line
12341 (setq cpltxt (concat "file:"
12342 (abbreviate-file-name
12343 (expand-file-name
12344 (dired-get-filename nil t))))
12345 link (org-make-link cpltxt)))
12347 ((and buffer-file-name (org-mode-p))
12348 ;; Just link to current headline
12349 (setq cpltxt (concat "file:"
12350 (abbreviate-file-name buffer-file-name)))
12351 ;; Add a context search string
12352 (when (org-xor org-context-in-file-links arg)
12353 ;; Check if we are on a target
12354 (if (org-in-regexp "<<\\(.*?\\)>>")
12355 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12356 (setq txt (cond
12357 ((org-on-heading-p) nil)
12358 ((org-region-active-p)
12359 (buffer-substring (region-beginning) (region-end)))
12360 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12361 (when (or (null txt) (string-match "\\S-" txt))
12362 (setq cpltxt
12363 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12364 desc "NONE"))))
12365 (if (string-match "::\\'" cpltxt)
12366 (setq cpltxt (substring cpltxt 0 -2)))
12367 (setq link (org-make-link cpltxt)))
12369 ((buffer-file-name (buffer-base-buffer))
12370 ;; Just link to this file here.
12371 (setq cpltxt (concat "file:"
12372 (abbreviate-file-name
12373 (buffer-file-name (buffer-base-buffer)))))
12374 ;; Add a context string
12375 (when (org-xor org-context-in-file-links arg)
12376 (setq txt (if (org-region-active-p)
12377 (buffer-substring (region-beginning) (region-end))
12378 (buffer-substring (point-at-bol) (point-at-eol))))
12379 ;; Only use search option if there is some text.
12380 (when (string-match "\\S-" txt)
12381 (setq cpltxt
12382 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12383 desc "NONE")))
12384 (setq link (org-make-link cpltxt)))
12386 ((interactive-p)
12387 (error "Cannot link to a buffer which is not visiting a file"))
12389 (t (setq link nil)))
12391 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12392 (setq link (or link cpltxt)
12393 desc (or desc cpltxt))
12394 (if (equal desc "NONE") (setq desc nil))
12396 (if (and (interactive-p) link)
12397 (progn
12398 (setq org-stored-links
12399 (cons (list link desc) org-stored-links))
12400 (message "Stored: %s" (or desc link)))
12401 (and link (org-make-link-string link desc)))))
12403 (defun org-store-link-props (&rest plist)
12404 "Store link properties, extract names and addresses."
12405 (let (x adr)
12406 (when (setq x (plist-get plist :from))
12407 (setq adr (mail-extract-address-components x))
12408 (plist-put plist :fromname (car adr))
12409 (plist-put plist :fromaddress (nth 1 adr)))
12410 (when (setq x (plist-get plist :to))
12411 (setq adr (mail-extract-address-components x))
12412 (plist-put plist :toname (car adr))
12413 (plist-put plist :toaddress (nth 1 adr))))
12414 (let ((from (plist-get plist :from))
12415 (to (plist-get plist :to)))
12416 (when (and from to org-from-is-user-regexp)
12417 (plist-put plist :fromto
12418 (if (string-match org-from-is-user-regexp from)
12419 (concat "to %t")
12420 (concat "from %f")))))
12421 (setq org-store-link-plist plist))
12423 (defun org-email-link-description (&optional fmt)
12424 "Return the description part of an email link.
12425 This takes information from `org-store-link-plist' and formats it
12426 according to FMT (default from `org-email-link-description-format')."
12427 (setq fmt (or fmt org-email-link-description-format))
12428 (let* ((p org-store-link-plist)
12429 (to (plist-get p :toaddress))
12430 (from (plist-get p :fromaddress))
12431 (table
12432 (list
12433 (cons "%c" (plist-get p :fromto))
12434 (cons "%F" (plist-get p :from))
12435 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12436 (cons "%T" (plist-get p :to))
12437 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12438 (cons "%s" (plist-get p :subject))
12439 (cons "%m" (plist-get p :message-id)))))
12440 (when (string-match "%c" fmt)
12441 ;; Check if the user wrote this message
12442 (if (and org-from-is-user-regexp from to
12443 (save-match-data (string-match org-from-is-user-regexp from)))
12444 (setq fmt (replace-match "to %t" t t fmt))
12445 (setq fmt (replace-match "from %f" t t fmt))))
12446 (org-replace-escapes fmt table)))
12448 (defun org-make-org-heading-search-string (&optional string heading)
12449 "Make search string for STRING or current headline."
12450 (interactive)
12451 (let ((s (or string (org-get-heading))))
12452 (unless (and string (not heading))
12453 ;; We are using a headline, clean up garbage in there.
12454 (if (string-match org-todo-regexp s)
12455 (setq s (replace-match "" t t s)))
12456 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12457 (setq s (replace-match "" t t s)))
12458 (setq s (org-trim s))
12459 (if (string-match (concat "^\\(" org-quote-string "\\|"
12460 org-comment-string "\\)") s)
12461 (setq s (replace-match "" t t s)))
12462 (while (string-match org-ts-regexp s)
12463 (setq s (replace-match "" t t s))))
12464 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12465 (setq s (replace-match " " t t s)))
12466 (or string (setq s (concat "*" s))) ; Add * for headlines
12467 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12469 (defun org-make-link (&rest strings)
12470 "Concatenate STRINGS."
12471 (apply 'concat strings))
12473 (defun org-make-link-string (link &optional description)
12474 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12475 (unless (string-match "\\S-" link)
12476 (error "Empty link"))
12477 (when (stringp description)
12478 ;; Remove brackets from the description, they are fatal.
12479 (while (string-match "\\[" description)
12480 (setq description (replace-match "{" t t description)))
12481 (while (string-match "\\]" description)
12482 (setq description (replace-match "}" t t description))))
12483 (when (equal (org-link-escape link) description)
12484 ;; No description needed, it is identical
12485 (setq description nil))
12486 (when (and (not description)
12487 (not (equal link (org-link-escape link))))
12488 (setq description link))
12489 (concat "[[" (org-link-escape link) "]"
12490 (if description (concat "[" description "]") "")
12491 "]"))
12493 (defconst org-link-escape-chars
12494 '((?\ . "%20")
12495 (?\[ . "%5B")
12496 (?\] . "%5D")
12497 (?\340 . "%E0") ; `a
12498 (?\342 . "%E2") ; ^a
12499 (?\347 . "%E7") ; ,c
12500 (?\350 . "%E8") ; `e
12501 (?\351 . "%E9") ; 'e
12502 (?\352 . "%EA") ; ^e
12503 (?\356 . "%EE") ; ^i
12504 (?\364 . "%F4") ; ^o
12505 (?\371 . "%F9") ; `u
12506 (?\373 . "%FB") ; ^u
12507 (?\; . "%3B")
12508 (?? . "%3F")
12509 (?= . "%3D")
12510 (?+ . "%2B")
12512 "Association list of escapes for some characters problematic in links.
12513 This is the list that is used for internal purposes.")
12515 (defconst org-link-escape-chars-browser
12516 '((?\ . "%20")) ; 32 for the SPC char
12517 "Association list of escapes for some characters problematic in links.
12518 This is the list that is used before handing over to the browser.")
12520 (defun org-link-escape (text &optional table)
12521 "Escape charaters in TEXT that are problematic for links."
12522 (setq table (or table org-link-escape-chars))
12523 (when text
12524 (let ((re (mapconcat (lambda (x) (regexp-quote
12525 (char-to-string (car x))))
12526 table "\\|")))
12527 (while (string-match re text)
12528 (setq text
12529 (replace-match
12530 (cdr (assoc (string-to-char (match-string 0 text))
12531 table))
12532 t t text)))
12533 text)))
12535 (defun org-link-unescape (text &optional table)
12536 "Reverse the action of `org-link-escape'."
12537 (setq table (or table org-link-escape-chars))
12538 (when text
12539 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12540 table "\\|")))
12541 (while (string-match re text)
12542 (setq text
12543 (replace-match
12544 (char-to-string (car (rassoc (match-string 0 text) table)))
12545 t t text)))
12546 text)))
12548 (defun org-xor (a b)
12549 "Exclusive or."
12550 (if a (not b) b))
12552 (defun org-get-header (header)
12553 "Find a header field in the current buffer."
12554 (save-excursion
12555 (goto-char (point-min))
12556 (let ((case-fold-search t) s)
12557 (cond
12558 ((eq header 'from)
12559 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12560 (setq s (match-string 1)))
12561 (while (string-match "\"" s)
12562 (setq s (replace-match "" t t s)))
12563 (if (string-match "[<(].*" s)
12564 (setq s (replace-match "" t t s))))
12565 ((eq header 'message-id)
12566 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12567 (setq s (match-string 1))))
12568 ((eq header 'subject)
12569 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12570 (setq s (match-string 1)))))
12571 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12572 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12573 s)))
12576 (defun org-fixup-message-id-for-http (s)
12577 "Replace special characters in a message id, so it can be used in an http query."
12578 (while (string-match "<" s)
12579 (setq s (replace-match "%3C" t t s)))
12580 (while (string-match ">" s)
12581 (setq s (replace-match "%3E" t t s)))
12582 (while (string-match "@" s)
12583 (setq s (replace-match "%40" t t s)))
12586 ;;;###autoload
12587 (defun org-insert-link-global ()
12588 "Insert a link like Org-mode does.
12589 This command can be called in any mode to insert a link in Org-mode syntax."
12590 (interactive)
12591 (org-run-like-in-org-mode 'org-insert-link))
12593 (defun org-insert-link (&optional complete-file)
12594 "Insert a link. At the prompt, enter the link.
12596 Completion can be used to select a link previously stored with
12597 `org-store-link'. When the empty string is entered (i.e. if you just
12598 press RET at the prompt), the link defaults to the most recently
12599 stored link. As SPC triggers completion in the minibuffer, you need to
12600 use M-SPC or C-q SPC to force the insertion of a space character.
12602 You will also be prompted for a description, and if one is given, it will
12603 be displayed in the buffer instead of the link.
12605 If there is already a link at point, this command will allow you to edit link
12606 and description parts.
12608 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12609 selected using completion. The path to the file will be relative to
12610 the current directory if the file is in the current directory or a
12611 subdirectory. Otherwise, the link will be the absolute path as
12612 completed in the minibuffer (i.e. normally ~/path/to/file).
12614 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12615 is in the current directory or below.
12616 With three \\[universal-argument] prefixes, negate the meaning of
12617 `org-keep-stored-link-after-insertion'."
12618 (interactive "P")
12619 (let* ((wcf (current-window-configuration))
12620 (region (if (org-region-active-p)
12621 (buffer-substring (region-beginning) (region-end))))
12622 (remove (and region (list (region-beginning) (region-end))))
12623 (desc region)
12624 tmphist ; byte-compile incorrectly complains about this
12625 link entry file)
12626 (cond
12627 ((org-in-regexp org-bracket-link-regexp 1)
12628 ;; We do have a link at point, and we are going to edit it.
12629 (setq remove (list (match-beginning 0) (match-end 0)))
12630 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12631 (setq link (read-string "Link: "
12632 (org-link-unescape
12633 (org-match-string-no-properties 1)))))
12634 ((or (org-in-regexp org-angle-link-re)
12635 (org-in-regexp org-plain-link-re))
12636 ;; Convert to bracket link
12637 (setq remove (list (match-beginning 0) (match-end 0))
12638 link (read-string "Link: "
12639 (org-remove-angle-brackets (match-string 0)))))
12640 ((equal complete-file '(4))
12641 ;; Completing read for file names.
12642 (setq file (read-file-name "File: "))
12643 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12644 (pwd1 (file-name-as-directory (abbreviate-file-name
12645 (expand-file-name ".")))))
12646 (cond
12647 ((equal complete-file '(16))
12648 (setq link (org-make-link
12649 "file:"
12650 (abbreviate-file-name (expand-file-name file)))))
12651 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12652 (setq link (org-make-link "file:" (match-string 1 file))))
12653 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12654 (expand-file-name file))
12655 (setq link (org-make-link
12656 "file:" (match-string 1 (expand-file-name file)))))
12657 (t (setq link (org-make-link "file:" file))))))
12659 ;; Read link, with completion for stored links.
12660 (with-output-to-temp-buffer "*Org Links*"
12661 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12662 (when org-stored-links
12663 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12664 (princ (mapconcat
12665 (lambda (x)
12666 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12667 (reverse org-stored-links) "\n"))))
12668 (let ((cw (selected-window)))
12669 (select-window (get-buffer-window "*Org Links*"))
12670 (shrink-window-if-larger-than-buffer)
12671 (setq truncate-lines t)
12672 (select-window cw))
12673 ;; Fake a link history, containing the stored links.
12674 (setq tmphist (append (mapcar 'car org-stored-links)
12675 org-insert-link-history))
12676 (unwind-protect
12677 (setq link (org-completing-read
12678 "Link: "
12679 (append
12680 (mapcar (lambda (x) (list (concat (car x) ":")))
12681 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12682 (mapcar (lambda (x) (list (concat x ":")))
12683 org-link-types))
12684 nil nil nil
12685 'tmphist
12686 (or (car (car org-stored-links)))))
12687 (set-window-configuration wcf)
12688 (kill-buffer "*Org Links*"))
12689 (setq entry (assoc link org-stored-links))
12690 (or entry (push link org-insert-link-history))
12691 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12692 (not org-keep-stored-link-after-insertion))
12693 (setq org-stored-links (delq (assoc link org-stored-links)
12694 org-stored-links)))
12695 (setq desc (or desc (nth 1 entry)))))
12697 (if (string-match org-plain-link-re link)
12698 ;; URL-like link, normalize the use of angular brackets.
12699 (setq link (org-make-link (org-remove-angle-brackets link))))
12701 ;; Check if we are linking to the current file with a search option
12702 ;; If yes, simplify the link by using only the search option.
12703 (when (and buffer-file-name
12704 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12705 (let* ((path (match-string 1 link))
12706 (case-fold-search nil)
12707 (search (match-string 2 link)))
12708 (save-match-data
12709 (if (equal (file-truename buffer-file-name) (file-truename path))
12710 ;; We are linking to this same file, with a search option
12711 (setq link search)))))
12713 ;; Check if we can/should use a relative path. If yes, simplify the link
12714 (when (string-match "\\<file:\\(.*\\)" link)
12715 (let* ((path (match-string 1 link))
12716 (origpath path)
12717 (case-fold-search nil))
12718 (cond
12719 ((eq org-link-file-path-type 'absolute)
12720 (setq path (abbreviate-file-name (expand-file-name path))))
12721 ((eq org-link-file-path-type 'noabbrev)
12722 (setq path (expand-file-name path)))
12723 ((eq org-link-file-path-type 'relative)
12724 (setq path (file-relative-name path)))
12726 (save-match-data
12727 (if (string-match (concat "^" (regexp-quote
12728 (file-name-as-directory
12729 (expand-file-name "."))))
12730 (expand-file-name path))
12731 ;; We are linking a file with relative path name.
12732 (setq path (substring (expand-file-name path)
12733 (match-end 0)))))))
12734 (setq link (concat "file:" path))
12735 (if (equal desc origpath)
12736 (setq desc path))))
12738 (setq desc (read-string "Description: " desc))
12739 (unless (string-match "\\S-" desc) (setq desc nil))
12740 (if remove (apply 'delete-region remove))
12741 (insert (org-make-link-string link desc))))
12743 (defun org-completing-read (&rest args)
12744 (let ((minibuffer-local-completion-map
12745 (copy-keymap minibuffer-local-completion-map)))
12746 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12747 (apply 'completing-read args)))
12749 ;;; Opening/following a link
12750 (defvar org-link-search-failed nil)
12752 (defun org-next-link ()
12753 "Move forward to the next link.
12754 If the link is in hidden text, expose it."
12755 (interactive)
12756 (when (and org-link-search-failed (eq this-command last-command))
12757 (goto-char (point-min))
12758 (message "Link search wrapped back to beginning of buffer"))
12759 (setq org-link-search-failed nil)
12760 (let* ((pos (point))
12761 (ct (org-context))
12762 (a (assoc :link ct)))
12763 (if a (goto-char (nth 2 a)))
12764 (if (re-search-forward org-any-link-re nil t)
12765 (progn
12766 (goto-char (match-beginning 0))
12767 (if (org-invisible-p) (org-show-context)))
12768 (goto-char pos)
12769 (setq org-link-search-failed t)
12770 (error "No further link found"))))
12772 (defun org-previous-link ()
12773 "Move backward to the previous link.
12774 If the link is in hidden text, expose it."
12775 (interactive)
12776 (when (and org-link-search-failed (eq this-command last-command))
12777 (goto-char (point-max))
12778 (message "Link search wrapped back to end of buffer"))
12779 (setq org-link-search-failed nil)
12780 (let* ((pos (point))
12781 (ct (org-context))
12782 (a (assoc :link ct)))
12783 (if a (goto-char (nth 1 a)))
12784 (if (re-search-backward org-any-link-re nil t)
12785 (progn
12786 (goto-char (match-beginning 0))
12787 (if (org-invisible-p) (org-show-context)))
12788 (goto-char pos)
12789 (setq org-link-search-failed t)
12790 (error "No further link found"))))
12792 (defun org-find-file-at-mouse (ev)
12793 "Open file link or URL at mouse."
12794 (interactive "e")
12795 (mouse-set-point ev)
12796 (org-open-at-point 'in-emacs))
12798 (defun org-open-at-mouse (ev)
12799 "Open file link or URL at mouse."
12800 (interactive "e")
12801 (mouse-set-point ev)
12802 (org-open-at-point))
12804 (defvar org-window-config-before-follow-link nil
12805 "The window configuration before following a link.
12806 This is saved in case the need arises to restore it.")
12808 (defvar org-open-link-marker (make-marker)
12809 "Marker pointing to the location where `org-open-at-point; was called.")
12811 ;;;###autoload
12812 (defun org-open-at-point-global ()
12813 "Follow a link like Org-mode does.
12814 This command can be called in any mode to follow a link that has
12815 Org-mode syntax."
12816 (interactive)
12817 (org-run-like-in-org-mode 'org-open-at-point))
12819 (defun org-open-at-point (&optional in-emacs)
12820 "Open link at or after point.
12821 If there is no link at point, this function will search forward up to
12822 the end of the current subtree.
12823 Normally, files will be opened by an appropriate application. If the
12824 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12825 (interactive "P")
12826 (move-marker org-open-link-marker (point))
12827 (setq org-window-config-before-follow-link (current-window-configuration))
12828 (org-remove-occur-highlights nil nil t)
12829 (if (org-at-timestamp-p t)
12830 (org-follow-timestamp-link)
12831 (let (type path link line search (pos (point)))
12832 (catch 'match
12833 (save-excursion
12834 (skip-chars-forward "^]\n\r")
12835 (when (org-in-regexp org-bracket-link-regexp)
12836 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12837 (while (string-match " *\n *" link)
12838 (setq link (replace-match " " t t link)))
12839 (setq link (org-link-expand-abbrev link))
12840 (if (string-match org-link-re-with-space2 link)
12841 (setq type (match-string 1 link) path (match-string 2 link))
12842 (setq type "thisfile" path link))
12843 (throw 'match t)))
12845 (when (get-text-property (point) 'org-linked-text)
12846 (setq type "thisfile"
12847 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12848 (1+ (point)) (point))
12849 path (buffer-substring
12850 (previous-single-property-change pos 'org-linked-text)
12851 (next-single-property-change pos 'org-linked-text)))
12852 (throw 'match t))
12854 (save-excursion
12855 (when (or (org-in-regexp org-angle-link-re)
12856 (org-in-regexp org-plain-link-re))
12857 (setq type (match-string 1) path (match-string 2))
12858 (throw 'match t)))
12859 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12860 (setq type "tree-match"
12861 path (match-string 1))
12862 (throw 'match t))
12863 (save-excursion
12864 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12865 (setq type "tags"
12866 path (match-string 1))
12867 (while (string-match ":" path)
12868 (setq path (replace-match "+" t t path)))
12869 (throw 'match t))))
12870 (unless path
12871 (error "No link found"))
12872 ;; Remove any trailing spaces in path
12873 (if (string-match " +\\'" path)
12874 (setq path (replace-match "" t t path)))
12876 (cond
12878 ((assoc type org-link-protocols)
12879 (funcall (nth 1 (assoc type org-link-protocols)) path))
12881 ((equal type "mailto")
12882 (let ((cmd (car org-link-mailto-program))
12883 (args (cdr org-link-mailto-program)) args1
12884 (address path) (subject "") a)
12885 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12886 (setq address (match-string 1 path)
12887 subject (org-link-escape (match-string 2 path))))
12888 (while args
12889 (cond
12890 ((not (stringp (car args))) (push (pop args) args1))
12891 (t (setq a (pop args))
12892 (if (string-match "%a" a)
12893 (setq a (replace-match address t t a)))
12894 (if (string-match "%s" a)
12895 (setq a (replace-match subject t t a)))
12896 (push a args1))))
12897 (apply cmd (nreverse args1))))
12899 ((member type '("http" "https" "ftp" "news"))
12900 (browse-url (concat type ":" (org-link-escape
12901 path org-link-escape-chars-browser))))
12903 ((member type '("message"))
12904 (browse-url (concat type ":" path)))
12906 ((string= type "tags")
12907 (org-tags-view in-emacs path))
12908 ((string= type "thisfile")
12909 (if in-emacs
12910 (switch-to-buffer-other-window
12911 (org-get-buffer-for-internal-link (current-buffer)))
12912 (org-mark-ring-push))
12913 (let ((cmd `(org-link-search
12914 ,path
12915 ,(cond ((equal in-emacs '(4)) 'occur)
12916 ((equal in-emacs '(16)) 'org-occur)
12917 (t nil))
12918 ,pos)))
12919 (condition-case nil (eval cmd)
12920 (error (progn (widen) (eval cmd))))))
12922 ((string= type "tree-match")
12923 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12925 ((string= type "file")
12926 (if (string-match "::\\([0-9]+\\)\\'" path)
12927 (setq line (string-to-number (match-string 1 path))
12928 path (substring path 0 (match-beginning 0)))
12929 (if (string-match "::\\(.+\\)\\'" path)
12930 (setq search (match-string 1 path)
12931 path (substring path 0 (match-beginning 0)))))
12932 (if (string-match "[*?{]" (file-name-nondirectory path))
12933 (dired path)
12934 (org-open-file path in-emacs line search)))
12936 ((string= type "news")
12937 (org-follow-gnus-link path))
12939 ((string= type "bbdb")
12940 (org-follow-bbdb-link path))
12942 ((string= type "info")
12943 (org-follow-info-link path))
12945 ((string= type "gnus")
12946 (let (group article)
12947 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12948 (error "Error in Gnus link"))
12949 (setq group (match-string 1 path)
12950 article (match-string 3 path))
12951 (org-follow-gnus-link group article)))
12953 ((string= type "vm")
12954 (let (folder article)
12955 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12956 (error "Error in VM link"))
12957 (setq folder (match-string 1 path)
12958 article (match-string 3 path))
12959 ;; in-emacs is the prefix arg, will be interpreted as read-only
12960 (org-follow-vm-link folder article in-emacs)))
12962 ((string= type "wl")
12963 (let (folder article)
12964 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12965 (error "Error in Wanderlust link"))
12966 (setq folder (match-string 1 path)
12967 article (match-string 3 path))
12968 (org-follow-wl-link folder article)))
12970 ((string= type "mhe")
12971 (let (folder article)
12972 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12973 (error "Error in MHE link"))
12974 (setq folder (match-string 1 path)
12975 article (match-string 3 path))
12976 (org-follow-mhe-link folder article)))
12978 ((string= type "rmail")
12979 (let (folder article)
12980 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12981 (error "Error in RMAIL link"))
12982 (setq folder (match-string 1 path)
12983 article (match-string 3 path))
12984 (org-follow-rmail-link folder article)))
12986 ((string= type "shell")
12987 (let ((cmd path))
12988 (if (or (not org-confirm-shell-link-function)
12989 (funcall org-confirm-shell-link-function
12990 (format "Execute \"%s\" in shell? "
12991 (org-add-props cmd nil
12992 'face 'org-warning))))
12993 (progn
12994 (message "Executing %s" cmd)
12995 (shell-command cmd))
12996 (error "Abort"))))
12998 ((string= type "elisp")
12999 (let ((cmd path))
13000 (if (or (not org-confirm-elisp-link-function)
13001 (funcall org-confirm-elisp-link-function
13002 (format "Execute \"%s\" as elisp? "
13003 (org-add-props cmd nil
13004 'face 'org-warning))))
13005 (message "%s => %s" cmd (eval (read cmd)))
13006 (error "Abort"))))
13009 (browse-url-at-point)))))
13010 (move-marker org-open-link-marker nil)
13011 (run-hook-with-args 'org-follow-link-hook))
13013 ;;; File search
13015 (defvar org-create-file-search-functions nil
13016 "List of functions to construct the right search string for a file link.
13017 These functions are called in turn with point at the location to
13018 which the link should point.
13020 A function in the hook should first test if it would like to
13021 handle this file type, for example by checking the major-mode or
13022 the file extension. If it decides not to handle this file, it
13023 should just return nil to give other functions a chance. If it
13024 does handle the file, it must return the search string to be used
13025 when following the link. The search string will be part of the
13026 file link, given after a double colon, and `org-open-at-point'
13027 will automatically search for it. If special measures must be
13028 taken to make the search successful, another function should be
13029 added to the companion hook `org-execute-file-search-functions',
13030 which see.
13032 A function in this hook may also use `setq' to set the variable
13033 `description' to provide a suggestion for the descriptive text to
13034 be used for this link when it gets inserted into an Org-mode
13035 buffer with \\[org-insert-link].")
13037 (defvar org-execute-file-search-functions nil
13038 "List of functions to execute a file search triggered by a link.
13040 Functions added to this hook must accept a single argument, the
13041 search string that was part of the file link, the part after the
13042 double colon. The function must first check if it would like to
13043 handle this search, for example by checking the major-mode or the
13044 file extension. If it decides not to handle this search, it
13045 should just return nil to give other functions a chance. If it
13046 does handle the search, it must return a non-nil value to keep
13047 other functions from trying.
13049 Each function can access the current prefix argument through the
13050 variable `current-prefix-argument'. Note that a single prefix is
13051 used to force opening a link in Emacs, so it may be good to only
13052 use a numeric or double prefix to guide the search function.
13054 In case this is needed, a function in this hook can also restore
13055 the window configuration before `org-open-at-point' was called using:
13057 (set-window-configuration org-window-config-before-follow-link)")
13059 (defun org-link-search (s &optional type avoid-pos)
13060 "Search for a link search option.
13061 If S is surrounded by forward slashes, it is interpreted as a
13062 regular expression. In org-mode files, this will create an `org-occur'
13063 sparse tree. In ordinary files, `occur' will be used to list matches.
13064 If the current buffer is in `dired-mode', grep will be used to search
13065 in all files. If AVOID-POS is given, ignore matches near that position."
13066 (let ((case-fold-search t)
13067 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
13068 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
13069 (append '(("") (" ") ("\t") ("\n"))
13070 org-emphasis-alist)
13071 "\\|") "\\)"))
13072 (pos (point))
13073 (pre "") (post "")
13074 words re0 re1 re2 re3 re4 re5 re2a reall)
13075 (cond
13076 ;; First check if there are any special
13077 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13078 ;; Now try the builtin stuff
13079 ((save-excursion
13080 (goto-char (point-min))
13081 (and
13082 (re-search-forward
13083 (concat "<<" (regexp-quote s0) ">>") nil t)
13084 (setq pos (match-beginning 0))))
13085 ;; There is an exact target for this
13086 (goto-char pos))
13087 ((string-match "^/\\(.*\\)/$" s)
13088 ;; A regular expression
13089 (cond
13090 ((org-mode-p)
13091 (org-occur (match-string 1 s)))
13092 ;;((eq major-mode 'dired-mode)
13093 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13094 (t (org-do-occur (match-string 1 s)))))
13096 ;; A normal search strings
13097 (when (equal (string-to-char s) ?*)
13098 ;; Anchor on headlines, post may include tags.
13099 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13100 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13101 s (substring s 1)))
13102 (remove-text-properties
13103 0 (length s)
13104 '(face nil mouse-face nil keymap nil fontified nil) s)
13105 ;; Make a series of regular expressions to find a match
13106 (setq words (org-split-string s "[ \n\r\t]+")
13107 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13108 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13109 "\\)" markers)
13110 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13111 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13112 re1 (concat pre re2 post)
13113 re3 (concat pre re4 post)
13114 re5 (concat pre ".*" re4)
13115 re2 (concat pre re2)
13116 re2a (concat pre re2a)
13117 re4 (concat pre re4)
13118 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13119 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13120 re5 "\\)"
13122 (cond
13123 ((eq type 'org-occur) (org-occur reall))
13124 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13125 (t (goto-char (point-min))
13126 (if (or (org-search-not-self 1 re0 nil t)
13127 (org-search-not-self 1 re1 nil t)
13128 (org-search-not-self 1 re2 nil t)
13129 (org-search-not-self 1 re2a nil t)
13130 (org-search-not-self 1 re3 nil t)
13131 (org-search-not-self 1 re4 nil t)
13132 (org-search-not-self 1 re5 nil t)
13134 (goto-char (match-beginning 1))
13135 (goto-char pos)
13136 (error "No match")))))
13138 ;; Normal string-search
13139 (goto-char (point-min))
13140 (if (search-forward s nil t)
13141 (goto-char (match-beginning 0))
13142 (error "No match"))))
13143 (and (org-mode-p) (org-show-context 'link-search))))
13145 (defun org-search-not-self (group &rest args)
13146 "Execute `re-search-forward', but only accept matches that do not
13147 enclose the position of `org-open-link-marker'."
13148 (let ((m org-open-link-marker))
13149 (catch 'exit
13150 (while (apply 're-search-forward args)
13151 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13152 (goto-char (match-end group))
13153 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13154 (> (match-beginning 0) (marker-position m))
13155 (< (match-end 0) (marker-position m)))
13156 (save-match-data
13157 (or (not (org-in-regexp
13158 org-bracket-link-analytic-regexp 1))
13159 (not (match-end 4)) ; no description
13160 (and (<= (match-beginning 4) (point))
13161 (>= (match-end 4) (point))))))
13162 (throw 'exit (point))))))))
13164 (defun org-get-buffer-for-internal-link (buffer)
13165 "Return a buffer to be used for displaying the link target of internal links."
13166 (cond
13167 ((not org-display-internal-link-with-indirect-buffer)
13168 buffer)
13169 ((string-match "(Clone)$" (buffer-name buffer))
13170 (message "Buffer is already a clone, not making another one")
13171 ;; we also do not modify visibility in this case
13172 buffer)
13173 (t ; make a new indirect buffer for displaying the link
13174 (let* ((bn (buffer-name buffer))
13175 (ibn (concat bn "(Clone)"))
13176 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13177 (with-current-buffer ib (org-overview))
13178 ib))))
13180 (defun org-do-occur (regexp &optional cleanup)
13181 "Call the Emacs command `occur'.
13182 If CLEANUP is non-nil, remove the printout of the regular expression
13183 in the *Occur* buffer. This is useful if the regex is long and not useful
13184 to read."
13185 (occur regexp)
13186 (when cleanup
13187 (let ((cwin (selected-window)) win beg end)
13188 (when (setq win (get-buffer-window "*Occur*"))
13189 (select-window win))
13190 (goto-char (point-min))
13191 (when (re-search-forward "match[a-z]+" nil t)
13192 (setq beg (match-end 0))
13193 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13194 (setq end (1- (match-beginning 0)))))
13195 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13196 (goto-char (point-min))
13197 (select-window cwin))))
13199 ;;; The mark ring for links jumps
13201 (defvar org-mark-ring nil
13202 "Mark ring for positions before jumps in Org-mode.")
13203 (defvar org-mark-ring-last-goto nil
13204 "Last position in the mark ring used to go back.")
13205 ;; Fill and close the ring
13206 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13207 (loop for i from 1 to org-mark-ring-length do
13208 (push (make-marker) org-mark-ring))
13209 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13210 org-mark-ring)
13212 (defun org-mark-ring-push (&optional pos buffer)
13213 "Put the current position or POS into the mark ring and rotate it."
13214 (interactive)
13215 (setq pos (or pos (point)))
13216 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13217 (move-marker (car org-mark-ring)
13218 (or pos (point))
13219 (or buffer (current-buffer)))
13220 (message "%s"
13221 (substitute-command-keys
13222 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13224 (defun org-mark-ring-goto (&optional n)
13225 "Jump to the previous position in the mark ring.
13226 With prefix arg N, jump back that many stored positions. When
13227 called several times in succession, walk through the entire ring.
13228 Org-mode commands jumping to a different position in the current file,
13229 or to another Org-mode file, automatically push the old position
13230 onto the ring."
13231 (interactive "p")
13232 (let (p m)
13233 (if (eq last-command this-command)
13234 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13235 (setq p org-mark-ring))
13236 (setq org-mark-ring-last-goto p)
13237 (setq m (car p))
13238 (switch-to-buffer (marker-buffer m))
13239 (goto-char m)
13240 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13242 (defun org-remove-angle-brackets (s)
13243 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13244 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13246 (defun org-add-angle-brackets (s)
13247 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13248 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13251 ;;; Following specific links
13253 (defun org-follow-timestamp-link ()
13254 (cond
13255 ((org-at-date-range-p t)
13256 (let ((org-agenda-start-on-weekday)
13257 (t1 (match-string 1))
13258 (t2 (match-string 2)))
13259 (setq t1 (time-to-days (org-time-string-to-time t1))
13260 t2 (time-to-days (org-time-string-to-time t2)))
13261 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13262 ((org-at-timestamp-p t)
13263 (org-agenda-list nil (time-to-days (org-time-string-to-time
13264 (substring (match-string 1) 0 10)))
13266 (t (error "This should not happen"))))
13269 (defun org-follow-bbdb-link (name)
13270 "Follow a BBDB link to NAME."
13271 (require 'bbdb)
13272 (let ((inhibit-redisplay (not debug-on-error))
13273 (bbdb-electric-p nil))
13274 (catch 'exit
13275 ;; Exact match on name
13276 (bbdb-name (concat "\\`" name "\\'") nil)
13277 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13278 ;; Exact match on name
13279 (bbdb-company (concat "\\`" name "\\'") nil)
13280 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13281 ;; Partial match on name
13282 (bbdb-name name nil)
13283 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13284 ;; Partial match on company
13285 (bbdb-company name nil)
13286 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13287 ;; General match including network address and notes
13288 (bbdb name nil)
13289 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13290 (delete-window (get-buffer-window "*BBDB*"))
13291 (error "No matching BBDB record")))))
13293 (defun org-follow-info-link (name)
13294 "Follow an info file & node link to NAME."
13295 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13296 (string-match "\\(.*\\)" name))
13297 (progn
13298 (require 'info)
13299 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13300 (Info-find-node (match-string 1 name) (match-string 2 name))
13301 (Info-find-node (match-string 1 name) "Top")))
13302 (message "Could not open: %s" name)))
13304 (defun org-follow-gnus-link (&optional group article)
13305 "Follow a Gnus link to GROUP and ARTICLE."
13306 (require 'gnus)
13307 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13308 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13309 (cond ((and group article)
13310 (gnus-group-read-group 1 nil group)
13311 (gnus-summary-goto-article (string-to-number article) nil t))
13312 (group (gnus-group-jump-to-group group))))
13314 (defun org-follow-vm-link (&optional folder article readonly)
13315 "Follow a VM link to FOLDER and ARTICLE."
13316 (require 'vm)
13317 (setq article (org-add-angle-brackets article))
13318 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13319 ;; ange-ftp or efs or tramp access
13320 (let ((user (or (match-string 1 folder) (user-login-name)))
13321 (host (match-string 2 folder))
13322 (file (match-string 3 folder)))
13323 (cond
13324 ((featurep 'tramp)
13325 ;; use tramp to access the file
13326 (if (featurep 'xemacs)
13327 (setq folder (format "[%s@%s]%s" user host file))
13328 (setq folder (format "/%s@%s:%s" user host file))))
13330 ;; use ange-ftp or efs
13331 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13332 (setq folder (format "/%s@%s:%s" user host file))))))
13333 (when folder
13334 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13335 (sit-for 0.1)
13336 (when article
13337 (vm-select-folder-buffer)
13338 (widen)
13339 (let ((case-fold-search t))
13340 (goto-char (point-min))
13341 (if (not (re-search-forward
13342 (concat "^" "message-id: *" (regexp-quote article))))
13343 (error "Could not find the specified message in this folder"))
13344 (vm-isearch-update)
13345 (vm-isearch-narrow)
13346 (vm-beginning-of-message)
13347 (vm-summarize)))))
13349 (defun org-follow-wl-link (folder article)
13350 "Follow a Wanderlust link to FOLDER and ARTICLE."
13351 (if (and (string= folder "%")
13352 article
13353 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13354 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13355 ;; Thus, we recompose folder and article ids.
13356 (setq folder (format "%s#%s" folder (match-string 1 article))
13357 article (match-string 3 article)))
13358 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13359 (error "No such folder: %s" folder))
13360 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13361 (and article
13362 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13363 (wl-summary-redisplay)))
13365 (defun org-follow-rmail-link (folder article)
13366 "Follow an RMAIL link to FOLDER and ARTICLE."
13367 (setq article (org-add-angle-brackets article))
13368 (let (message-number)
13369 (save-excursion
13370 (save-window-excursion
13371 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13372 (setq message-number
13373 (save-restriction
13374 (widen)
13375 (goto-char (point-max))
13376 (if (re-search-backward
13377 (concat "^Message-ID:\\s-+" (regexp-quote
13378 (or article "")))
13379 nil t)
13380 (rmail-what-message))))))
13381 (if message-number
13382 (progn
13383 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13384 (rmail-show-message message-number)
13385 message-number)
13386 (error "Message not found"))))
13388 ;;; mh-e integration based on planner-mode
13389 (defun org-mhe-get-message-real-folder ()
13390 "Return the name of the current message real folder, so if you use
13391 sequences, it will now work."
13392 (save-excursion
13393 (let* ((folder
13394 (if (equal major-mode 'mh-folder-mode)
13395 mh-current-folder
13396 ;; Refer to the show buffer
13397 mh-show-folder-buffer))
13398 (end-index
13399 (if (boundp 'mh-index-folder)
13400 (min (length mh-index-folder) (length folder))))
13402 ;; a simple test on mh-index-data does not work, because
13403 ;; mh-index-data is always nil in a show buffer.
13404 (if (and (boundp 'mh-index-folder)
13405 (string= mh-index-folder (substring folder 0 end-index)))
13406 (if (equal major-mode 'mh-show-mode)
13407 (save-window-excursion
13408 (let (pop-up-frames)
13409 (when (buffer-live-p (get-buffer folder))
13410 (progn
13411 (pop-to-buffer folder)
13412 (org-mhe-get-message-folder-from-index)
13415 (org-mhe-get-message-folder-from-index)
13417 folder
13421 (defun org-mhe-get-message-folder-from-index ()
13422 "Returns the name of the message folder in a index folder buffer."
13423 (save-excursion
13424 (mh-index-previous-folder)
13425 (re-search-forward "^\\(+.*\\)$" nil t)
13426 (message "%s" (match-string 1))))
13428 (defun org-mhe-get-message-folder ()
13429 "Return the name of the current message folder. Be careful if you
13430 use sequences."
13431 (save-excursion
13432 (if (equal major-mode 'mh-folder-mode)
13433 mh-current-folder
13434 ;; Refer to the show buffer
13435 mh-show-folder-buffer)))
13437 (defun org-mhe-get-message-num ()
13438 "Return the number of the current message. Be careful if you
13439 use sequences."
13440 (save-excursion
13441 (if (equal major-mode 'mh-folder-mode)
13442 (mh-get-msg-num nil)
13443 ;; Refer to the show buffer
13444 (mh-show-buffer-message-number))))
13446 (defun org-mhe-get-header (header)
13447 "Return a header of the message in folder mode. This will create a
13448 show buffer for the corresponding message. If you have a more clever
13449 idea..."
13450 (let* ((folder (org-mhe-get-message-folder))
13451 (num (org-mhe-get-message-num))
13452 (buffer (get-buffer-create (concat "show-" folder)))
13453 (header-field))
13454 (with-current-buffer buffer
13455 (mh-display-msg num folder)
13456 (if (equal major-mode 'mh-folder-mode)
13457 (mh-header-display)
13458 (mh-show-header-display))
13459 (set-buffer buffer)
13460 (setq header-field (mh-get-header-field header))
13461 (if (equal major-mode 'mh-folder-mode)
13462 (mh-show)
13463 (mh-show-show))
13464 header-field)))
13466 (defun org-follow-mhe-link (folder article)
13467 "Follow an MHE link to FOLDER and ARTICLE.
13468 If ARTICLE is nil FOLDER is shown. If the configuration variable
13469 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13470 ARTICLE is searched in all folders. Indexed searches (swish++,
13471 namazu, and others supported by MH-E) will always search in all
13472 folders."
13473 (require 'mh-e)
13474 (require 'mh-search)
13475 (require 'mh-utils)
13476 (mh-find-path)
13477 (if (not article)
13478 (mh-visit-folder (mh-normalize-folder-name folder))
13479 (setq article (org-add-angle-brackets article))
13480 (mh-search-choose)
13481 (if (equal mh-searcher 'pick)
13482 (progn
13483 (mh-search folder (list "--message-id" article))
13484 (when (and org-mhe-search-all-folders
13485 (not (org-mhe-get-message-real-folder)))
13486 (kill-this-buffer)
13487 (mh-search "+" (list "--message-id" article))))
13488 (mh-search "+" article))
13489 (if (org-mhe-get-message-real-folder)
13490 (mh-show-msg 1)
13491 (kill-this-buffer)
13492 (error "Message not found"))))
13494 ;;; BibTeX links
13496 ;; Use the custom search meachnism to construct and use search strings for
13497 ;; file links to BibTeX database entries.
13499 (defun org-create-file-search-in-bibtex ()
13500 "Create the search string and description for a BibTeX database entry."
13501 (when (eq major-mode 'bibtex-mode)
13502 ;; yes, we want to construct this search string.
13503 ;; Make a good description for this entry, using names, year and the title
13504 ;; Put it into the `description' variable which is dynamically scoped.
13505 (let ((bibtex-autokey-names 1)
13506 (bibtex-autokey-names-stretch 1)
13507 (bibtex-autokey-name-case-convert-function 'identity)
13508 (bibtex-autokey-name-separator " & ")
13509 (bibtex-autokey-additional-names " et al.")
13510 (bibtex-autokey-year-length 4)
13511 (bibtex-autokey-name-year-separator " ")
13512 (bibtex-autokey-titlewords 3)
13513 (bibtex-autokey-titleword-separator " ")
13514 (bibtex-autokey-titleword-case-convert-function 'identity)
13515 (bibtex-autokey-titleword-length 'infty)
13516 (bibtex-autokey-year-title-separator ": "))
13517 (setq description (bibtex-generate-autokey)))
13518 ;; Now parse the entry, get the key and return it.
13519 (save-excursion
13520 (bibtex-beginning-of-entry)
13521 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13523 (defun org-execute-file-search-in-bibtex (s)
13524 "Find the link search string S as a key for a database entry."
13525 (when (eq major-mode 'bibtex-mode)
13526 ;; Yes, we want to do the search in this file.
13527 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13528 (goto-char (point-min))
13529 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13530 (regexp-quote s) "[ \t\n]*,") nil t)
13531 (goto-char (match-beginning 0)))
13532 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13533 ;; Use double prefix to indicate that any web link should be browsed
13534 (let ((b (current-buffer)) (p (point)))
13535 ;; Restore the window configuration because we just use the web link
13536 (set-window-configuration org-window-config-before-follow-link)
13537 (save-excursion (set-buffer b) (goto-char p)
13538 (bibtex-url)))
13539 (recenter 0)) ; Move entry start to beginning of window
13540 ;; return t to indicate that the search is done.
13543 ;; Finally add the functions to the right hooks.
13544 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13545 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13547 ;; end of Bibtex link setup
13549 ;;; Following file links
13551 (defun org-open-file (path &optional in-emacs line search)
13552 "Open the file at PATH.
13553 First, this expands any special file name abbreviations. Then the
13554 configuration variable `org-file-apps' is checked if it contains an
13555 entry for this file type, and if yes, the corresponding command is launched.
13556 If no application is found, Emacs simply visits the file.
13557 With optional argument IN-EMACS, Emacs will visit the file.
13558 Optional LINE specifies a line to go to, optional SEARCH a string to
13559 search for. If LINE or SEARCH is given, the file will always be
13560 opened in Emacs.
13561 If the file does not exist, an error is thrown."
13562 (setq in-emacs (or in-emacs line search))
13563 (let* ((file (if (equal path "")
13564 buffer-file-name
13565 (substitute-in-file-name (expand-file-name path))))
13566 (apps (append org-file-apps (org-default-apps)))
13567 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13568 (dirp (if remp nil (file-directory-p file)))
13569 (dfile (downcase file))
13570 (old-buffer (current-buffer))
13571 (old-pos (point))
13572 (old-mode major-mode)
13573 ext cmd)
13574 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13575 (setq ext (match-string 1 dfile))
13576 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13577 (setq ext (match-string 1 dfile))))
13578 (if in-emacs
13579 (setq cmd 'emacs)
13580 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13581 (and dirp (cdr (assoc 'directory apps)))
13582 (cdr (assoc ext apps))
13583 (cdr (assoc t apps)))))
13584 (when (eq cmd 'mailcap)
13585 (require 'mailcap)
13586 (mailcap-parse-mailcaps)
13587 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13588 (command (mailcap-mime-info mime-type)))
13589 (if (stringp command)
13590 (setq cmd command)
13591 (setq cmd 'emacs))))
13592 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13593 (not (file-exists-p file))
13594 (not org-open-non-existing-files))
13595 (error "No such file: %s" file))
13596 (cond
13597 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13598 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13599 (while (string-match "['\"]%s['\"]" cmd)
13600 (setq cmd (replace-match "%s" t t cmd)))
13601 (while (string-match "%s" cmd)
13602 (setq cmd (replace-match
13603 (save-match-data (shell-quote-argument file))
13604 t t cmd)))
13605 (save-window-excursion
13606 (start-process-shell-command cmd nil cmd)))
13607 ((or (stringp cmd)
13608 (eq cmd 'emacs))
13609 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13610 (widen)
13611 (if line (goto-line line)
13612 (if search (org-link-search search))))
13613 ((consp cmd)
13614 (eval cmd))
13615 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13616 (and (org-mode-p) (eq old-mode 'org-mode)
13617 (or (not (equal old-buffer (current-buffer)))
13618 (not (equal old-pos (point))))
13619 (org-mark-ring-push old-pos old-buffer))))
13621 (defun org-default-apps ()
13622 "Return the default applications for this operating system."
13623 (cond
13624 ((eq system-type 'darwin)
13625 org-file-apps-defaults-macosx)
13626 ((eq system-type 'windows-nt)
13627 org-file-apps-defaults-windowsnt)
13628 (t org-file-apps-defaults-gnu)))
13630 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13631 (defun org-file-remote-p (file)
13632 "Test whether FILE specifies a location on a remote system.
13633 Return non-nil if the location is indeed remote.
13635 For example, the filename \"/user@host:/foo\" specifies a location
13636 on the system \"/user@host:\"."
13637 (cond ((fboundp 'file-remote-p)
13638 (file-remote-p file))
13639 ((fboundp 'tramp-handle-file-remote-p)
13640 (tramp-handle-file-remote-p file))
13641 ((and (boundp 'ange-ftp-name-format)
13642 (string-match (car ange-ftp-name-format) file))
13644 (t nil)))
13647 ;;;; Hooks for remember.el, and refiling
13649 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13650 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13652 ;;;###autoload
13653 (defun org-remember-insinuate ()
13654 "Setup remember.el for use wiht Org-mode."
13655 (require 'remember)
13656 (setq remember-annotation-functions '(org-remember-annotation))
13657 (setq remember-handler-functions '(org-remember-handler))
13658 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13660 ;;;###autoload
13661 (defun org-remember-annotation ()
13662 "Return a link to the current location as an annotation for remember.el.
13663 If you are using Org-mode files as target for data storage with
13664 remember.el, then the annotations should include a link compatible with the
13665 conventions in Org-mode. This function returns such a link."
13666 (org-store-link nil))
13668 (defconst org-remember-help
13669 "Select a destination location for the note.
13670 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13671 RET on headline -> Store as sublevel entry to current headline
13672 RET at beg-of-buf -> Append to file as level 2 headline
13673 <left>/<right> -> before/after current headline, same headings level")
13675 (defvar org-remember-previous-location nil)
13676 (defvar org-force-remember-template-char) ;; dynamically scoped
13678 ;; Save the major mode of the buffer we called remember from
13679 (defvar org-select-template-temp-major-mode nil)
13681 ;; Temporary store the buffer where remember was called from
13682 (defvar org-select-template-original-buffer nil)
13684 (defun org-select-remember-template (&optional use-char)
13685 (when org-remember-templates
13686 (let* ((pre-selected-templates
13687 (mapcar
13688 (lambda (tpl)
13689 (let ((ctxt (nth 5 tpl))
13690 (mode org-select-template-temp-major-mode)
13691 (buf org-select-template-original-buffer))
13692 (if (or (and (functionp ctxt)
13693 (save-excursion
13694 (set-buffer buf)
13695 ;; Protect the user-defined function from error
13696 (condition-case nil (funcall ctxt) (error nil))))
13697 (and ctxt (listp ctxt)
13698 (delq nil (mapcar (lambda(x) (eq mode x)) ctxt))))
13699 tpl)))
13700 org-remember-templates))
13701 ;; If no template at this point, add the default templates:
13702 (pre-selected-templates1
13703 (if (not (delq nil pre-selected-templates))
13704 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13705 org-remember-templates)
13706 pre-selected-templates))
13707 ;; Then unconditionnally add template for any contexts
13708 (pre-selected-templates2
13709 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13710 org-remember-templates)
13711 (delq nil pre-selected-templates1)))
13712 (templates (mapcar (lambda (x)
13713 (if (stringp (car x))
13714 (append (list (nth 1 x) (car x)) (cddr x))
13715 (append (list (car x) "") (cdr x))))
13716 (delq nil pre-selected-templates2)))
13717 (char (or use-char
13718 (cond
13719 ((= (length templates) 1)
13720 (caar templates))
13721 ((and (boundp 'org-force-remember-template-char)
13722 org-force-remember-template-char)
13723 (if (stringp org-force-remember-template-char)
13724 (string-to-char org-force-remember-template-char)
13725 org-force-remember-template-char))
13727 (message "Select template: %s"
13728 (mapconcat
13729 (lambda (x)
13730 (cond
13731 ((not (string-match "\\S-" (nth 1 x)))
13732 (format "[%c]" (car x)))
13733 ((equal (downcase (car x))
13734 (downcase (aref (nth 1 x) 0)))
13735 (format "[%c]%s" (car x)
13736 (substring (nth 1 x) 1)))
13737 (t (format "[%c]%s" (car x) (nth 1 x)))))
13738 templates " "))
13739 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13740 (when (equal char0 ?\C-g)
13741 (jump-to-register remember-register)
13742 (kill-buffer remember-buffer))
13743 char0))))))
13744 (cddr (assoc char templates)))))
13746 (defvar x-last-selected-text)
13747 (defvar x-last-selected-text-primary)
13749 ;;;###autoload
13750 (defun org-remember-apply-template (&optional use-char skip-interactive)
13751 "Initialize *remember* buffer with template, invoke `org-mode'.
13752 This function should be placed into `remember-mode-hook' and in fact requires
13753 to be run from that hook to function properly."
13754 (if org-remember-templates
13755 (let* ((entry (org-select-remember-template use-char))
13756 (tpl (car entry))
13757 (plist-p (if org-store-link-plist t nil))
13758 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13759 (string-match "\\S-" (nth 1 entry)))
13760 (nth 1 entry)
13761 org-default-notes-file))
13762 (headline (nth 2 entry))
13763 (v-c (or (and (eq window-system 'x)
13764 (fboundp 'x-cut-buffer-or-selection-value)
13765 (x-cut-buffer-or-selection-value))
13766 (org-bound-and-true-p x-last-selected-text)
13767 (org-bound-and-true-p x-last-selected-text-primary)
13768 (and (> (length kill-ring) 0) (current-kill 0))))
13769 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13770 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13771 (v-u (concat "[" (substring v-t 1 -1) "]"))
13772 (v-U (concat "[" (substring v-T 1 -1) "]"))
13773 ;; `initial' and `annotation' are bound in `remember'
13774 (v-i (if (boundp 'initial) initial))
13775 (v-a (if (and (boundp 'annotation) annotation)
13776 (if (equal annotation "[[]]") "" annotation)
13777 ""))
13778 (v-A (if (and v-a
13779 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13780 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13781 v-a))
13782 (v-n user-full-name)
13783 (org-startup-folded nil)
13784 org-time-was-given org-end-time-was-given x
13785 prompt completions char time pos default histvar)
13786 (setq org-store-link-plist
13787 (append (list :annotation v-a :initial v-i)
13788 org-store-link-plist))
13789 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13790 (erase-buffer)
13791 (insert (substitute-command-keys
13792 (format
13793 "## Filing location: Select interactively, default, or last used:
13794 ## %s to select file and header location interactively.
13795 ## %s \"%s\" -> \"* %s\"
13796 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13797 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13798 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13799 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13800 (abbreviate-file-name (or file org-default-notes-file))
13801 (or headline "")
13802 (or (car org-remember-previous-location) "???")
13803 (or (cdr org-remember-previous-location) "???"))))
13804 (insert tpl) (goto-char (point-min))
13805 ;; Simple %-escapes
13806 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13807 (when (and initial (equal (match-string 0) "%i"))
13808 (save-match-data
13809 (let* ((lead (buffer-substring
13810 (point-at-bol) (match-beginning 0))))
13811 (setq v-i (mapconcat 'identity
13812 (org-split-string initial "\n")
13813 (concat "\n" lead))))))
13814 (replace-match
13815 (or (eval (intern (concat "v-" (match-string 1)))) "")
13816 t t))
13818 ;; %[] Insert contents of a file.
13819 (goto-char (point-min))
13820 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13821 (let ((start (match-beginning 0))
13822 (end (match-end 0))
13823 (filename (expand-file-name (match-string 1))))
13824 (goto-char start)
13825 (delete-region start end)
13826 (condition-case error
13827 (insert-file-contents filename)
13828 (error (insert (format "%%![Couldn't insert %s: %s]"
13829 filename error))))))
13830 ;; %() embedded elisp
13831 (goto-char (point-min))
13832 (while (re-search-forward "%\\((.+)\\)" nil t)
13833 (goto-char (match-beginning 0))
13834 (let ((template-start (point)))
13835 (forward-char 1)
13836 (let ((result
13837 (condition-case error
13838 (eval (read (current-buffer)))
13839 (error (format "%%![Error: %s]" error)))))
13840 (delete-region template-start (point))
13841 (insert result))))
13843 ;; From the property list
13844 (when plist-p
13845 (goto-char (point-min))
13846 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13847 (and (setq x (or (plist-get org-store-link-plist
13848 (intern (match-string 1))) ""))
13849 (replace-match x t t))))
13851 ;; Turn on org-mode in the remember buffer, set local variables
13852 (org-mode)
13853 (org-set-local 'org-finish-function 'org-remember-finalize)
13854 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13855 (org-set-local 'org-default-notes-file file))
13856 (if (and headline (stringp headline) (string-match "\\S-" headline))
13857 (org-set-local 'org-remember-default-headline headline))
13858 ;; Interactive template entries
13859 (goto-char (point-min))
13860 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13861 (setq char (if (match-end 3) (match-string 3))
13862 prompt (if (match-end 2) (match-string 2)))
13863 (goto-char (match-beginning 0))
13864 (replace-match "")
13865 (setq completions nil default nil)
13866 (when prompt
13867 (setq completions (org-split-string prompt "|")
13868 prompt (pop completions)
13869 default (car completions)
13870 histvar (intern (concat
13871 "org-remember-template-prompt-history::"
13872 (or prompt "")))
13873 completions (mapcar 'list completions)))
13874 (cond
13875 ((member char '("G" "g"))
13876 (let* ((org-last-tags-completion-table
13877 (org-global-tags-completion-table
13878 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13879 (org-add-colon-after-tag-completion t)
13880 (ins (completing-read
13881 (if prompt (concat prompt ": ") "Tags: ")
13882 'org-tags-completion-function nil nil nil
13883 'org-tags-history)))
13884 (setq ins (mapconcat 'identity
13885 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13886 ":"))
13887 (when (string-match "\\S-" ins)
13888 (or (equal (char-before) ?:) (insert ":"))
13889 (insert ins)
13890 (or (equal (char-after) ?:) (insert ":")))))
13891 (char
13892 (setq org-time-was-given (equal (upcase char) char))
13893 (setq time (org-read-date (equal (upcase char) "U") t nil
13894 prompt))
13895 (org-insert-time-stamp time org-time-was-given
13896 (member char '("u" "U"))
13897 nil nil (list org-end-time-was-given)))
13899 (insert (org-completing-read
13900 (concat (if prompt prompt "Enter string")
13901 (if default (concat " [" default "]"))
13902 ": ")
13903 completions nil nil nil histvar default)))))
13904 (goto-char (point-min))
13905 (if (re-search-forward "%\\?" nil t)
13906 (replace-match "")
13907 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13908 (org-mode)
13909 (org-set-local 'org-finish-function 'org-remember-finalize))
13910 (when (save-excursion
13911 (goto-char (point-min))
13912 (re-search-forward "%!" nil t))
13913 (replace-match "")
13914 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13916 (defun org-remember-finish-immediately ()
13917 "File remember note immediately.
13918 This should be run in `post-command-hook' and will remove itself
13919 from that hook."
13920 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13921 (when org-finish-function
13922 (funcall org-finish-function)))
13924 (defvar org-clock-marker) ; Defined below
13925 (defun org-remember-finalize ()
13926 "Finalize the remember process."
13927 (unless (fboundp 'remember-finalize)
13928 (defalias 'remember-finalize 'remember-buffer))
13929 (when (and org-clock-marker
13930 (equal (marker-buffer org-clock-marker) (current-buffer)))
13931 ;; FIXME: test this, this is w/o notetaking!
13932 (let (org-log-note-clock-out) (org-clock-out)))
13933 (when buffer-file-name
13934 (save-buffer)
13935 (setq buffer-file-name nil))
13936 (remember-finalize))
13938 ;;;###autoload
13939 (defun org-remember (&optional goto org-force-remember-template-char)
13940 "Call `remember'. If this is already a remember buffer, re-apply template.
13941 If there is an active region, make sure remember uses it as initial content
13942 of the remember buffer.
13944 When called interactively with a `C-u' prefix argument GOTO, don't remember
13945 anything, just go to the file/headline where the selected template usually
13946 stores its notes. With a double prefix arg `C-u C-u', go to the last
13947 note stored by remember.
13949 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13950 associated with a template in `org-remember-templates'."
13951 (interactive "P")
13952 (cond
13953 ((equal goto '(4)) (org-go-to-remember-target))
13954 ((equal goto '(16)) (org-remember-goto-last-stored))
13956 ;; set temporary variables that will be needed in
13957 ;; `org-select-remember-template'
13958 (setq org-select-template-temp-major-mode major-mode)
13959 (setq org-select-template-original-buffer (current-buffer))
13960 (if (memq org-finish-function '(remember-buffer remember-finalize))
13961 (progn
13962 (when (< (length org-remember-templates) 2)
13963 (error "No other template available"))
13964 (erase-buffer)
13965 (let ((annotation (plist-get org-store-link-plist :annotation))
13966 (initial (plist-get org-store-link-plist :initial)))
13967 (org-remember-apply-template))
13968 (message "Press C-c C-c to remember data"))
13969 (if (org-region-active-p)
13970 (remember (buffer-substring (point) (mark)))
13971 (call-interactively 'remember))))))
13973 (defun org-remember-goto-last-stored ()
13974 "Go to the location where the last remember note was stored."
13975 (interactive)
13976 (bookmark-jump "org-remember-last-stored")
13977 (message "This is the last note stored by remember"))
13979 (defun org-go-to-remember-target (&optional template-key)
13980 "Go to the target location of a remember template.
13981 The user is queried for the template."
13982 (interactive)
13983 (let* (org-select-template-temp-major-mode
13984 (entry (org-select-remember-template template-key))
13985 (file (nth 1 entry))
13986 (heading (nth 2 entry))
13987 visiting)
13988 (unless (and file (stringp file) (string-match "\\S-" file))
13989 (setq file org-default-notes-file))
13990 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13991 (setq heading org-remember-default-headline))
13992 (setq visiting (org-find-base-buffer-visiting file))
13993 (if (not visiting) (find-file-noselect file))
13994 (switch-to-buffer (or visiting (get-file-buffer file)))
13995 (widen)
13996 (goto-char (point-min))
13997 (if (re-search-forward
13998 (concat "^\\*+[ \t]+" (regexp-quote heading)
13999 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14000 nil t)
14001 (goto-char (match-beginning 0))
14002 (error "Target headline not found: %s" heading))))
14004 (defvar org-note-abort nil) ; dynamically scoped
14006 ;;;###autoload
14007 (defun org-remember-handler ()
14008 "Store stuff from remember.el into an org file.
14009 First prompts for an org file. If the user just presses return, the value
14010 of `org-default-notes-file' is used.
14011 Then the command offers the headings tree of the selected file in order to
14012 file the text at a specific location.
14013 You can either immediately press RET to get the note appended to the
14014 file, or you can use vertical cursor motion and visibility cycling (TAB) to
14015 find a better place. Then press RET or <left> or <right> in insert the note.
14017 Key Cursor position Note gets inserted
14018 -----------------------------------------------------------------------------
14019 RET buffer-start as level 1 heading at end of file
14020 RET on headline as sublevel of the heading at cursor
14021 RET no heading at cursor position, level taken from context.
14022 Or use prefix arg to specify level manually.
14023 <left> on headline as same level, before current heading
14024 <right> on headline as same level, after current heading
14026 So the fastest way to store the note is to press RET RET to append it to
14027 the default file. This way your current train of thought is not
14028 interrupted, in accordance with the principles of remember.el.
14029 You can also get the fast execution without prompting by using
14030 C-u C-c C-c to exit the remember buffer. See also the variable
14031 `org-remember-store-without-prompt'.
14033 Before being stored away, the function ensures that the text has a
14034 headline, i.e. a first line that starts with a \"*\". If not, a headline
14035 is constructed from the current date and some additional data.
14037 If the variable `org-adapt-indentation' is non-nil, the entire text is
14038 also indented so that it starts in the same column as the headline
14039 \(i.e. after the stars).
14041 See also the variable `org-reverse-note-order'."
14042 (goto-char (point-min))
14043 (while (looking-at "^[ \t]*\n\\|^##.*\n")
14044 (replace-match ""))
14045 (goto-char (point-max))
14046 (beginning-of-line 1)
14047 (while (looking-at "[ \t]*$\\|##.*")
14048 (delete-region (1- (point)) (point-max))
14049 (beginning-of-line 1))
14050 (catch 'quit
14051 (if org-note-abort (throw 'quit nil))
14052 (let* ((txt (buffer-substring (point-min) (point-max)))
14053 (fastp (org-xor (equal current-prefix-arg '(4))
14054 org-remember-store-without-prompt))
14055 (file (cond
14056 (fastp org-default-notes-file)
14057 ((and (eq org-remember-interactive-interface 'refile)
14058 org-refile-targets)
14059 org-default-notes-file)
14060 ((not (and (equal current-prefix-arg '(16))
14061 org-remember-previous-location))
14062 (org-get-org-file))))
14063 (heading org-remember-default-headline)
14064 (visiting (and file (org-find-base-buffer-visiting file)))
14065 (org-startup-folded nil)
14066 (org-startup-align-all-tables nil)
14067 (org-goto-start-pos 1)
14068 spos exitcmd level indent reversed)
14069 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
14070 (setq file (car org-remember-previous-location)
14071 heading (cdr org-remember-previous-location)
14072 fastp t))
14073 (setq current-prefix-arg nil)
14074 (if (string-match "[ \t\n]+\\'" txt)
14075 (setq txt (replace-match "" t t txt)))
14076 ;; Modify text so that it becomes a nice subtree which can be inserted
14077 ;; into an org tree.
14078 (let* ((lines (split-string txt "\n"))
14079 first)
14080 (setq first (car lines) lines (cdr lines))
14081 (if (string-match "^\\*+ " first)
14082 ;; Is already a headline
14083 (setq indent nil)
14084 ;; We need to add a headline: Use time and first buffer line
14085 (setq lines (cons first lines)
14086 first (concat "* " (current-time-string)
14087 " (" (remember-buffer-desc) ")")
14088 indent " "))
14089 (if (and org-adapt-indentation indent)
14090 (setq lines (mapcar
14091 (lambda (x)
14092 (if (string-match "\\S-" x)
14093 (concat indent x) x))
14094 lines)))
14095 (setq txt (concat first "\n"
14096 (mapconcat 'identity lines "\n"))))
14097 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14098 (setq txt (replace-match "\n\n" t t txt))
14099 (if (string-match "[ \t\n]*\\'" txt)
14100 (setq txt (replace-match "\n" t t txt))))
14101 ;; Put the modified text back into the remember buffer, for refile.
14102 (erase-buffer)
14103 (insert txt)
14104 (goto-char (point-min))
14105 (when (and (eq org-remember-interactive-interface 'refile)
14106 (not fastp))
14107 (org-refile nil (or visiting (find-file-noselect file)))
14108 (throw 'quit t))
14109 ;; Find the file
14110 (if (not visiting) (find-file-noselect file))
14111 (with-current-buffer (or visiting (get-file-buffer file))
14112 (unless (org-mode-p)
14113 (error "Target files for remember notes must be in Org-mode"))
14114 (save-excursion
14115 (save-restriction
14116 (widen)
14117 (and (goto-char (point-min))
14118 (not (re-search-forward "^\\* " nil t))
14119 (insert "\n* " (or heading "Notes") "\n"))
14120 (setq reversed (org-notes-order-reversed-p))
14122 ;; Find the default location
14123 (when (and heading (stringp heading) (string-match "\\S-" heading))
14124 (goto-char (point-min))
14125 (if (re-search-forward
14126 (concat "^\\*+[ \t]+" (regexp-quote heading)
14127 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14128 nil t)
14129 (setq org-goto-start-pos (match-beginning 0))
14130 (when fastp
14131 (goto-char (point-max))
14132 (unless (bolp) (newline))
14133 (insert "* " heading "\n")
14134 (setq org-goto-start-pos (point-at-bol 0)))))
14136 ;; Ask the User for a location, using the appropriate interface
14137 (cond
14138 (fastp (setq spos org-goto-start-pos
14139 exitcmd 'return))
14140 ((eq org-remember-interactive-interface 'outline)
14141 (setq spos (org-get-location (current-buffer)
14142 org-remember-help)
14143 exitcmd (cdr spos)
14144 spos (car spos)))
14145 ((eq org-remember-interactive-interface 'outline-path-completion)
14146 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14147 (org-refile-use-outline-path t))
14148 (setq spos (org-refile-get-location "Heading: ")
14149 exitcmd 'return
14150 spos (nth 3 spos))))
14151 (t (error "this should not hapen")))
14152 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14153 ; not handle this note
14154 (goto-char spos)
14155 (cond ((org-on-heading-p t)
14156 (org-back-to-heading t)
14157 (setq level (funcall outline-level))
14158 (cond
14159 ((eq exitcmd 'return)
14160 ;; sublevel of current
14161 (setq org-remember-previous-location
14162 (cons (abbreviate-file-name file)
14163 (org-get-heading 'notags)))
14164 (if reversed
14165 (outline-next-heading)
14166 (org-end-of-subtree t)
14167 (if (not (bolp))
14168 (if (looking-at "[ \t]*\n")
14169 (beginning-of-line 2)
14170 (end-of-line 1)
14171 (insert "\n"))))
14172 (bookmark-set "org-remember-last-stored")
14173 (org-paste-subtree (org-get-valid-level level 1) txt))
14174 ((eq exitcmd 'left)
14175 ;; before current
14176 (bookmark-set "org-remember-last-stored")
14177 (org-paste-subtree level txt))
14178 ((eq exitcmd 'right)
14179 ;; after current
14180 (org-end-of-subtree t)
14181 (bookmark-set "org-remember-last-stored")
14182 (org-paste-subtree level txt))
14183 (t (error "This should not happen"))))
14185 ((and (bobp) (not reversed))
14186 ;; Put it at the end, one level below level 1
14187 (save-restriction
14188 (widen)
14189 (goto-char (point-max))
14190 (if (not (bolp)) (newline))
14191 (bookmark-set "org-remember-last-stored")
14192 (org-paste-subtree (org-get-valid-level 1 1) txt)))
14194 ((and (bobp) reversed)
14195 ;; Put it at the start, as level 1
14196 (save-restriction
14197 (widen)
14198 (goto-char (point-min))
14199 (re-search-forward "^\\*+ " nil t)
14200 (beginning-of-line 1)
14201 (bookmark-set "org-remember-last-stored")
14202 (org-paste-subtree 1 txt)))
14204 ;; Put it right there, with automatic level determined by
14205 ;; org-paste-subtree or from prefix arg
14206 (bookmark-set "org-remember-last-stored")
14207 (org-paste-subtree
14208 (if (numberp current-prefix-arg) current-prefix-arg)
14209 txt)))
14210 (when remember-save-after-remembering
14211 (save-buffer)
14212 (if (not visiting) (kill-buffer (current-buffer)))))))))
14214 t) ;; return t to indicate that we took care of this note.
14216 (defun org-get-org-file ()
14217 "Read a filename, with default directory `org-directory'."
14218 (let ((default (or org-default-notes-file remember-data-file)))
14219 (read-file-name (format "File name [%s]: " default)
14220 (file-name-as-directory org-directory)
14221 default)))
14223 (defun org-notes-order-reversed-p ()
14224 "Check if the current file should receive notes in reversed order."
14225 (cond
14226 ((not org-reverse-note-order) nil)
14227 ((eq t org-reverse-note-order) t)
14228 ((not (listp org-reverse-note-order)) nil)
14229 (t (catch 'exit
14230 (let ((all org-reverse-note-order)
14231 entry)
14232 (while (setq entry (pop all))
14233 (if (string-match (car entry) buffer-file-name)
14234 (throw 'exit (cdr entry))))
14235 nil)))))
14237 ;;; Refiling
14239 (defvar org-refile-target-table nil
14240 "The list of refile targets, created by `org-refile'.")
14242 (defvar org-agenda-new-buffers nil
14243 "Buffers created to visit agenda files.")
14245 (defun org-get-refile-targets (&optional default-buffer)
14246 "Produce a table with refile targets."
14247 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14248 targets txt re files f desc descre)
14249 (with-current-buffer (or default-buffer (current-buffer))
14250 (while (setq entry (pop entries))
14251 (setq files (car entry) desc (cdr entry))
14252 (cond
14253 ((null files) (setq files (list (current-buffer))))
14254 ((eq files 'org-agenda-files)
14255 (setq files (org-agenda-files 'unrestricted)))
14256 ((and (symbolp files) (fboundp files))
14257 (setq files (funcall files)))
14258 ((and (symbolp files) (boundp files))
14259 (setq files (symbol-value files))))
14260 (if (stringp files) (setq files (list files)))
14261 (cond
14262 ((eq (car desc) :tag)
14263 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14264 ((eq (car desc) :todo)
14265 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14266 ((eq (car desc) :regexp)
14267 (setq descre (cdr desc)))
14268 ((eq (car desc) :level)
14269 (setq descre (concat "^\\*\\{" (number-to-string
14270 (if org-odd-levels-only
14271 (1- (* 2 (cdr desc)))
14272 (cdr desc)))
14273 "\\}[ \t]")))
14274 ((eq (car desc) :maxlevel)
14275 (setq descre (concat "^\\*\\{1," (number-to-string
14276 (if org-odd-levels-only
14277 (1- (* 2 (cdr desc)))
14278 (cdr desc)))
14279 "\\}[ \t]")))
14280 (t (error "Bad refiling target description %s" desc)))
14281 (while (setq f (pop files))
14282 (save-excursion
14283 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14284 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14285 (save-excursion
14286 (save-restriction
14287 (widen)
14288 (goto-char (point-min))
14289 (while (re-search-forward descre nil t)
14290 (goto-char (point-at-bol))
14291 (when (looking-at org-complex-heading-regexp)
14292 (setq txt (match-string 4)
14293 re (concat "^" (regexp-quote
14294 (buffer-substring (match-beginning 1)
14295 (match-end 4)))))
14296 (if (match-end 5) (setq re (concat re "[ \t]+"
14297 (regexp-quote
14298 (match-string 5)))))
14299 (setq re (concat re "[ \t]*$"))
14300 (when org-refile-use-outline-path
14301 (setq txt (mapconcat 'identity
14302 (append
14303 (if (eq org-refile-use-outline-path 'file)
14304 (list (file-name-nondirectory
14305 (buffer-file-name (buffer-base-buffer))))
14306 (if (eq org-refile-use-outline-path 'full-file-path)
14307 (list (buffer-file-name (buffer-base-buffer)))))
14308 (org-get-outline-path)
14309 (list txt))
14310 "/")))
14311 (push (list txt f re (point)) targets))
14312 (goto-char (point-at-eol))))))))
14313 (nreverse targets))))
14315 (defun org-get-outline-path ()
14316 "Return the outline path to the current entry, as a list."
14317 (let (rtn)
14318 (save-excursion
14319 (while (org-up-heading-safe)
14320 (when (looking-at org-complex-heading-regexp)
14321 (push (org-match-string-no-properties 4) rtn)))
14322 rtn)))
14324 (defvar org-refile-history nil
14325 "History for refiling operations.")
14327 (defun org-refile (&optional goto default-buffer)
14328 "Move the entry at point to another heading.
14329 The list of target headings is compiled using the information in
14330 `org-refile-targets', which see. This list is created upon first use, and
14331 you can update it by calling this command with a double prefix (`C-u C-u').
14332 FIXME: Can we find a better way of updating?
14334 At the target location, the entry is filed as a subitem of the target heading.
14335 Depending on `org-reverse-note-order', the new subitem will either be the
14336 first of the last subitem.
14338 With prefix arg GOTO, the command will only visit the target location,
14339 not actually move anything.
14340 With a double prefix `C-c C-c', go to the location where the last refiling
14341 operation has put the subtree.
14343 With a double prefix argument, the command can be used to jump to any
14344 heading in the current buffer."
14345 (interactive "P")
14346 (let* ((cbuf (current-buffer))
14347 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14348 pos it nbuf file re level reversed)
14349 (if (equal goto '(16))
14350 (org-refile-goto-last-stored)
14351 (when (setq it (org-refile-get-location
14352 (if goto "Goto: " "Refile to: ") default-buffer))
14353 (setq file (nth 1 it)
14354 re (nth 2 it)
14355 pos (nth 3 it))
14356 (setq nbuf (or (find-buffer-visiting file)
14357 (find-file-noselect file)))
14358 (if goto
14359 (progn
14360 (switch-to-buffer nbuf)
14361 (goto-char pos)
14362 (org-show-context 'org-goto))
14363 (org-copy-special)
14364 (save-excursion
14365 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14366 (find-file-noselect file))))
14367 (setq reversed (org-notes-order-reversed-p))
14368 (save-excursion
14369 (save-restriction
14370 (widen)
14371 (goto-char pos)
14372 (looking-at outline-regexp)
14373 (setq level (org-get-valid-level (funcall outline-level) 1))
14374 (goto-char
14375 (if reversed
14376 (outline-next-heading)
14377 (or (save-excursion (outline-get-next-sibling))
14378 (org-end-of-subtree t t)
14379 (point-max))))
14380 (bookmark-set "org-refile-last-stored")
14381 (org-paste-subtree level))))
14382 (org-cut-special)
14383 (message "Entry refiled to \"%s\"" (car it)))))))
14385 (defun org-refile-goto-last-stored ()
14386 "Go to the location where the last refile was stored."
14387 (interactive)
14388 (bookmark-jump "org-refile-last-stored")
14389 (message "This is the location of the last refile"))
14391 (defun org-refile-get-location (&optional prompt default-buffer)
14392 "Prompt the user for a refile location, using PROMPT."
14393 (let ((org-refile-targets org-refile-targets)
14394 (org-refile-use-outline-path org-refile-use-outline-path))
14395 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14396 (unless org-refile-target-table
14397 (error "No refile targets"))
14398 (let* ((cbuf (current-buffer))
14399 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14400 (fname (and filename (file-truename filename)))
14401 (tbl (mapcar
14402 (lambda (x)
14403 (if (not (equal fname (file-truename (nth 1 x))))
14404 (cons (concat (car x) " (" (file-name-nondirectory
14405 (nth 1 x)) ")")
14406 (cdr x))
14408 org-refile-target-table))
14409 (completion-ignore-case t))
14410 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14411 tbl)))
14413 ;;;; Dynamic blocks
14415 (defun org-find-dblock (name)
14416 "Find the first dynamic block with name NAME in the buffer.
14417 If not found, stay at current position and return nil."
14418 (let (pos)
14419 (save-excursion
14420 (goto-char (point-min))
14421 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14422 nil t)
14423 (match-beginning 0))))
14424 (if pos (goto-char pos))
14425 pos))
14427 (defconst org-dblock-start-re
14428 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14429 "Matches the startline of a dynamic block, with parameters.")
14431 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14432 "Matches the end of a dyhamic block.")
14434 (defun org-create-dblock (plist)
14435 "Create a dynamic block section, with parameters taken from PLIST.
14436 PLIST must containe a :name entry which is used as name of the block."
14437 (unless (bolp) (newline))
14438 (let ((name (plist-get plist :name)))
14439 (insert "#+BEGIN: " name)
14440 (while plist
14441 (if (eq (car plist) :name)
14442 (setq plist (cddr plist))
14443 (insert " " (prin1-to-string (pop plist)))))
14444 (insert "\n\n#+END:\n")
14445 (beginning-of-line -2)))
14447 (defun org-prepare-dblock ()
14448 "Prepare dynamic block for refresh.
14449 This empties the block, puts the cursor at the insert position and returns
14450 the property list including an extra property :name with the block name."
14451 (unless (looking-at org-dblock-start-re)
14452 (error "Not at a dynamic block"))
14453 (let* ((begdel (1+ (match-end 0)))
14454 (name (org-no-properties (match-string 1)))
14455 (params (append (list :name name)
14456 (read (concat "(" (match-string 3) ")")))))
14457 (unless (re-search-forward org-dblock-end-re nil t)
14458 (error "Dynamic block not terminated"))
14459 (delete-region begdel (match-beginning 0))
14460 (goto-char begdel)
14461 (open-line 1)
14462 params))
14464 (defun org-map-dblocks (&optional command)
14465 "Apply COMMAND to all dynamic blocks in the current buffer.
14466 If COMMAND is not given, use `org-update-dblock'."
14467 (let ((cmd (or command 'org-update-dblock))
14468 pos)
14469 (save-excursion
14470 (goto-char (point-min))
14471 (while (re-search-forward org-dblock-start-re nil t)
14472 (goto-char (setq pos (match-beginning 0)))
14473 (condition-case nil
14474 (funcall cmd)
14475 (error (message "Error during update of dynamic block")))
14476 (goto-char pos)
14477 (unless (re-search-forward org-dblock-end-re nil t)
14478 (error "Dynamic block not terminated"))))))
14480 (defun org-dblock-update (&optional arg)
14481 "User command for updating dynamic blocks.
14482 Update the dynamic block at point. With prefix ARG, update all dynamic
14483 blocks in the buffer."
14484 (interactive "P")
14485 (if arg
14486 (org-update-all-dblocks)
14487 (or (looking-at org-dblock-start-re)
14488 (org-beginning-of-dblock))
14489 (org-update-dblock)))
14491 (defun org-update-dblock ()
14492 "Update the dynamic block at point
14493 This means to empty the block, parse for parameters and then call
14494 the correct writing function."
14495 (save-window-excursion
14496 (let* ((pos (point))
14497 (line (org-current-line))
14498 (params (org-prepare-dblock))
14499 (name (plist-get params :name))
14500 (cmd (intern (concat "org-dblock-write:" name))))
14501 (message "Updating dynamic block `%s' at line %d..." name line)
14502 (funcall cmd params)
14503 (message "Updating dynamic block `%s' at line %d...done" name line)
14504 (goto-char pos))))
14506 (defun org-beginning-of-dblock ()
14507 "Find the beginning of the dynamic block at point.
14508 Error if there is no scuh block at point."
14509 (let ((pos (point))
14510 beg)
14511 (end-of-line 1)
14512 (if (and (re-search-backward org-dblock-start-re nil t)
14513 (setq beg (match-beginning 0))
14514 (re-search-forward org-dblock-end-re nil t)
14515 (> (match-end 0) pos))
14516 (goto-char beg)
14517 (goto-char pos)
14518 (error "Not in a dynamic block"))))
14520 (defun org-update-all-dblocks ()
14521 "Update all dynamic blocks in the buffer.
14522 This function can be used in a hook."
14523 (when (org-mode-p)
14524 (org-map-dblocks 'org-update-dblock)))
14527 ;;;; Completion
14529 (defconst org-additional-option-like-keywords
14530 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14531 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14532 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14534 (defun org-complete (&optional arg)
14535 "Perform completion on word at point.
14536 At the beginning of a headline, this completes TODO keywords as given in
14537 `org-todo-keywords'.
14538 If the current word is preceded by a backslash, completes the TeX symbols
14539 that are supported for HTML support.
14540 If the current word is preceded by \"#+\", completes special words for
14541 setting file options.
14542 In the line after \"#+STARTUP:, complete valid keywords.\"
14543 At all other locations, this simply calls the value of
14544 `org-completion-fallback-command'."
14545 (interactive "P")
14546 (org-without-partial-completion
14547 (catch 'exit
14548 (let* ((end (point))
14549 (beg1 (save-excursion
14550 (skip-chars-backward (org-re "[:alnum:]_@"))
14551 (point)))
14552 (beg (save-excursion
14553 (skip-chars-backward "a-zA-Z0-9_:$")
14554 (point)))
14555 (confirm (lambda (x) (stringp (car x))))
14556 (searchhead (equal (char-before beg) ?*))
14557 (tag (and (equal (char-before beg1) ?:)
14558 (equal (char-after (point-at-bol)) ?*)))
14559 (prop (and (equal (char-before beg1) ?:)
14560 (not (equal (char-after (point-at-bol)) ?*))))
14561 (texp (equal (char-before beg) ?\\))
14562 (link (equal (char-before beg) ?\[))
14563 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14564 beg)
14565 "#+"))
14566 (startup (string-match "^#\\+STARTUP:.*"
14567 (buffer-substring (point-at-bol) (point))))
14568 (completion-ignore-case opt)
14569 (type nil)
14570 (tbl nil)
14571 (table (cond
14572 (opt
14573 (setq type :opt)
14574 (append
14575 (mapcar
14576 (lambda (x)
14577 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14578 (cons (match-string 2 x) (match-string 1 x)))
14579 (org-split-string (org-get-current-options) "\n"))
14580 (mapcar 'list org-additional-option-like-keywords)))
14581 (startup
14582 (setq type :startup)
14583 org-startup-options)
14584 (link (append org-link-abbrev-alist-local
14585 org-link-abbrev-alist))
14586 (texp
14587 (setq type :tex)
14588 org-html-entities)
14589 ((string-match "\\`\\*+[ \t]+\\'"
14590 (buffer-substring (point-at-bol) beg))
14591 (setq type :todo)
14592 (mapcar 'list org-todo-keywords-1))
14593 (searchhead
14594 (setq type :searchhead)
14595 (save-excursion
14596 (goto-char (point-min))
14597 (while (re-search-forward org-todo-line-regexp nil t)
14598 (push (list
14599 (org-make-org-heading-search-string
14600 (match-string 3) t))
14601 tbl)))
14602 tbl)
14603 (tag (setq type :tag beg beg1)
14604 (or org-tag-alist (org-get-buffer-tags)))
14605 (prop (setq type :prop beg beg1)
14606 (mapcar 'list (org-buffer-property-keys nil t t)))
14607 (t (progn
14608 (call-interactively org-completion-fallback-command)
14609 (throw 'exit nil)))))
14610 (pattern (buffer-substring-no-properties beg end))
14611 (completion (try-completion pattern table confirm)))
14612 (cond ((eq completion t)
14613 (if (not (assoc (upcase pattern) table))
14614 (message "Already complete")
14615 (if (equal type :opt)
14616 (insert (substring (cdr (assoc (upcase pattern) table))
14617 (length pattern)))
14618 (if (memq type '(:tag :prop)) (insert ":")))))
14619 ((null completion)
14620 (message "Can't find completion for \"%s\"" pattern)
14621 (ding))
14622 ((not (string= pattern completion))
14623 (delete-region beg end)
14624 (if (string-match " +$" completion)
14625 (setq completion (replace-match "" t t completion)))
14626 (insert completion)
14627 (if (get-buffer-window "*Completions*")
14628 (delete-window (get-buffer-window "*Completions*")))
14629 (if (assoc completion table)
14630 (if (eq type :todo) (insert " ")
14631 (if (memq type '(:tag :prop)) (insert ":"))))
14632 (if (and (equal type :opt) (assoc completion table))
14633 (message "%s" (substitute-command-keys
14634 "Press \\[org-complete] again to insert example settings"))))
14636 (message "Making completion list...")
14637 (let ((list (sort (all-completions pattern table confirm)
14638 'string<)))
14639 (with-output-to-temp-buffer "*Completions*"
14640 (condition-case nil
14641 ;; Protection needed for XEmacs and emacs 21
14642 (display-completion-list list pattern)
14643 (error (display-completion-list list)))))
14644 (message "Making completion list...%s" "done")))))))
14646 ;;;; TODO, DEADLINE, Comments
14648 (defun org-toggle-comment ()
14649 "Change the COMMENT state of an entry."
14650 (interactive)
14651 (save-excursion
14652 (org-back-to-heading)
14653 (let (case-fold-search)
14654 (if (looking-at (concat outline-regexp
14655 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14656 (replace-match "" t t nil 1)
14657 (if (looking-at outline-regexp)
14658 (progn
14659 (goto-char (match-end 0))
14660 (insert org-comment-string " ")))))))
14662 (defvar org-last-todo-state-is-todo nil
14663 "This is non-nil when the last TODO state change led to a TODO state.
14664 If the last change removed the TODO tag or switched to DONE, then
14665 this is nil.")
14667 (defvar org-setting-tags nil) ; dynamically skiped
14669 ;; FIXME: better place
14670 (defun org-property-or-variable-value (var &optional inherit)
14671 "Check if there is a property fixing the value of VAR.
14672 If yes, return this value. If not, return the current value of the variable."
14673 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14674 (if (and prop (stringp prop) (string-match "\\S-" prop))
14675 (read prop)
14676 (symbol-value var))))
14678 (defun org-parse-local-options (string var)
14679 "Parse STRING for startup setting relevant for variable VAR."
14680 (let ((rtn (symbol-value var))
14681 e opts)
14682 (save-match-data
14683 (if (or (not string) (not (string-match "\\S-" string)))
14685 (setq opts (delq nil (mapcar (lambda (x)
14686 (setq e (assoc x org-startup-options))
14687 (if (eq (nth 1 e) var) e nil))
14688 (org-split-string string "[ \t]+"))))
14689 (if (not opts)
14691 (setq rtn nil)
14692 (while (setq e (pop opts))
14693 (if (not (nth 3 e))
14694 (setq rtn (nth 2 e))
14695 (if (not (listp rtn)) (setq rtn nil))
14696 (push (nth 2 e) rtn)))
14697 rtn)))))
14699 (defvar org-blocker-hook nil
14700 "Hook for functions that are allowed to block a state change.
14702 Each function gets as its single argument a property list, see
14703 `org-trigger-hook' for more information about this list.
14705 If any of the functions in this hook returns nil, the state change
14706 is blocked.")
14708 (defvar org-trigger-hook nil
14709 "Hook for functions that are triggered by a state change.
14711 Each function gets as its single argument a property list with at least
14712 the following elements:
14714 (:type type-of-change :position pos-at-entry-start
14715 :from old-state :to new-state)
14717 Depending on the type, more properties may be present.
14719 This mechanism is currently implemented for:
14721 TODO state changes
14722 ------------------
14723 :type todo-state-change
14724 :from previous state (keyword as a string), or nil
14725 :to new state (keyword as a string), or nil")
14728 (defun org-todo (&optional arg)
14729 "Change the TODO state of an item.
14730 The state of an item is given by a keyword at the start of the heading,
14731 like
14732 *** TODO Write paper
14733 *** DONE Call mom
14735 The different keywords are specified in the variable `org-todo-keywords'.
14736 By default the available states are \"TODO\" and \"DONE\".
14737 So for this example: when the item starts with TODO, it is changed to DONE.
14738 When it starts with DONE, the DONE is removed. And when neither TODO nor
14739 DONE are present, add TODO at the beginning of the heading.
14741 With C-u prefix arg, use completion to determine the new state.
14742 With numeric prefix arg, switch to that state.
14744 For calling through lisp, arg is also interpreted in the following way:
14745 'none -> empty state
14746 \"\"(empty string) -> switch to empty state
14747 'done -> switch to DONE
14748 'nextset -> switch to the next set of keywords
14749 'previousset -> switch to the previous set of keywords
14750 \"WAITING\" -> switch to the specified keyword, but only if it
14751 really is a member of `org-todo-keywords'."
14752 (interactive "P")
14753 (save-excursion
14754 (catch 'exit
14755 (org-back-to-heading)
14756 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14757 (or (looking-at (concat " +" org-todo-regexp " *"))
14758 (looking-at " *"))
14759 (let* ((match-data (match-data))
14760 (startpos (point-at-bol))
14761 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14762 (org-log-done org-log-done)
14763 (org-log-repeat org-log-repeat)
14764 (org-todo-log-states org-todo-log-states)
14765 (this (match-string 1))
14766 (hl-pos (match-beginning 0))
14767 (head (org-get-todo-sequence-head this))
14768 (ass (assoc head org-todo-kwd-alist))
14769 (interpret (nth 1 ass))
14770 (done-word (nth 3 ass))
14771 (final-done-word (nth 4 ass))
14772 (last-state (or this ""))
14773 (completion-ignore-case t)
14774 (member (member this org-todo-keywords-1))
14775 (tail (cdr member))
14776 (state (cond
14777 ((and org-todo-key-trigger
14778 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14779 (and (not arg) org-use-fast-todo-selection
14780 (not (eq org-use-fast-todo-selection 'prefix)))))
14781 ;; Use fast selection
14782 (org-fast-todo-selection))
14783 ((and (equal arg '(4))
14784 (or (not org-use-fast-todo-selection)
14785 (not org-todo-key-trigger)))
14786 ;; Read a state with completion
14787 (completing-read "State: " (mapcar (lambda(x) (list x))
14788 org-todo-keywords-1)
14789 nil t))
14790 ((eq arg 'right)
14791 (if this
14792 (if tail (car tail) nil)
14793 (car org-todo-keywords-1)))
14794 ((eq arg 'left)
14795 (if (equal member org-todo-keywords-1)
14797 (if this
14798 (nth (- (length org-todo-keywords-1) (length tail) 2)
14799 org-todo-keywords-1)
14800 (org-last org-todo-keywords-1))))
14801 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14802 (setq arg nil))) ; hack to fall back to cycling
14803 (arg
14804 ;; user or caller requests a specific state
14805 (cond
14806 ((equal arg "") nil)
14807 ((eq arg 'none) nil)
14808 ((eq arg 'done) (or done-word (car org-done-keywords)))
14809 ((eq arg 'nextset)
14810 (or (car (cdr (member head org-todo-heads)))
14811 (car org-todo-heads)))
14812 ((eq arg 'previousset)
14813 (let ((org-todo-heads (reverse org-todo-heads)))
14814 (or (car (cdr (member head org-todo-heads)))
14815 (car org-todo-heads))))
14816 ((car (member arg org-todo-keywords-1)))
14817 ((nth (1- (prefix-numeric-value arg))
14818 org-todo-keywords-1))))
14819 ((null member) (or head (car org-todo-keywords-1)))
14820 ((equal this final-done-word) nil) ;; -> make empty
14821 ((null tail) nil) ;; -> first entry
14822 ((eq interpret 'sequence)
14823 (car tail))
14824 ((memq interpret '(type priority))
14825 (if (eq this-command last-command)
14826 (car tail)
14827 (if (> (length tail) 0)
14828 (or done-word (car org-done-keywords))
14829 nil)))
14830 (t nil)))
14831 (next (if state (concat " " state " ") " "))
14832 (change-plist (list :type 'todo-state-change :from this :to state
14833 :position startpos))
14834 dolog now-done-p)
14835 (when org-blocker-hook
14836 (unless (save-excursion
14837 (save-match-data
14838 (run-hook-with-args-until-failure
14839 'org-blocker-hook change-plist)))
14840 (if (interactive-p)
14841 (error "TODO state change from %s to %s blocked" this state)
14842 ;; fail silently
14843 (message "TODO state change from %s to %s blocked" this state)
14844 (throw 'exit nil))))
14845 (store-match-data match-data)
14846 (replace-match next t t)
14847 (unless (pos-visible-in-window-p hl-pos)
14848 (message "TODO state changed to %s" (org-trim next)))
14849 (unless head
14850 (setq head (org-get-todo-sequence-head state)
14851 ass (assoc head org-todo-kwd-alist)
14852 interpret (nth 1 ass)
14853 done-word (nth 3 ass)
14854 final-done-word (nth 4 ass)))
14855 (when (memq arg '(nextset previousset))
14856 (message "Keyword-Set %d/%d: %s"
14857 (- (length org-todo-sets) -1
14858 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14859 (length org-todo-sets)
14860 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14861 (setq org-last-todo-state-is-todo
14862 (not (member state org-done-keywords)))
14863 (setq now-done-p (and (member state org-done-keywords)
14864 (not (member this org-done-keywords))))
14865 (and logging (org-local-logging logging))
14866 (when (and (or org-todo-log-states org-log-done)
14867 (not (memq arg '(nextset previousset))))
14868 ;; we need to look at recording a time and note
14869 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14870 (nth 2 (assoc this org-todo-log-states))))
14871 (when (and state
14872 (member state org-not-done-keywords)
14873 (not (member this org-not-done-keywords)))
14874 ;; This is now a todo state and was not one before
14875 ;; If there was a CLOSED time stamp, get rid of it.
14876 (org-add-planning-info nil nil 'closed))
14877 (when (and now-done-p org-log-done)
14878 ;; It is now done, and it was not done before
14879 (org-add-planning-info 'closed (org-current-time))
14880 (if (and (not dolog) (eq 'note org-log-done))
14881 (org-add-log-maybe 'done state 'findpos 'note)))
14882 (when (and state dolog)
14883 ;; This is a non-nil state, and we need to log it
14884 (org-add-log-maybe 'state state 'findpos dolog)))
14885 ;; Fixup tag positioning
14886 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14887 (run-hooks 'org-after-todo-state-change-hook)
14888 (if (and arg (not (member state org-done-keywords)))
14889 (setq head (org-get-todo-sequence-head state)))
14890 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14891 ;; Do we need to trigger a repeat?
14892 (when now-done-p (org-auto-repeat-maybe state))
14893 ;; Fixup cursor location if close to the keyword
14894 (if (and (outline-on-heading-p)
14895 (not (bolp))
14896 (save-excursion (beginning-of-line 1)
14897 (looking-at org-todo-line-regexp))
14898 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14899 (progn
14900 (goto-char (or (match-end 2) (match-end 1)))
14901 (just-one-space)))
14902 (when org-trigger-hook
14903 (save-excursion
14904 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14906 (defun org-local-logging (value)
14907 "Get logging settings from a property VALUE."
14908 (let* (words w a)
14909 ;; directly set the variables, they are already local.
14910 (setq org-log-done nil
14911 org-log-repeat nil
14912 org-todo-log-states nil)
14913 (setq words (org-split-string value))
14914 (while (setq w (pop words))
14915 (cond
14916 ((setq a (assoc w org-startup-options))
14917 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14918 (set (nth 1 a) (nth 2 a))))
14919 ((setq a (org-extract-log-state-settings w))
14920 (and (member (car a) org-todo-keywords-1)
14921 (push a org-todo-log-states)))))))
14923 (defun org-get-todo-sequence-head (kwd)
14924 "Return the head of the TODO sequence to which KWD belongs.
14925 If KWD is not set, check if there is a text property remembering the
14926 right sequence."
14927 (let (p)
14928 (cond
14929 ((not kwd)
14930 (or (get-text-property (point-at-bol) 'org-todo-head)
14931 (progn
14932 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14933 nil (point-at-eol)))
14934 (get-text-property p 'org-todo-head))))
14935 ((not (member kwd org-todo-keywords-1))
14936 (car org-todo-keywords-1))
14937 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14939 (defun org-fast-todo-selection ()
14940 "Fast TODO keyword selection with single keys.
14941 Returns the new TODO keyword, or nil if no state change should occur."
14942 (let* ((fulltable org-todo-key-alist)
14943 (done-keywords org-done-keywords) ;; needed for the faces.
14944 (maxlen (apply 'max (mapcar
14945 (lambda (x)
14946 (if (stringp (car x)) (string-width (car x)) 0))
14947 fulltable)))
14948 (expert nil)
14949 (fwidth (+ maxlen 3 1 3))
14950 (ncol (/ (- (window-width) 4) fwidth))
14951 tg cnt e c tbl
14952 groups ingroup)
14953 (save-window-excursion
14954 (if expert
14955 (set-buffer (get-buffer-create " *Org todo*"))
14956 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14957 (erase-buffer)
14958 (org-set-local 'org-done-keywords done-keywords)
14959 (setq tbl fulltable cnt 0)
14960 (while (setq e (pop tbl))
14961 (cond
14962 ((equal e '(:startgroup))
14963 (push '() groups) (setq ingroup t)
14964 (when (not (= cnt 0))
14965 (setq cnt 0)
14966 (insert "\n"))
14967 (insert "{ "))
14968 ((equal e '(:endgroup))
14969 (setq ingroup nil cnt 0)
14970 (insert "}\n"))
14972 (setq tg (car e) c (cdr e))
14973 (if ingroup (push tg (car groups)))
14974 (setq tg (org-add-props tg nil 'face
14975 (org-get-todo-face tg)))
14976 (if (and (= cnt 0) (not ingroup)) (insert " "))
14977 (insert "[" c "] " tg (make-string
14978 (- fwidth 4 (length tg)) ?\ ))
14979 (when (= (setq cnt (1+ cnt)) ncol)
14980 (insert "\n")
14981 (if ingroup (insert " "))
14982 (setq cnt 0)))))
14983 (insert "\n")
14984 (goto-char (point-min))
14985 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14986 (fit-window-to-buffer))
14987 (message "[a-z..]:Set [SPC]:clear")
14988 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14989 (cond
14990 ((or (= c ?\C-g)
14991 (and (= c ?q) (not (rassoc c fulltable))))
14992 (setq quit-flag t))
14993 ((= c ?\ ) nil)
14994 ((setq e (rassoc c fulltable) tg (car e))
14996 (t (setq quit-flag t))))))
14998 (defun org-get-repeat ()
14999 "Check if tere is a deadline/schedule with repeater in this entry."
15000 (save-match-data
15001 (save-excursion
15002 (org-back-to-heading t)
15003 (if (re-search-forward
15004 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
15005 (match-string 1)))))
15007 (defvar org-last-changed-timestamp)
15008 (defvar org-log-post-message)
15009 (defvar org-log-note-purpose)
15010 (defun org-auto-repeat-maybe (done-word)
15011 "Check if the current headline contains a repeated deadline/schedule.
15012 If yes, set TODO state back to what it was and change the base date
15013 of repeating deadline/scheduled time stamps to new date.
15014 This function is run automatically after each state change to a DONE state."
15015 ;; last-state is dynamically scoped into this function
15016 (let* ((repeat (org-get-repeat))
15017 (aa (assoc last-state org-todo-kwd-alist))
15018 (interpret (nth 1 aa))
15019 (head (nth 2 aa))
15020 (whata '(("d" . day) ("m" . month) ("y" . year)))
15021 (msg "Entry repeats: ")
15022 (org-log-done nil)
15023 (org-todo-log-states nil)
15024 (nshiftmax 10) (nshift 0)
15025 re type n what ts mb0 time)
15026 (when repeat
15027 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
15028 (org-todo (if (eq interpret 'type) last-state head))
15029 (when (and org-log-repeat
15030 (or (not (memq 'org-add-log-note
15031 (default-value 'post-command-hook)))
15032 (eq org-log-note-purpose 'done)))
15033 ;; Make sure a note is taken;
15034 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
15035 'findpos org-log-repeat))
15036 (org-back-to-heading t)
15037 (org-add-planning-info nil nil 'closed)
15038 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
15039 org-deadline-time-regexp "\\)\\|\\("
15040 org-ts-regexp "\\)"))
15041 (while (re-search-forward
15042 re (save-excursion (outline-next-heading) (point)) t)
15043 (setq type (if (match-end 1) org-scheduled-string
15044 (if (match-end 3) org-deadline-string "Plain:"))
15045 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
15046 mb0 (match-beginning 0))
15047 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
15048 (setq n (string-to-number (match-string 2 ts))
15049 what (match-string 3 ts))
15050 (if (equal what "w") (setq n (* n 7) what "d"))
15051 ;; Preparation, see if we need to modify the start date for the change
15052 (when (match-end 1)
15053 (setq time (save-match-data (org-time-string-to-time ts)))
15054 (cond
15055 ((equal (match-string 1 ts) ".")
15056 ;; Shift starting date to today
15057 (org-timestamp-change
15058 (- (time-to-days (current-time)) (time-to-days time))
15059 'day))
15060 ((equal (match-string 1 ts) "+")
15061 (while (< (time-to-days time) (time-to-days (current-time)))
15062 (when (= (incf nshift) nshiftmax)
15063 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
15064 (error "Abort")))
15065 (org-timestamp-change n (cdr (assoc what whata)))
15066 (sit-for .0001) ;; so we can watch the date shifting
15067 (org-at-timestamp-p t)
15068 (setq ts (match-string 1))
15069 (setq time (save-match-data (org-time-string-to-time ts))))
15070 (org-timestamp-change (- n) (cdr (assoc what whata)))
15071 ;; rematch, so that we have everything in place for the real shift
15072 (org-at-timestamp-p t)
15073 (setq ts (match-string 1))
15074 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
15075 (org-timestamp-change n (cdr (assoc what whata)))
15076 (setq msg (concat msg type org-last-changed-timestamp " "))))
15077 (setq org-log-post-message msg)
15078 (message "%s" msg))))
15080 (defun org-show-todo-tree (arg)
15081 "Make a compact tree which shows all headlines marked with TODO.
15082 The tree will show the lines where the regexp matches, and all higher
15083 headlines above the match.
15084 With a \\[universal-argument] prefix, also show the DONE entries.
15085 With a numeric prefix N, construct a sparse tree for the Nth element
15086 of `org-todo-keywords-1'."
15087 (interactive "P")
15088 (let ((case-fold-search nil)
15089 (kwd-re
15090 (cond ((null arg) org-not-done-regexp)
15091 ((equal arg '(4))
15092 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15093 (mapcar 'list org-todo-keywords-1))))
15094 (concat "\\("
15095 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15096 "\\)\\>")))
15097 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15098 (regexp-quote (nth (1- (prefix-numeric-value arg))
15099 org-todo-keywords-1)))
15100 (t (error "Invalid prefix argument: %s" arg)))))
15101 (message "%d TODO entries found"
15102 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15104 (defun org-deadline (&optional remove)
15105 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15106 With argument REMOVE, remove any deadline from the item."
15107 (interactive "P")
15108 (if remove
15109 (progn
15110 (org-remove-timestamp-with-keyword org-deadline-string)
15111 (message "Item no longer has a deadline."))
15112 (org-add-planning-info 'deadline nil 'closed)))
15114 (defun org-schedule (&optional remove)
15115 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15116 With argument REMOVE, remove any scheduling date from the item."
15117 (interactive "P")
15118 (if remove
15119 (progn
15120 (org-remove-timestamp-with-keyword org-scheduled-string)
15121 (message "Item is no longer scheduled."))
15122 (org-add-planning-info 'scheduled nil 'closed)))
15124 (defun org-remove-timestamp-with-keyword (keyword)
15125 "Remove all time stamps with KEYWORD in the current entry."
15126 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15127 beg)
15128 (save-excursion
15129 (org-back-to-heading t)
15130 (setq beg (point))
15131 (org-end-of-subtree t t)
15132 (while (re-search-backward re beg t)
15133 (replace-match "")
15134 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15135 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15137 (defun org-add-planning-info (what &optional time &rest remove)
15138 "Insert new timestamp with keyword in the line directly after the headline.
15139 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15140 If non is given, the user is prompted for a date.
15141 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15142 be removed."
15143 (interactive)
15144 (let (org-time-was-given org-end-time-was-given)
15145 (when what (setq time (or time (org-read-date nil 'to-time))))
15146 (when (and org-insert-labeled-timestamps-at-point
15147 (member what '(scheduled deadline)))
15148 (insert
15149 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15150 (org-insert-time-stamp time org-time-was-given
15151 nil nil nil (list org-end-time-was-given))
15152 (setq what nil))
15153 (save-excursion
15154 (save-restriction
15155 (let (col list elt ts buffer-invisibility-spec)
15156 (org-back-to-heading t)
15157 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15158 (goto-char (match-end 1))
15159 (setq col (current-column))
15160 (goto-char (match-end 0))
15161 (if (eobp) (insert "\n") (forward-char 1))
15162 (if (and (not (looking-at outline-regexp))
15163 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15164 "[^\r\n]*"))
15165 (not (equal (match-string 1) org-clock-string)))
15166 (narrow-to-region (match-beginning 0) (match-end 0))
15167 (insert-before-markers "\n")
15168 (backward-char 1)
15169 (narrow-to-region (point) (point))
15170 (indent-to-column col))
15171 ;; Check if we have to remove something.
15172 (setq list (cons what remove))
15173 (while list
15174 (setq elt (pop list))
15175 (goto-char (point-min))
15176 (when (or (and (eq elt 'scheduled)
15177 (re-search-forward org-scheduled-time-regexp nil t))
15178 (and (eq elt 'deadline)
15179 (re-search-forward org-deadline-time-regexp nil t))
15180 (and (eq elt 'closed)
15181 (re-search-forward org-closed-time-regexp nil t)))
15182 (replace-match "")
15183 (if (looking-at "--+<[^>]+>") (replace-match ""))
15184 (if (looking-at " +") (replace-match ""))))
15185 (goto-char (point-max))
15186 (when what
15187 (insert
15188 (if (not (equal (char-before) ?\ )) " " "")
15189 (cond ((eq what 'scheduled) org-scheduled-string)
15190 ((eq what 'deadline) org-deadline-string)
15191 ((eq what 'closed) org-closed-string))
15192 " ")
15193 (setq ts (org-insert-time-stamp
15194 time
15195 (or org-time-was-given
15196 (and (eq what 'closed) org-log-done-with-time))
15197 (eq what 'closed)
15198 nil nil (list org-end-time-was-given)))
15199 (end-of-line 1))
15200 (goto-char (point-min))
15201 (widen)
15202 (if (looking-at "[ \t]+\r?\n")
15203 (replace-match ""))
15204 ts)))))
15206 (defvar org-log-note-marker (make-marker))
15207 (defvar org-log-note-purpose nil)
15208 (defvar org-log-note-state nil)
15209 (defvar org-log-note-how nil)
15210 (defvar org-log-note-window-configuration nil)
15211 (defvar org-log-note-return-to (make-marker))
15212 (defvar org-log-post-message nil
15213 "Message to be displayed after a log note has been stored.
15214 The auto-repeater uses this.")
15216 (defun org-add-log-maybe (&optional purpose state findpos how)
15217 "Set up the post command hook to take a note.
15218 If this is about to TODO state change, the new state is expected in STATE.
15219 When FINDPOS is non-nil, find the correct position for the note in
15220 the current entry. If not, assume that it can be inserted at point."
15221 (save-excursion
15222 (when findpos
15223 (org-back-to-heading t)
15224 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15225 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15226 "[^\r\n]*\\)?"))
15227 (goto-char (match-end 0))
15228 (unless org-log-states-order-reversed
15229 (and (= (char-after) ?\n) (forward-char 1))
15230 (org-skip-over-state-notes)
15231 (skip-chars-backward " \t\n\r")))
15232 (move-marker org-log-note-marker (point))
15233 (setq org-log-note-purpose purpose
15234 org-log-note-state state
15235 org-log-note-how how)
15236 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15238 (defun org-skip-over-state-notes ()
15239 "Skip past the list of State notes in an entry."
15240 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15241 (while (looking-at "[ \t]*- State")
15242 (condition-case nil
15243 (org-next-item)
15244 (error (org-end-of-item)))))
15246 (defun org-add-log-note (&optional purpose)
15247 "Pop up a window for taking a note, and add this note later at point."
15248 (remove-hook 'post-command-hook 'org-add-log-note)
15249 (setq org-log-note-window-configuration (current-window-configuration))
15250 (delete-other-windows)
15251 (move-marker org-log-note-return-to (point))
15252 (switch-to-buffer (marker-buffer org-log-note-marker))
15253 (goto-char org-log-note-marker)
15254 (org-switch-to-buffer-other-window "*Org Note*")
15255 (erase-buffer)
15256 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15257 (org-store-log-note)
15258 (let ((org-inhibit-startup t)) (org-mode))
15259 (insert (format "# Insert note for %s.
15260 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15261 (cond
15262 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15263 ((eq org-log-note-purpose 'done) "closed todo item")
15264 ((eq org-log-note-purpose 'state)
15265 (format "state change to \"%s\"" org-log-note-state))
15266 (t (error "This should not happen")))))
15267 (org-set-local 'org-finish-function 'org-store-log-note)))
15269 (defun org-store-log-note ()
15270 "Finish taking a log note, and insert it to where it belongs."
15271 (let ((txt (buffer-string))
15272 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15273 lines ind)
15274 (kill-buffer (current-buffer))
15275 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15276 (setq txt (replace-match "" t t txt)))
15277 (if (string-match "\\s-+\\'" txt)
15278 (setq txt (replace-match "" t t txt)))
15279 (setq lines (org-split-string txt "\n"))
15280 (when (and note (string-match "\\S-" note))
15281 (setq note
15282 (org-replace-escapes
15283 note
15284 (list (cons "%u" (user-login-name))
15285 (cons "%U" user-full-name)
15286 (cons "%t" (format-time-string
15287 (org-time-stamp-format 'long 'inactive)
15288 (current-time)))
15289 (cons "%s" (if org-log-note-state
15290 (concat "\"" org-log-note-state "\"")
15291 "")))))
15292 (if lines (setq note (concat note " \\\\")))
15293 (push note lines))
15294 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15295 (when lines
15296 (save-excursion
15297 (set-buffer (marker-buffer org-log-note-marker))
15298 (save-excursion
15299 (goto-char org-log-note-marker)
15300 (move-marker org-log-note-marker nil)
15301 (end-of-line 1)
15302 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15303 (indent-relative nil)
15304 (insert "- " (pop lines))
15305 (org-indent-line-function)
15306 (beginning-of-line 1)
15307 (looking-at "[ \t]*")
15308 (setq ind (concat (match-string 0) " "))
15309 (end-of-line 1)
15310 (while lines (insert "\n" ind (pop lines)))))))
15311 (set-window-configuration org-log-note-window-configuration)
15312 (with-current-buffer (marker-buffer org-log-note-return-to)
15313 (goto-char org-log-note-return-to))
15314 (move-marker org-log-note-return-to nil)
15315 (and org-log-post-message (message "%s" org-log-post-message)))
15317 ;; FIXME: what else would be useful?
15318 ;; - priority
15319 ;; - date
15321 (defun org-sparse-tree (&optional arg)
15322 "Create a sparse tree, prompt for the details.
15323 This command can create sparse trees. You first need to select the type
15324 of match used to create the tree:
15326 t Show entries with a specific TODO keyword.
15327 T Show entries selected by a tags match.
15328 p Enter a property name and its value (both with completion on existing
15329 names/values) and show entries with that property.
15330 r Show entries matching a regular expression
15331 d Show deadlines due within `org-deadline-warning-days'."
15332 (interactive "P")
15333 (let (ans kwd value)
15334 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15335 (setq ans (read-char-exclusive))
15336 (cond
15337 ((equal ans ?d)
15338 (call-interactively 'org-check-deadlines))
15339 ((equal ans ?b)
15340 (call-interactively 'org-check-before-date))
15341 ((equal ans ?t)
15342 (org-show-todo-tree '(4)))
15343 ((equal ans ?T)
15344 (call-interactively 'org-tags-sparse-tree))
15345 ((member ans '(?p ?P))
15346 (setq kwd (completing-read "Property: "
15347 (mapcar 'list (org-buffer-property-keys))))
15348 (setq value (completing-read "Value: "
15349 (mapcar 'list (org-property-values kwd))))
15350 (unless (string-match "\\`{.*}\\'" value)
15351 (setq value (concat "\"" value "\"")))
15352 (org-tags-sparse-tree arg (concat kwd "=" value)))
15353 ((member ans '(?r ?R ?/))
15354 (call-interactively 'org-occur))
15355 (t (error "No such sparse tree command \"%c\"" ans)))))
15357 (defvar org-occur-highlights nil
15358 "List of overlays used for occur matches.")
15359 (make-variable-buffer-local 'org-occur-highlights)
15360 (defvar org-occur-parameters nil
15361 "Parameters of the active org-occur calls.
15362 This is a list, each call to org-occur pushes as cons cell,
15363 containing the regular expression and the callback, onto the list.
15364 The list can contain several entries if `org-occur' has been called
15365 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15366 will only contain one set of parameters. When the highlights are
15367 removed (for example with `C-c C-c', or with the next edit (depending
15368 on `org-remove-highlights-with-change'), this variable is emptied
15369 as well.")
15370 (make-variable-buffer-local 'org-occur-parameters)
15372 (defun org-occur (regexp &optional keep-previous callback)
15373 "Make a compact tree which shows all matches of REGEXP.
15374 The tree will show the lines where the regexp matches, and all higher
15375 headlines above the match. It will also show the heading after the match,
15376 to make sure editing the matching entry is easy.
15377 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15378 call to `org-occur' will be kept, to allow stacking of calls to this
15379 command.
15380 If CALLBACK is non-nil, it is a function which is called to confirm
15381 that the match should indeed be shown."
15382 (interactive "sRegexp: \nP")
15383 (unless keep-previous
15384 (org-remove-occur-highlights nil nil t))
15385 (push (cons regexp callback) org-occur-parameters)
15386 (let ((cnt 0))
15387 (save-excursion
15388 (goto-char (point-min))
15389 (if (or (not keep-previous) ; do not want to keep
15390 (not org-occur-highlights)) ; no previous matches
15391 ;; hide everything
15392 (org-overview))
15393 (while (re-search-forward regexp nil t)
15394 (when (or (not callback)
15395 (save-match-data (funcall callback)))
15396 (setq cnt (1+ cnt))
15397 (when org-highlight-sparse-tree-matches
15398 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15399 (org-show-context 'occur-tree))))
15400 (when org-remove-highlights-with-change
15401 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15402 nil 'local))
15403 (unless org-sparse-tree-open-archived-trees
15404 (org-hide-archived-subtrees (point-min) (point-max)))
15405 (run-hooks 'org-occur-hook)
15406 (if (interactive-p)
15407 (message "%d match(es) for regexp %s" cnt regexp))
15408 cnt))
15410 (defun org-show-context (&optional key)
15411 "Make sure point and context and visible.
15412 How much context is shown depends upon the variables
15413 `org-show-hierarchy-above', `org-show-following-heading'. and
15414 `org-show-siblings'."
15415 (let ((heading-p (org-on-heading-p t))
15416 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15417 (following-p (org-get-alist-option org-show-following-heading key))
15418 (entry-p (org-get-alist-option org-show-entry-below key))
15419 (siblings-p (org-get-alist-option org-show-siblings key)))
15420 (catch 'exit
15421 ;; Show heading or entry text
15422 (if (and heading-p (not entry-p))
15423 (org-flag-heading nil) ; only show the heading
15424 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15425 (org-show-hidden-entry))) ; show entire entry
15426 (when following-p
15427 ;; Show next sibling, or heading below text
15428 (save-excursion
15429 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15430 (org-flag-heading nil))))
15431 (when siblings-p (org-show-siblings))
15432 (when hierarchy-p
15433 ;; show all higher headings, possibly with siblings
15434 (save-excursion
15435 (while (and (condition-case nil
15436 (progn (org-up-heading-all 1) t)
15437 (error nil))
15438 (not (bobp)))
15439 (org-flag-heading nil)
15440 (when siblings-p (org-show-siblings))))))))
15442 (defun org-reveal (&optional siblings)
15443 "Show current entry, hierarchy above it, and the following headline.
15444 This can be used to show a consistent set of context around locations
15445 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15446 not t for the search context.
15448 With optional argument SIBLINGS, on each level of the hierarchy all
15449 siblings are shown. This repairs the tree structure to what it would
15450 look like when opened with hierarchical calls to `org-cycle'."
15451 (interactive "P")
15452 (let ((org-show-hierarchy-above t)
15453 (org-show-following-heading t)
15454 (org-show-siblings (if siblings t org-show-siblings)))
15455 (org-show-context nil)))
15457 (defun org-highlight-new-match (beg end)
15458 "Highlight from BEG to END and mark the highlight is an occur headline."
15459 (let ((ov (org-make-overlay beg end)))
15460 (org-overlay-put ov 'face 'secondary-selection)
15461 (push ov org-occur-highlights)))
15463 (defun org-remove-occur-highlights (&optional beg end noremove)
15464 "Remove the occur highlights from the buffer.
15465 BEG and END are ignored. If NOREMOVE is nil, remove this function
15466 from the `before-change-functions' in the current buffer."
15467 (interactive)
15468 (unless org-inhibit-highlight-removal
15469 (mapc 'org-delete-overlay org-occur-highlights)
15470 (setq org-occur-highlights nil)
15471 (setq org-occur-parameters nil)
15472 (unless noremove
15473 (remove-hook 'before-change-functions
15474 'org-remove-occur-highlights 'local))))
15476 ;;;; Priorities
15478 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15479 "Regular expression matching the priority indicator.")
15481 (defvar org-remove-priority-next-time nil)
15483 (defun org-priority-up ()
15484 "Increase the priority of the current item."
15485 (interactive)
15486 (org-priority 'up))
15488 (defun org-priority-down ()
15489 "Decrease the priority of the current item."
15490 (interactive)
15491 (org-priority 'down))
15493 (defun org-priority (&optional action)
15494 "Change the priority of an item by ARG.
15495 ACTION can be `set', `up', `down', or a character."
15496 (interactive)
15497 (setq action (or action 'set))
15498 (let (current new news have remove)
15499 (save-excursion
15500 (org-back-to-heading)
15501 (if (looking-at org-priority-regexp)
15502 (setq current (string-to-char (match-string 2))
15503 have t)
15504 (setq current org-default-priority))
15505 (cond
15506 ((or (eq action 'set) (integerp action))
15507 (if (integerp action)
15508 (setq new action)
15509 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15510 (setq new (read-char-exclusive)))
15511 (if (and (= (upcase org-highest-priority) org-highest-priority)
15512 (= (upcase org-lowest-priority) org-lowest-priority))
15513 (setq new (upcase new)))
15514 (cond ((equal new ?\ ) (setq remove t))
15515 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15516 (error "Priority must be between `%c' and `%c'"
15517 org-highest-priority org-lowest-priority))))
15518 ((eq action 'up)
15519 (if (and (not have) (eq last-command this-command))
15520 (setq new org-lowest-priority)
15521 (setq new (if (and org-priority-start-cycle-with-default (not have))
15522 org-default-priority (1- current)))))
15523 ((eq action 'down)
15524 (if (and (not have) (eq last-command this-command))
15525 (setq new org-highest-priority)
15526 (setq new (if (and org-priority-start-cycle-with-default (not have))
15527 org-default-priority (1+ current)))))
15528 (t (error "Invalid action")))
15529 (if (or (< (upcase new) org-highest-priority)
15530 (> (upcase new) org-lowest-priority))
15531 (setq remove t))
15532 (setq news (format "%c" new))
15533 (if have
15534 (if remove
15535 (replace-match "" t t nil 1)
15536 (replace-match news t t nil 2))
15537 (if remove
15538 (error "No priority cookie found in line")
15539 (looking-at org-todo-line-regexp)
15540 (if (match-end 2)
15541 (progn
15542 (goto-char (match-end 2))
15543 (insert " [#" news "]"))
15544 (goto-char (match-beginning 3))
15545 (insert "[#" news "] ")))))
15546 (org-preserve-lc (org-set-tags nil 'align))
15547 (if remove
15548 (message "Priority removed")
15549 (message "Priority of current item set to %s" news))))
15552 (defun org-get-priority (s)
15553 "Find priority cookie and return priority."
15554 (save-match-data
15555 (if (not (string-match org-priority-regexp s))
15556 (* 1000 (- org-lowest-priority org-default-priority))
15557 (* 1000 (- org-lowest-priority
15558 (string-to-char (match-string 2 s)))))))
15560 ;;;; Tags
15562 (defun org-scan-tags (action matcher &optional todo-only)
15563 "Scan headline tags with inheritance and produce output ACTION.
15564 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15565 evaluated, testing if a given set of tags qualifies a headline for
15566 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15567 are included in the output."
15568 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15569 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15570 (org-re
15571 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15572 (props (list 'face nil
15573 'done-face 'org-done
15574 'undone-face nil
15575 'mouse-face 'highlight
15576 'org-not-done-regexp org-not-done-regexp
15577 'org-todo-regexp org-todo-regexp
15578 'keymap org-agenda-keymap
15579 'help-echo
15580 (format "mouse-2 or RET jump to org file %s"
15581 (abbreviate-file-name
15582 (or (buffer-file-name (buffer-base-buffer))
15583 (buffer-name (buffer-base-buffer)))))))
15584 (case-fold-search nil)
15585 lspos
15586 tags tags-list tags-alist (llast 0) rtn level category i txt
15587 todo marker entry priority)
15588 (save-excursion
15589 (goto-char (point-min))
15590 (when (eq action 'sparse-tree)
15591 (org-overview)
15592 (org-remove-occur-highlights))
15593 (while (re-search-forward re nil t)
15594 (catch :skip
15595 (setq todo (if (match-end 1) (match-string 2))
15596 tags (if (match-end 4) (match-string 4)))
15597 (goto-char (setq lspos (1+ (match-beginning 0))))
15598 (setq level (org-reduced-level (funcall outline-level))
15599 category (org-get-category))
15600 (setq i llast llast level)
15601 ;; remove tag lists from same and sublevels
15602 (while (>= i level)
15603 (when (setq entry (assoc i tags-alist))
15604 (setq tags-alist (delete entry tags-alist)))
15605 (setq i (1- i)))
15606 ;; add the nex tags
15607 (when tags
15608 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15609 tags-alist
15610 (cons (cons level tags) tags-alist)))
15611 ;; compile tags for current headline
15612 (setq tags-list
15613 (if org-use-tag-inheritance
15614 (apply 'append (mapcar 'cdr tags-alist))
15615 tags))
15616 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15617 (eval matcher)
15618 (or (not org-agenda-skip-archived-trees)
15619 (not (member org-archive-tag tags-list))))
15620 (and (eq action 'agenda) (org-agenda-skip))
15621 ;; list this headline
15623 (if (eq action 'sparse-tree)
15624 (progn
15625 (and org-highlight-sparse-tree-matches
15626 (org-get-heading) (match-end 0)
15627 (org-highlight-new-match
15628 (match-beginning 0) (match-beginning 1)))
15629 (org-show-context 'tags-tree))
15630 (setq txt (org-format-agenda-item
15632 (concat
15633 (if org-tags-match-list-sublevels
15634 (make-string (1- level) ?.) "")
15635 (org-get-heading))
15636 category tags-list)
15637 priority (org-get-priority txt))
15638 (goto-char lspos)
15639 (setq marker (org-agenda-new-marker))
15640 (org-add-props txt props
15641 'org-marker marker 'org-hd-marker marker 'org-category category
15642 'priority priority 'type "tagsmatch")
15643 (push txt rtn))
15644 ;; if we are to skip sublevels, jump to end of subtree
15645 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15646 (when (and (eq action 'sparse-tree)
15647 (not org-sparse-tree-open-archived-trees))
15648 (org-hide-archived-subtrees (point-min) (point-max)))
15649 (nreverse rtn)))
15651 (defvar todo-only) ;; dynamically scoped
15653 (defun org-tags-sparse-tree (&optional todo-only match)
15654 "Create a sparse tree according to tags string MATCH.
15655 MATCH can contain positive and negative selection of tags, like
15656 \"+WORK+URGENT-WITHBOSS\".
15657 If optional argument TODO_ONLY is non-nil, only select lines that are
15658 also TODO lines."
15659 (interactive "P")
15660 (org-prepare-agenda-buffers (list (current-buffer)))
15661 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15663 (defvar org-cached-props nil)
15664 (defun org-cached-entry-get (pom property)
15665 (if (or (eq t org-use-property-inheritance)
15666 (member property org-use-property-inheritance))
15667 ;; Caching is not possible, check it directly
15668 (org-entry-get pom property 'inherit)
15669 ;; Get all properties, so that we can do complicated checks easily
15670 (cdr (assoc property (or org-cached-props
15671 (setq org-cached-props
15672 (org-entry-properties pom)))))))
15674 (defun org-global-tags-completion-table (&optional files)
15675 "Return the list of all tags in all agenda buffer/files."
15676 (save-excursion
15677 (org-uniquify
15678 (delq nil
15679 (apply 'append
15680 (mapcar
15681 (lambda (file)
15682 (set-buffer (find-file-noselect file))
15683 (append (org-get-buffer-tags)
15684 (mapcar (lambda (x) (if (stringp (car-safe x))
15685 (list (car-safe x)) nil))
15686 org-tag-alist)))
15687 (if (and files (car files))
15688 files
15689 (org-agenda-files))))))))
15691 (defun org-make-tags-matcher (match)
15692 "Create the TAGS//TODO matcher form for the selection string MATCH."
15693 ;; todo-only is scoped dynamically into this function, and the function
15694 ;; may change it it the matcher asksk for it.
15695 (unless match
15696 ;; Get a new match request, with completion
15697 (let ((org-last-tags-completion-table
15698 (org-global-tags-completion-table)))
15699 (setq match (completing-read
15700 "Match: " 'org-tags-completion-function nil nil nil
15701 'org-tags-history))))
15703 ;; Parse the string and create a lisp form
15704 (let ((match0 match)
15705 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15706 minus tag mm
15707 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15708 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15709 (if (string-match "/+" match)
15710 ;; match contains also a todo-matching request
15711 (progn
15712 (setq tagsmatch (substring match 0 (match-beginning 0))
15713 todomatch (substring match (match-end 0)))
15714 (if (string-match "^!" todomatch)
15715 (setq todo-only t todomatch (substring todomatch 1)))
15716 (if (string-match "^\\s-*$" todomatch)
15717 (setq todomatch nil)))
15718 ;; only matching tags
15719 (setq tagsmatch match todomatch nil))
15721 ;; Make the tags matcher
15722 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15723 (setq tagsmatcher t)
15724 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15725 (while (setq term (pop orterms))
15726 (while (and (equal (substring term -1) "\\") orterms)
15727 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15728 (while (string-match re term)
15729 (setq minus (and (match-end 1)
15730 (equal (match-string 1 term) "-"))
15731 tag (match-string 2 term)
15732 re-p (equal (string-to-char tag) ?{)
15733 level-p (match-end 3)
15734 prop-p (match-end 4)
15735 mm (cond
15736 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15737 (level-p `(= level ,(string-to-number
15738 (match-string 3 term))))
15739 (prop-p
15740 (setq pn (match-string 4 term)
15741 pv (match-string 5 term)
15742 cat-p (equal pn "CATEGORY")
15743 re-p (equal (string-to-char pv) ?{)
15744 pv (substring pv 1 -1))
15745 (if (equal pn "CATEGORY")
15746 (setq gv '(get-text-property (point) 'org-category))
15747 (setq gv `(org-cached-entry-get nil ,pn)))
15748 (if re-p
15749 `(string-match ,pv (or ,gv ""))
15750 `(equal ,pv (or ,gv ""))))
15751 (t `(member ,(downcase tag) tags-list)))
15752 mm (if minus (list 'not mm) mm)
15753 term (substring term (match-end 0)))
15754 (push mm tagsmatcher))
15755 (push (if (> (length tagsmatcher) 1)
15756 (cons 'and tagsmatcher)
15757 (car tagsmatcher))
15758 orlist)
15759 (setq tagsmatcher nil))
15760 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15761 (setq tagsmatcher
15762 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15764 ;; Make the todo matcher
15765 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15766 (setq todomatcher t)
15767 (setq orterms (org-split-string todomatch "|") orlist nil)
15768 (while (setq term (pop orterms))
15769 (while (string-match re term)
15770 (setq minus (and (match-end 1)
15771 (equal (match-string 1 term) "-"))
15772 kwd (match-string 2 term)
15773 re-p (equal (string-to-char kwd) ?{)
15774 term (substring term (match-end 0))
15775 mm (if re-p
15776 `(string-match ,(substring kwd 1 -1) todo)
15777 (list 'equal 'todo kwd))
15778 mm (if minus (list 'not mm) mm))
15779 (push mm todomatcher))
15780 (push (if (> (length todomatcher) 1)
15781 (cons 'and todomatcher)
15782 (car todomatcher))
15783 orlist)
15784 (setq todomatcher nil))
15785 (setq todomatcher (if (> (length orlist) 1)
15786 (cons 'or orlist) (car orlist))))
15788 ;; Return the string and lisp forms of the matcher
15789 (setq matcher (if todomatcher
15790 (list 'and tagsmatcher todomatcher)
15791 tagsmatcher))
15792 (cons match0 matcher)))
15794 (defun org-match-any-p (re list)
15795 "Does re match any element of list?"
15796 (setq list (mapcar (lambda (x) (string-match re x)) list))
15797 (delq nil list))
15799 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15800 (defvar org-tags-overlay (org-make-overlay 1 1))
15801 (org-detach-overlay org-tags-overlay)
15803 (defun org-align-tags-here (to-col)
15804 ;; Assumes that this is a headline
15805 (let ((pos (point)) (col (current-column)) tags)
15806 (beginning-of-line 1)
15807 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15808 (< pos (match-beginning 2)))
15809 (progn
15810 (setq tags (match-string 2))
15811 (goto-char (match-beginning 1))
15812 (insert " ")
15813 (delete-region (point) (1+ (match-end 0)))
15814 (backward-char 1)
15815 (move-to-column
15816 (max (1+ (current-column))
15817 (1+ col)
15818 (if (> to-col 0)
15819 to-col
15820 (- (abs to-col) (length tags))))
15822 (insert tags)
15823 (move-to-column (min (current-column) col) t))
15824 (goto-char pos))))
15826 (defun org-set-tags (&optional arg just-align)
15827 "Set the tags for the current headline.
15828 With prefix ARG, realign all tags in headings in the current buffer."
15829 (interactive "P")
15830 (let* ((re (concat "^" outline-regexp))
15831 (current (org-get-tags-string))
15832 (col (current-column))
15833 (org-setting-tags t)
15834 table current-tags inherited-tags ; computed below when needed
15835 tags p0 c0 c1 rpl)
15836 (if arg
15837 (save-excursion
15838 (goto-char (point-min))
15839 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15840 (while (re-search-forward re nil t)
15841 (org-set-tags nil t)
15842 (end-of-line 1)))
15843 (message "All tags realigned to column %d" org-tags-column))
15844 (if just-align
15845 (setq tags current)
15846 ;; Get a new set of tags from the user
15847 (save-excursion
15848 (setq table (or org-tag-alist (org-get-buffer-tags))
15849 org-last-tags-completion-table table
15850 current-tags (org-split-string current ":")
15851 inherited-tags (nreverse
15852 (nthcdr (length current-tags)
15853 (nreverse (org-get-tags-at))))
15854 tags
15855 (if (or (eq t org-use-fast-tag-selection)
15856 (and org-use-fast-tag-selection
15857 (delq nil (mapcar 'cdr table))))
15858 (org-fast-tag-selection
15859 current-tags inherited-tags table
15860 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15861 (let ((org-add-colon-after-tag-completion t))
15862 (org-trim
15863 (org-without-partial-completion
15864 (completing-read "Tags: " 'org-tags-completion-function
15865 nil nil current 'org-tags-history)))))))
15866 (while (string-match "[-+&]+" tags)
15867 ;; No boolean logic, just a list
15868 (setq tags (replace-match ":" t t tags))))
15870 (if (string-match "\\`[\t ]*\\'" tags)
15871 (setq tags "")
15872 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15873 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15875 ;; Insert new tags at the correct column
15876 (beginning-of-line 1)
15877 (cond
15878 ((and (equal current "") (equal tags "")))
15879 ((re-search-forward
15880 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15881 (point-at-eol) t)
15882 (if (equal tags "")
15883 (setq rpl "")
15884 (goto-char (match-beginning 0))
15885 (setq c0 (current-column) p0 (point)
15886 c1 (max (1+ c0) (if (> org-tags-column 0)
15887 org-tags-column
15888 (- (- org-tags-column) (length tags))))
15889 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15890 (replace-match rpl t t)
15891 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15892 tags)
15893 (t (error "Tags alignment failed")))
15894 (move-to-column col)
15895 (unless just-align
15896 (run-hooks 'org-after-tags-change-hook)))))
15898 (defun org-change-tag-in-region (beg end tag off)
15899 "Add or remove TAG for each entry in the region.
15900 This works in the agenda, and also in an org-mode buffer."
15901 (interactive
15902 (list (region-beginning) (region-end)
15903 (let ((org-last-tags-completion-table
15904 (if (org-mode-p)
15905 (org-get-buffer-tags)
15906 (org-global-tags-completion-table))))
15907 (completing-read
15908 "Tag: " 'org-tags-completion-function nil nil nil
15909 'org-tags-history))
15910 (progn
15911 (message "[s]et or [r]emove? ")
15912 (equal (read-char-exclusive) ?r))))
15913 (if (fboundp 'deactivate-mark) (deactivate-mark))
15914 (let ((agendap (equal major-mode 'org-agenda-mode))
15915 l1 l2 m buf pos newhead (cnt 0))
15916 (goto-char end)
15917 (setq l2 (1- (org-current-line)))
15918 (goto-char beg)
15919 (setq l1 (org-current-line))
15920 (loop for l from l1 to l2 do
15921 (goto-line l)
15922 (setq m (get-text-property (point) 'org-hd-marker))
15923 (when (or (and (org-mode-p) (org-on-heading-p))
15924 (and agendap m))
15925 (setq buf (if agendap (marker-buffer m) (current-buffer))
15926 pos (if agendap m (point)))
15927 (with-current-buffer buf
15928 (save-excursion
15929 (save-restriction
15930 (goto-char pos)
15931 (setq cnt (1+ cnt))
15932 (org-toggle-tag tag (if off 'off 'on))
15933 (setq newhead (org-get-heading)))))
15934 (and agendap (org-agenda-change-all-lines newhead m))))
15935 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15937 (defun org-tags-completion-function (string predicate &optional flag)
15938 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15939 (confirm (lambda (x) (stringp (car x)))))
15940 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15941 (setq s1 (match-string 1 string)
15942 s2 (match-string 2 string))
15943 (setq s1 "" s2 string))
15944 (cond
15945 ((eq flag nil)
15946 ;; try completion
15947 (setq rtn (try-completion s2 ctable confirm))
15948 (if (stringp rtn)
15949 (setq rtn
15950 (concat s1 s2 (substring rtn (length s2))
15951 (if (and org-add-colon-after-tag-completion
15952 (assoc rtn ctable))
15953 ":" ""))))
15954 rtn)
15955 ((eq flag t)
15956 ;; all-completions
15957 (all-completions s2 ctable confirm)
15959 ((eq flag 'lambda)
15960 ;; exact match?
15961 (assoc s2 ctable)))
15964 (defun org-fast-tag-insert (kwd tags face &optional end)
15965 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15966 (insert (format "%-12s" (concat kwd ":"))
15967 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15968 (or end "")))
15970 (defun org-fast-tag-show-exit (flag)
15971 (save-excursion
15972 (goto-line 3)
15973 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15974 (replace-match ""))
15975 (when flag
15976 (end-of-line 1)
15977 (move-to-column (- (window-width) 19) t)
15978 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15980 (defun org-set-current-tags-overlay (current prefix)
15981 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15982 (if (featurep 'xemacs)
15983 (org-overlay-display org-tags-overlay (concat prefix s)
15984 'secondary-selection)
15985 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15986 (org-overlay-display org-tags-overlay (concat prefix s)))))
15988 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15989 "Fast tag selection with single keys.
15990 CURRENT is the current list of tags in the headline, INHERITED is the
15991 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15992 possibly with grouping information. TODO-TABLE is a similar table with
15993 TODO keywords, should these have keys assigned to them.
15994 If the keys are nil, a-z are automatically assigned.
15995 Returns the new tags string, or nil to not change the current settings."
15996 (let* ((fulltable (append table todo-table))
15997 (maxlen (apply 'max (mapcar
15998 (lambda (x)
15999 (if (stringp (car x)) (string-width (car x)) 0))
16000 fulltable)))
16001 (buf (current-buffer))
16002 (expert (eq org-fast-tag-selection-single-key 'expert))
16003 (buffer-tags nil)
16004 (fwidth (+ maxlen 3 1 3))
16005 (ncol (/ (- (window-width) 4) fwidth))
16006 (i-face 'org-done)
16007 (c-face 'org-todo)
16008 tg cnt e c char c1 c2 ntable tbl rtn
16009 ov-start ov-end ov-prefix
16010 (exit-after-next org-fast-tag-selection-single-key)
16011 (done-keywords org-done-keywords)
16012 groups ingroup)
16013 (save-excursion
16014 (beginning-of-line 1)
16015 (if (looking-at
16016 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16017 (setq ov-start (match-beginning 1)
16018 ov-end (match-end 1)
16019 ov-prefix "")
16020 (setq ov-start (1- (point-at-eol))
16021 ov-end (1+ ov-start))
16022 (skip-chars-forward "^\n\r")
16023 (setq ov-prefix
16024 (concat
16025 (buffer-substring (1- (point)) (point))
16026 (if (> (current-column) org-tags-column)
16028 (make-string (- org-tags-column (current-column)) ?\ ))))))
16029 (org-move-overlay org-tags-overlay ov-start ov-end)
16030 (save-window-excursion
16031 (if expert
16032 (set-buffer (get-buffer-create " *Org tags*"))
16033 (delete-other-windows)
16034 (split-window-vertically)
16035 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
16036 (erase-buffer)
16037 (org-set-local 'org-done-keywords done-keywords)
16038 (org-fast-tag-insert "Inherited" inherited i-face "\n")
16039 (org-fast-tag-insert "Current" current c-face "\n\n")
16040 (org-fast-tag-show-exit exit-after-next)
16041 (org-set-current-tags-overlay current ov-prefix)
16042 (setq tbl fulltable char ?a cnt 0)
16043 (while (setq e (pop tbl))
16044 (cond
16045 ((equal e '(:startgroup))
16046 (push '() groups) (setq ingroup t)
16047 (when (not (= cnt 0))
16048 (setq cnt 0)
16049 (insert "\n"))
16050 (insert "{ "))
16051 ((equal e '(:endgroup))
16052 (setq ingroup nil cnt 0)
16053 (insert "}\n"))
16055 (setq tg (car e) c2 nil)
16056 (if (cdr e)
16057 (setq c (cdr e))
16058 ;; automatically assign a character.
16059 (setq c1 (string-to-char
16060 (downcase (substring
16061 tg (if (= (string-to-char tg) ?@) 1 0)))))
16062 (if (or (rassoc c1 ntable) (rassoc c1 table))
16063 (while (or (rassoc char ntable) (rassoc char table))
16064 (setq char (1+ char)))
16065 (setq c2 c1))
16066 (setq c (or c2 char)))
16067 (if ingroup (push tg (car groups)))
16068 (setq tg (org-add-props tg nil 'face
16069 (cond
16070 ((not (assoc tg table))
16071 (org-get-todo-face tg))
16072 ((member tg current) c-face)
16073 ((member tg inherited) i-face)
16074 (t nil))))
16075 (if (and (= cnt 0) (not ingroup)) (insert " "))
16076 (insert "[" c "] " tg (make-string
16077 (- fwidth 4 (length tg)) ?\ ))
16078 (push (cons tg c) ntable)
16079 (when (= (setq cnt (1+ cnt)) ncol)
16080 (insert "\n")
16081 (if ingroup (insert " "))
16082 (setq cnt 0)))))
16083 (setq ntable (nreverse ntable))
16084 (insert "\n")
16085 (goto-char (point-min))
16086 (if (and (not expert) (fboundp 'fit-window-to-buffer))
16087 (fit-window-to-buffer))
16088 (setq rtn
16089 (catch 'exit
16090 (while t
16091 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
16092 (if groups " [!] no groups" " [!]groups")
16093 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16094 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16095 (cond
16096 ((= c ?\r) (throw 'exit t))
16097 ((= c ?!)
16098 (setq groups (not groups))
16099 (goto-char (point-min))
16100 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16101 ((= c ?\C-c)
16102 (if (not expert)
16103 (org-fast-tag-show-exit
16104 (setq exit-after-next (not exit-after-next)))
16105 (setq expert nil)
16106 (delete-other-windows)
16107 (split-window-vertically)
16108 (org-switch-to-buffer-other-window " *Org tags*")
16109 (and (fboundp 'fit-window-to-buffer)
16110 (fit-window-to-buffer))))
16111 ((or (= c ?\C-g)
16112 (and (= c ?q) (not (rassoc c ntable))))
16113 (org-detach-overlay org-tags-overlay)
16114 (setq quit-flag t))
16115 ((= c ?\ )
16116 (setq current nil)
16117 (if exit-after-next (setq exit-after-next 'now)))
16118 ((= c ?\t)
16119 (condition-case nil
16120 (setq tg (completing-read
16121 "Tag: "
16122 (or buffer-tags
16123 (with-current-buffer buf
16124 (org-get-buffer-tags)))))
16125 (quit (setq tg "")))
16126 (when (string-match "\\S-" tg)
16127 (add-to-list 'buffer-tags (list tg))
16128 (if (member tg current)
16129 (setq current (delete tg current))
16130 (push tg current)))
16131 (if exit-after-next (setq exit-after-next 'now)))
16132 ((setq e (rassoc c todo-table) tg (car e))
16133 (with-current-buffer buf
16134 (save-excursion (org-todo tg)))
16135 (if exit-after-next (setq exit-after-next 'now)))
16136 ((setq e (rassoc c ntable) tg (car e))
16137 (if (member tg current)
16138 (setq current (delete tg current))
16139 (loop for g in groups do
16140 (if (member tg g)
16141 (mapc (lambda (x)
16142 (setq current (delete x current)))
16143 g)))
16144 (push tg current))
16145 (if exit-after-next (setq exit-after-next 'now))))
16147 ;; Create a sorted list
16148 (setq current
16149 (sort current
16150 (lambda (a b)
16151 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16152 (if (eq exit-after-next 'now) (throw 'exit t))
16153 (goto-char (point-min))
16154 (beginning-of-line 2)
16155 (delete-region (point) (point-at-eol))
16156 (org-fast-tag-insert "Current" current c-face)
16157 (org-set-current-tags-overlay current ov-prefix)
16158 (while (re-search-forward
16159 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16160 (setq tg (match-string 1))
16161 (add-text-properties
16162 (match-beginning 1) (match-end 1)
16163 (list 'face
16164 (cond
16165 ((member tg current) c-face)
16166 ((member tg inherited) i-face)
16167 (t (get-text-property (match-beginning 1) 'face))))))
16168 (goto-char (point-min)))))
16169 (org-detach-overlay org-tags-overlay)
16170 (if rtn
16171 (mapconcat 'identity current ":")
16172 nil))))
16174 (defun org-get-tags-string ()
16175 "Get the TAGS string in the current headline."
16176 (unless (org-on-heading-p t)
16177 (error "Not on a heading"))
16178 (save-excursion
16179 (beginning-of-line 1)
16180 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16181 (org-match-string-no-properties 1)
16182 "")))
16184 (defun org-get-tags ()
16185 "Get the list of tags specified in the current headline."
16186 (org-split-string (org-get-tags-string) ":"))
16188 (defun org-get-buffer-tags ()
16189 "Get a table of all tags used in the buffer, for completion."
16190 (let (tags)
16191 (save-excursion
16192 (goto-char (point-min))
16193 (while (re-search-forward
16194 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16195 (when (equal (char-after (point-at-bol 0)) ?*)
16196 (mapc (lambda (x) (add-to-list 'tags x))
16197 (org-split-string (org-match-string-no-properties 1) ":")))))
16198 (mapcar 'list tags)))
16201 ;;;; Properties
16203 ;;; Setting and retrieving properties
16205 (defconst org-special-properties
16206 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16207 "TIMESTAMP" "TIMESTAMP_IA")
16208 "The special properties valid in Org-mode.
16210 These are properties that are not defined in the property drawer,
16211 but in some other way.")
16213 (defconst org-default-properties
16214 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16215 "LOCATION" "LOGGING" "COLUMNS")
16216 "Some properties that are used by Org-mode for various purposes.
16217 Being in this list makes sure that they are offered for completion.")
16219 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16220 "Regular expression matching the first line of a property drawer.")
16222 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16223 "Regular expression matching the first line of a property drawer.")
16225 (defun org-property-action ()
16226 "Do an action on properties."
16227 (interactive)
16228 (let (c)
16229 (org-at-property-p)
16230 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16231 (setq c (read-char-exclusive))
16232 (cond
16233 ((equal c ?s)
16234 (call-interactively 'org-set-property))
16235 ((equal c ?d)
16236 (call-interactively 'org-delete-property))
16237 ((equal c ?D)
16238 (call-interactively 'org-delete-property-globally))
16239 ((equal c ?c)
16240 (call-interactively 'org-compute-property-at-point))
16241 (t (error "No such property action %c" c)))))
16243 (defun org-at-property-p ()
16244 "Is the cursor in a property line?"
16245 ;; FIXME: Does not check if we are actually in the drawer.
16246 ;; FIXME: also returns true on any drawers.....
16247 ;; This is used by C-c C-c for property action.
16248 (save-excursion
16249 (beginning-of-line 1)
16250 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16252 (defmacro org-with-point-at (pom &rest body)
16253 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16254 (declare (indent 1) (debug t))
16255 `(save-excursion
16256 (if (markerp pom) (set-buffer (marker-buffer pom)))
16257 (save-excursion
16258 (goto-char (or pom (point)))
16259 ,@body)))
16261 (defun org-get-property-block (&optional beg end force)
16262 "Return the (beg . end) range of the body of the property drawer.
16263 BEG and END can be beginning and end of subtree, if not given
16264 they will be found.
16265 If the drawer does not exist and FORCE is non-nil, create the drawer."
16266 (catch 'exit
16267 (save-excursion
16268 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16269 (end (or end (progn (outline-next-heading) (point)))))
16270 (goto-char beg)
16271 (if (re-search-forward org-property-start-re end t)
16272 (setq beg (1+ (match-end 0)))
16273 (if force
16274 (save-excursion
16275 (org-insert-property-drawer)
16276 (setq end (progn (outline-next-heading) (point))))
16277 (throw 'exit nil))
16278 (goto-char beg)
16279 (if (re-search-forward org-property-start-re end t)
16280 (setq beg (1+ (match-end 0)))))
16281 (if (re-search-forward org-property-end-re end t)
16282 (setq end (match-beginning 0))
16283 (or force (throw 'exit nil))
16284 (goto-char beg)
16285 (setq end beg)
16286 (org-indent-line-function)
16287 (insert ":END:\n"))
16288 (cons beg end)))))
16290 (defun org-entry-properties (&optional pom which)
16291 "Get all properties of the entry at point-or-marker POM.
16292 This includes the TODO keyword, the tags, time strings for deadline,
16293 scheduled, and clocking, and any additional properties defined in the
16294 entry. The return value is an alist, keys may occur multiple times
16295 if the property key was used several times.
16296 POM may also be nil, in which case the current entry is used.
16297 If WHICH is nil or `all', get all properties. If WHICH is
16298 `special' or `standard', only get that subclass."
16299 (setq which (or which 'all))
16300 (org-with-point-at pom
16301 (let ((clockstr (substring org-clock-string 0 -1))
16302 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16303 beg end range props sum-props key value string clocksum)
16304 (save-excursion
16305 (when (condition-case nil (org-back-to-heading t) (error nil))
16306 (setq beg (point))
16307 (setq sum-props (get-text-property (point) 'org-summaries))
16308 (setq clocksum (get-text-property (point) :org-clock-minutes))
16309 (outline-next-heading)
16310 (setq end (point))
16311 (when (memq which '(all special))
16312 ;; Get the special properties, like TODO and tags
16313 (goto-char beg)
16314 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16315 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16316 (when (looking-at org-priority-regexp)
16317 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16318 (when (and (setq value (org-get-tags-string))
16319 (string-match "\\S-" value))
16320 (push (cons "TAGS" value) props))
16321 (when (setq value (org-get-tags-at))
16322 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16323 props))
16324 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16325 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16326 string (if (equal key clockstr)
16327 (org-no-properties
16328 (org-trim
16329 (buffer-substring
16330 (match-beginning 3) (goto-char (point-at-eol)))))
16331 (substring (org-match-string-no-properties 3) 1 -1)))
16332 (unless key
16333 (if (= (char-after (match-beginning 3)) ?\[)
16334 (setq key "TIMESTAMP_IA")
16335 (setq key "TIMESTAMP")))
16336 (when (or (equal key clockstr) (not (assoc key props)))
16337 (push (cons key string) props)))
16341 (when (memq which '(all standard))
16342 ;; Get the standard properties, like :PORP: ...
16343 (setq range (org-get-property-block beg end))
16344 (when range
16345 (goto-char (car range))
16346 (while (re-search-forward
16347 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16348 (cdr range) t)
16349 (setq key (org-match-string-no-properties 1)
16350 value (org-trim (or (org-match-string-no-properties 2) "")))
16351 (unless (member key excluded)
16352 (push (cons key (or value "")) props)))))
16353 (if clocksum
16354 (push (cons "CLOCKSUM"
16355 (org-column-number-to-string (/ (float clocksum) 60.)
16356 'add_times))
16357 props))
16358 (append sum-props (nreverse props)))))))
16360 (defun org-entry-get (pom property &optional inherit)
16361 "Get value of PROPERTY for entry at point-or-marker POM.
16362 If INHERIT is non-nil and the entry does not have the property,
16363 then also check higher levels of the hierarchy.
16364 If the property is present but empty, the return value is the empty string.
16365 If the property is not present at all, nil is returned."
16366 (org-with-point-at pom
16367 (if inherit
16368 (org-entry-get-with-inheritance property)
16369 (if (member property org-special-properties)
16370 ;; We need a special property. Use brute force, get all properties.
16371 (cdr (assoc property (org-entry-properties nil 'special)))
16372 (let ((range (org-get-property-block)))
16373 (if (and range
16374 (goto-char (car range))
16375 (re-search-forward
16376 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16377 (cdr range) t))
16378 ;; Found the property, return it.
16379 (if (match-end 1)
16380 (org-match-string-no-properties 1)
16381 "")))))))
16383 (defun org-entry-delete (pom property)
16384 "Delete the property PROPERTY from entry at point-or-marker POM."
16385 (org-with-point-at pom
16386 (if (member property org-special-properties)
16387 nil ; cannot delete these properties.
16388 (let ((range (org-get-property-block)))
16389 (if (and range
16390 (goto-char (car range))
16391 (re-search-forward
16392 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16393 (cdr range) t))
16394 (progn
16395 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16397 nil)))))
16399 ;; Multi-values properties are properties that contain multiple values
16400 ;; These values are assumed to be single words, separated by whitespace.
16401 (defun org-entry-add-to-multivalued-property (pom property value)
16402 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16403 (let* ((old (org-entry-get pom property))
16404 (values (and old (org-split-string old "[ \t]"))))
16405 (unless (member value values)
16406 (setq values (cons value values))
16407 (org-entry-put pom property
16408 (mapconcat 'identity values " ")))))
16410 (defun org-entry-remove-from-multivalued-property (pom property value)
16411 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16412 (let* ((old (org-entry-get pom property))
16413 (values (and old (org-split-string old "[ \t]"))))
16414 (when (member value values)
16415 (setq values (delete value values))
16416 (org-entry-put pom property
16417 (mapconcat 'identity values " ")))))
16419 (defun org-entry-member-in-multivalued-property (pom property value)
16420 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16421 (let* ((old (org-entry-get pom property))
16422 (values (and old (org-split-string old "[ \t]"))))
16423 (member value values)))
16425 (defvar org-entry-property-inherited-from (make-marker))
16427 (defun org-entry-get-with-inheritance (property)
16428 "Get entry property, and search higher levels if not present."
16429 (let (tmp)
16430 (save-excursion
16431 (save-restriction
16432 (widen)
16433 (catch 'ex
16434 (while t
16435 (when (setq tmp (org-entry-get nil property))
16436 (org-back-to-heading t)
16437 (move-marker org-entry-property-inherited-from (point))
16438 (throw 'ex tmp))
16439 (or (org-up-heading-safe) (throw 'ex nil)))))
16440 (or tmp (cdr (assoc property org-local-properties))
16441 (cdr (assoc property org-global-properties))))))
16443 (defun org-entry-put (pom property value)
16444 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16445 (org-with-point-at pom
16446 (org-back-to-heading t)
16447 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16448 range)
16449 (cond
16450 ((equal property "TODO")
16451 (when (and (stringp value) (string-match "\\S-" value)
16452 (not (member value org-todo-keywords-1)))
16453 (error "\"%s\" is not a valid TODO state" value))
16454 (if (or (not value)
16455 (not (string-match "\\S-" value)))
16456 (setq value 'none))
16457 (org-todo value)
16458 (org-set-tags nil 'align))
16459 ((equal property "PRIORITY")
16460 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16461 (string-to-char value) ?\ ))
16462 (org-set-tags nil 'align))
16463 ((equal property "SCHEDULED")
16464 (if (re-search-forward org-scheduled-time-regexp end t)
16465 (cond
16466 ((eq value 'earlier) (org-timestamp-change -1 'day))
16467 ((eq value 'later) (org-timestamp-change 1 'day))
16468 (t (call-interactively 'org-schedule)))
16469 (call-interactively 'org-schedule)))
16470 ((equal property "DEADLINE")
16471 (if (re-search-forward org-deadline-time-regexp end t)
16472 (cond
16473 ((eq value 'earlier) (org-timestamp-change -1 'day))
16474 ((eq value 'later) (org-timestamp-change 1 'day))
16475 (t (call-interactively 'org-deadline)))
16476 (call-interactively 'org-deadline)))
16477 ((member property org-special-properties)
16478 (error "The %s property can not yet be set with `org-entry-put'"
16479 property))
16480 (t ; a non-special property
16481 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16482 (setq range (org-get-property-block beg end 'force))
16483 (goto-char (car range))
16484 (if (re-search-forward
16485 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16486 (progn
16487 (delete-region (match-beginning 1) (match-end 1))
16488 (goto-char (match-beginning 1)))
16489 (goto-char (cdr range))
16490 (insert "\n")
16491 (backward-char 1)
16492 (org-indent-line-function)
16493 (insert ":" property ":"))
16494 (and value (insert " " value))
16495 (org-indent-line-function)))))))
16497 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16498 "Get all property keys in the current buffer.
16499 With INCLUDE-SPECIALS, also list the special properties that relect things
16500 like tags and TODO state.
16501 With INCLUDE-DEFAULTS, also include properties that has special meaning
16502 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16503 With INCLUDE-COLUMNS, also include property names given in COLUMN
16504 formats in the current buffer."
16505 (let (rtn range cfmt cols s p)
16506 (save-excursion
16507 (save-restriction
16508 (widen)
16509 (goto-char (point-min))
16510 (while (re-search-forward org-property-start-re nil t)
16511 (setq range (org-get-property-block))
16512 (goto-char (car range))
16513 (while (re-search-forward
16514 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16515 (cdr range) t)
16516 (add-to-list 'rtn (org-match-string-no-properties 1)))
16517 (outline-next-heading))))
16519 (when include-specials
16520 (setq rtn (append org-special-properties rtn)))
16522 (when include-defaults
16523 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16525 (when include-columns
16526 (save-excursion
16527 (save-restriction
16528 (widen)
16529 (goto-char (point-min))
16530 (while (re-search-forward
16531 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16532 nil t)
16533 (setq cfmt (match-string 2) s 0)
16534 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16535 cfmt s)
16536 (setq s (match-end 0)
16537 p (match-string 1 cfmt))
16538 (unless (or (equal p "ITEM")
16539 (member p org-special-properties))
16540 (add-to-list 'rtn (match-string 1 cfmt))))))))
16542 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16544 (defun org-property-values (key)
16545 "Return a list of all values of property KEY."
16546 (save-excursion
16547 (save-restriction
16548 (widen)
16549 (goto-char (point-min))
16550 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16551 values)
16552 (while (re-search-forward re nil t)
16553 (add-to-list 'values (org-trim (match-string 1))))
16554 (delete "" values)))))
16556 (defun org-insert-property-drawer ()
16557 "Insert a property drawer into the current entry."
16558 (interactive)
16559 (org-back-to-heading t)
16560 (looking-at outline-regexp)
16561 (let ((indent (- (match-end 0)(match-beginning 0)))
16562 (beg (point))
16563 (re (concat "^[ \t]*" org-keyword-time-regexp))
16564 end hiddenp)
16565 (outline-next-heading)
16566 (setq end (point))
16567 (goto-char beg)
16568 (while (re-search-forward re end t))
16569 (setq hiddenp (org-invisible-p))
16570 (end-of-line 1)
16571 (and (equal (char-after) ?\n) (forward-char 1))
16572 (org-skip-over-state-notes)
16573 (skip-chars-backward " \t\n\r")
16574 (if (eq (char-before) ?*) (forward-char 1))
16575 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16576 (beginning-of-line 0)
16577 (indent-to-column indent)
16578 (beginning-of-line 2)
16579 (indent-to-column indent)
16580 (beginning-of-line 0)
16581 (if hiddenp
16582 (save-excursion
16583 (org-back-to-heading t)
16584 (hide-entry))
16585 (org-flag-drawer t))))
16587 (defun org-set-property (property value)
16588 "In the current entry, set PROPERTY to VALUE.
16589 When called interactively, this will prompt for a property name, offering
16590 completion on existing and default properties. And then it will prompt
16591 for a value, offering competion either on allowed values (via an inherited
16592 xxx_ALL property) or on existing values in other instances of this property
16593 in the current file."
16594 (interactive
16595 (let* ((prop (completing-read
16596 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16597 (cur (org-entry-get nil prop))
16598 (allowed (org-property-get-allowed-values nil prop 'table))
16599 (existing (mapcar 'list (org-property-values prop)))
16600 (val (if allowed
16601 (completing-read "Value: " allowed nil 'req-match)
16602 (completing-read
16603 (concat "Value" (if (and cur (string-match "\\S-" cur))
16604 (concat "[" cur "]") "")
16605 ": ")
16606 existing nil nil "" nil cur))))
16607 (list prop (if (equal val "") cur val))))
16608 (unless (equal (org-entry-get nil property) value)
16609 (org-entry-put nil property value)))
16611 (defun org-delete-property (property)
16612 "In the current entry, delete PROPERTY."
16613 (interactive
16614 (let* ((prop (completing-read
16615 "Property: " (org-entry-properties nil 'standard))))
16616 (list prop)))
16617 (message "Property %s %s" property
16618 (if (org-entry-delete nil property)
16619 "deleted"
16620 "was not present in the entry")))
16622 (defun org-delete-property-globally (property)
16623 "Remove PROPERTY globally, from all entries."
16624 (interactive
16625 (let* ((prop (completing-read
16626 "Globally remove property: "
16627 (mapcar 'list (org-buffer-property-keys)))))
16628 (list prop)))
16629 (save-excursion
16630 (save-restriction
16631 (widen)
16632 (goto-char (point-min))
16633 (let ((cnt 0))
16634 (while (re-search-forward
16635 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16636 nil t)
16637 (setq cnt (1+ cnt))
16638 (replace-match ""))
16639 (message "Property \"%s\" removed from %d entries" property cnt)))))
16641 (defvar org-columns-current-fmt-compiled) ; defined below
16643 (defun org-compute-property-at-point ()
16644 "Compute the property at point.
16645 This looks for an enclosing column format, extracts the operator and
16646 then applies it to the proerty in the column format's scope."
16647 (interactive)
16648 (unless (org-at-property-p)
16649 (error "Not at a property"))
16650 (let ((prop (org-match-string-no-properties 2)))
16651 (org-columns-get-format-and-top-level)
16652 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16653 (error "No operator defined for property %s" prop))
16654 (org-columns-compute prop)))
16656 (defun org-property-get-allowed-values (pom property &optional table)
16657 "Get allowed values for the property PROPERTY.
16658 When TABLE is non-nil, return an alist that can directly be used for
16659 completion."
16660 (let (vals)
16661 (cond
16662 ((equal property "TODO")
16663 (setq vals (org-with-point-at pom
16664 (append org-todo-keywords-1 '("")))))
16665 ((equal property "PRIORITY")
16666 (let ((n org-lowest-priority))
16667 (while (>= n org-highest-priority)
16668 (push (char-to-string n) vals)
16669 (setq n (1- n)))))
16670 ((member property org-special-properties))
16672 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16674 (when (and vals (string-match "\\S-" vals))
16675 (setq vals (car (read-from-string (concat "(" vals ")"))))
16676 (setq vals (mapcar (lambda (x)
16677 (cond ((stringp x) x)
16678 ((numberp x) (number-to-string x))
16679 ((symbolp x) (symbol-name x))
16680 (t "???")))
16681 vals)))))
16682 (if table (mapcar 'list vals) vals)))
16684 (defun org-property-previous-allowed-value (&optional previous)
16685 "Switch to the next allowed value for this property."
16686 (interactive)
16687 (org-property-next-allowed-value t))
16689 (defun org-property-next-allowed-value (&optional previous)
16690 "Switch to the next allowed value for this property."
16691 (interactive)
16692 (unless (org-at-property-p)
16693 (error "Not at a property"))
16694 (let* ((key (match-string 2))
16695 (value (match-string 3))
16696 (allowed (or (org-property-get-allowed-values (point) key)
16697 (and (member value '("[ ]" "[-]" "[X]"))
16698 '("[ ]" "[X]"))))
16699 nval)
16700 (unless allowed
16701 (error "Allowed values for this property have not been defined"))
16702 (if previous (setq allowed (reverse allowed)))
16703 (if (member value allowed)
16704 (setq nval (car (cdr (member value allowed)))))
16705 (setq nval (or nval (car allowed)))
16706 (if (equal nval value)
16707 (error "Only one allowed value for this property"))
16708 (org-at-property-p)
16709 (replace-match (concat " :" key ": " nval) t t)
16710 (org-indent-line-function)
16711 (beginning-of-line 1)
16712 (skip-chars-forward " \t")))
16714 (defun org-find-entry-with-id (ident)
16715 "Locate the entry that contains the ID property with exact value IDENT.
16716 IDENT can be a string, a symbol or a number, this function will search for
16717 the string representation of it.
16718 Return the position where this entry starts, or nil if there is no such entry."
16719 (let ((id (cond
16720 ((stringp ident) ident)
16721 ((symbol-name ident) (symbol-name ident))
16722 ((numberp ident) (number-to-string ident))
16723 (t (error "IDENT %s must be a string, symbol or number" ident))))
16724 (case-fold-search nil))
16725 (save-excursion
16726 (save-restriction
16727 (widen)
16728 (goto-char (point-min))
16729 (when (re-search-forward
16730 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16731 nil t)
16732 (org-back-to-heading)
16733 (point))))))
16735 ;;; Column View
16737 (defvar org-columns-overlays nil
16738 "Holds the list of current column overlays.")
16740 (defvar org-columns-current-fmt nil
16741 "Local variable, holds the currently active column format.")
16742 (defvar org-columns-current-fmt-compiled nil
16743 "Local variable, holds the currently active column format.
16744 This is the compiled version of the format.")
16745 (defvar org-columns-current-widths nil
16746 "Loval variable, holds the currently widths of fields.")
16747 (defvar org-columns-current-maxwidths nil
16748 "Loval variable, holds the currently active maximum column widths.")
16749 (defvar org-columns-begin-marker (make-marker)
16750 "Points to the position where last a column creation command was called.")
16751 (defvar org-columns-top-level-marker (make-marker)
16752 "Points to the position where current columns region starts.")
16754 (defvar org-columns-map (make-sparse-keymap)
16755 "The keymap valid in column display.")
16757 (defun org-columns-content ()
16758 "Switch to contents view while in columns view."
16759 (interactive)
16760 (org-overview)
16761 (org-content))
16763 (org-defkey org-columns-map "c" 'org-columns-content)
16764 (org-defkey org-columns-map "o" 'org-overview)
16765 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16766 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16767 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16768 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16769 (org-defkey org-columns-map "v" 'org-columns-show-value)
16770 (org-defkey org-columns-map "q" 'org-columns-quit)
16771 (org-defkey org-columns-map "r" 'org-columns-redo)
16772 (org-defkey org-columns-map "g" 'org-columns-redo)
16773 (org-defkey org-columns-map [left] 'backward-char)
16774 (org-defkey org-columns-map "\M-b" 'backward-char)
16775 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16776 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16777 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16778 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16779 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16780 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16781 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16782 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16783 (org-defkey org-columns-map "<" 'org-columns-narrow)
16784 (org-defkey org-columns-map ">" 'org-columns-widen)
16785 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16786 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16787 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16788 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16790 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16791 '("Column"
16792 ["Edit property" org-columns-edit-value t]
16793 ["Next allowed value" org-columns-next-allowed-value t]
16794 ["Previous allowed value" org-columns-previous-allowed-value t]
16795 ["Show full value" org-columns-show-value t]
16796 ["Edit allowed values" org-columns-edit-allowed t]
16797 "--"
16798 ["Edit column attributes" org-columns-edit-attributes t]
16799 ["Increase column width" org-columns-widen t]
16800 ["Decrease column width" org-columns-narrow t]
16801 "--"
16802 ["Move column right" org-columns-move-right t]
16803 ["Move column left" org-columns-move-left t]
16804 ["Add column" org-columns-new t]
16805 ["Delete column" org-columns-delete t]
16806 "--"
16807 ["CONTENTS" org-columns-content t]
16808 ["OVERVIEW" org-overview t]
16809 ["Refresh columns display" org-columns-redo t]
16810 "--"
16811 ["Open link" org-columns-open-link t]
16812 "--"
16813 ["Quit" org-columns-quit t]))
16815 (defun org-columns-new-overlay (beg end &optional string face)
16816 "Create a new column overlay and add it to the list."
16817 (let ((ov (org-make-overlay beg end)))
16818 (org-overlay-put ov 'face (or face 'secondary-selection))
16819 (org-overlay-display ov string face)
16820 (push ov org-columns-overlays)
16821 ov))
16823 (defun org-columns-display-here (&optional props)
16824 "Overlay the current line with column display."
16825 (interactive)
16826 (let* ((fmt org-columns-current-fmt-compiled)
16827 (beg (point-at-bol))
16828 (level-face (save-excursion
16829 (beginning-of-line 1)
16830 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16831 (org-get-level-face 2))))
16832 (color (list :foreground
16833 (face-attribute (or level-face 'default) :foreground)))
16834 props pom property ass width f string ov column val modval)
16835 ;; Check if the entry is in another buffer.
16836 (unless props
16837 (if (eq major-mode 'org-agenda-mode)
16838 (setq pom (or (get-text-property (point) 'org-hd-marker)
16839 (get-text-property (point) 'org-marker))
16840 props (if pom (org-entry-properties pom) nil))
16841 (setq props (org-entry-properties nil))))
16842 ;; Walk the format
16843 (while (setq column (pop fmt))
16844 (setq property (car column)
16845 ass (if (equal property "ITEM")
16846 (cons "ITEM"
16847 (save-match-data
16848 (org-no-properties
16849 (org-remove-tabs
16850 (buffer-substring-no-properties
16851 (point-at-bol) (point-at-eol))))))
16852 (assoc property props))
16853 width (or (cdr (assoc property org-columns-current-maxwidths))
16854 (nth 2 column)
16855 (length property))
16856 f (format "%%-%d.%ds | " width width)
16857 val (or (cdr ass) "")
16858 modval (if (equal property "ITEM")
16859 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16860 string (format f (or modval val)))
16861 ;; Create the overlay
16862 (org-unmodified
16863 (setq ov (org-columns-new-overlay
16864 beg (setq beg (1+ beg)) string
16865 (list color 'org-column)))
16866 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16867 (org-overlay-put ov 'keymap org-columns-map)
16868 (org-overlay-put ov 'org-columns-key property)
16869 (org-overlay-put ov 'org-columns-value (cdr ass))
16870 (org-overlay-put ov 'org-columns-value-modified modval)
16871 (org-overlay-put ov 'org-columns-pom pom)
16872 (org-overlay-put ov 'org-columns-format f))
16873 (if (or (not (char-after beg))
16874 (equal (char-after beg) ?\n))
16875 (let ((inhibit-read-only t))
16876 (save-excursion
16877 (goto-char beg)
16878 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16879 ;; Make the rest of the line disappear.
16880 (org-unmodified
16881 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16882 (org-overlay-put ov 'invisible t)
16883 (org-overlay-put ov 'keymap org-columns-map)
16884 (org-overlay-put ov 'intangible t)
16885 (push ov org-columns-overlays)
16886 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16887 (org-overlay-put ov 'keymap org-columns-map)
16888 (push ov org-columns-overlays)
16889 (let ((inhibit-read-only t))
16890 (put-text-property (max (point-min) (1- (point-at-bol)))
16891 (min (point-max) (1+ (point-at-eol)))
16892 'read-only "Type `e' to edit property")))))
16894 (defvar org-previous-header-line-format nil
16895 "The header line format before column view was turned on.")
16896 (defvar org-columns-inhibit-recalculation nil
16897 "Inhibit recomputing of columns on column view startup.")
16900 (defvar header-line-format)
16901 (defun org-columns-display-here-title ()
16902 "Overlay the newline before the current line with the table title."
16903 (interactive)
16904 (let ((fmt org-columns-current-fmt-compiled)
16905 string (title "")
16906 property width f column str widths)
16907 (while (setq column (pop fmt))
16908 (setq property (car column)
16909 str (or (nth 1 column) property)
16910 width (or (cdr (assoc property org-columns-current-maxwidths))
16911 (nth 2 column)
16912 (length str))
16913 widths (push width widths)
16914 f (format "%%-%d.%ds | " width width)
16915 string (format f str)
16916 title (concat title string)))
16917 (setq title (concat
16918 (org-add-props " " nil 'display '(space :align-to 0))
16919 (org-add-props title nil 'face '(:weight bold :underline t))))
16920 (org-set-local 'org-previous-header-line-format header-line-format)
16921 (org-set-local 'org-columns-current-widths (nreverse widths))
16922 (setq header-line-format title)))
16924 (defun org-columns-remove-overlays ()
16925 "Remove all currently active column overlays."
16926 (interactive)
16927 (when (marker-buffer org-columns-begin-marker)
16928 (with-current-buffer (marker-buffer org-columns-begin-marker)
16929 (when (local-variable-p 'org-previous-header-line-format)
16930 (setq header-line-format org-previous-header-line-format)
16931 (kill-local-variable 'org-previous-header-line-format))
16932 (move-marker org-columns-begin-marker nil)
16933 (move-marker org-columns-top-level-marker nil)
16934 (org-unmodified
16935 (mapc 'org-delete-overlay org-columns-overlays)
16936 (setq org-columns-overlays nil)
16937 (let ((inhibit-read-only t))
16938 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16940 (defun org-columns-cleanup-item (item fmt)
16941 "Remove from ITEM what is a column in the format FMT."
16942 (if (not org-complex-heading-regexp)
16943 item
16944 (when (string-match org-complex-heading-regexp item)
16945 (concat
16946 (org-add-props (concat (match-string 1 item) " ") nil
16947 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16948 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16949 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16950 " " (match-string 4 item)
16951 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16953 (defun org-columns-show-value ()
16954 "Show the full value of the property."
16955 (interactive)
16956 (let ((value (get-char-property (point) 'org-columns-value)))
16957 (message "Value is: %s" (or value ""))))
16959 (defun org-columns-quit ()
16960 "Remove the column overlays and in this way exit column editing."
16961 (interactive)
16962 (org-unmodified
16963 (org-columns-remove-overlays)
16964 (let ((inhibit-read-only t))
16965 (remove-text-properties (point-min) (point-max) '(read-only t))))
16966 (when (eq major-mode 'org-agenda-mode)
16967 (message
16968 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16970 (defun org-columns-check-computed ()
16971 "Check if this column value is computed.
16972 If yes, throw an error indicating that changing it does not make sense."
16973 (let ((val (get-char-property (point) 'org-columns-value)))
16974 (when (and (stringp val)
16975 (get-char-property 0 'org-computed val))
16976 (error "This value is computed from the entry's children"))))
16978 (defun org-columns-todo (&optional arg)
16979 "Change the TODO state during column view."
16980 (interactive "P")
16981 (org-columns-edit-value "TODO"))
16983 (defun org-columns-set-tags-or-toggle (&optional arg)
16984 "Toggle checkbox at point, or set tags for current headline."
16985 (interactive "P")
16986 (if (string-match "\\`\\[[ xX-]\\]\\'"
16987 (get-char-property (point) 'org-columns-value))
16988 (org-columns-next-allowed-value)
16989 (org-columns-edit-value "TAGS")))
16991 (defun org-columns-edit-value (&optional key)
16992 "Edit the value of the property at point in column view.
16993 Where possible, use the standard interface for changing this line."
16994 (interactive)
16995 (org-columns-check-computed)
16996 (let* ((external-key key)
16997 (col (current-column))
16998 (key (or 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 nval eval allowed)
17011 (cond
17012 ((equal key "CLOCKSUM")
17013 (error "This special column cannot be edited"))
17014 ((equal key "ITEM")
17015 (setq eval '(org-with-point-at pom
17016 (org-edit-headline))))
17017 ((equal key "TODO")
17018 (setq eval '(org-with-point-at pom
17019 (let ((current-prefix-arg
17020 (if external-key current-prefix-arg '(4))))
17021 (call-interactively 'org-todo)))))
17022 ((equal key "PRIORITY")
17023 (setq eval '(org-with-point-at pom
17024 (call-interactively 'org-priority))))
17025 ((equal key "TAGS")
17026 (setq eval '(org-with-point-at pom
17027 (let ((org-fast-tag-selection-single-key
17028 (if (eq org-fast-tag-selection-single-key 'expert)
17029 t org-fast-tag-selection-single-key)))
17030 (call-interactively 'org-set-tags)))))
17031 ((equal key "DEADLINE")
17032 (setq eval '(org-with-point-at pom
17033 (call-interactively 'org-deadline))))
17034 ((equal key "SCHEDULED")
17035 (setq eval '(org-with-point-at pom
17036 (call-interactively 'org-schedule))))
17038 (setq allowed (org-property-get-allowed-values pom key 'table))
17039 (if allowed
17040 (setq nval (completing-read "Value: " allowed nil t))
17041 (setq nval (read-string "Edit: " value)))
17042 (setq nval (org-trim nval))
17043 (when (not (equal nval value))
17044 (setq eval '(org-entry-put pom key nval)))))
17045 (when eval
17046 (let ((inhibit-read-only t))
17047 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
17048 (unwind-protect
17049 (progn
17050 (setq org-columns-overlays
17051 (org-delete-all line-overlays org-columns-overlays))
17052 (mapc 'org-delete-overlay line-overlays)
17053 (org-columns-eval eval))
17054 (org-columns-display-here))))
17055 (move-to-column col)
17056 (if (and (org-mode-p)
17057 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17058 (org-columns-update key))))
17060 (defun org-edit-headline () ; FIXME: this is not columns specific
17061 "Edit the current headline, the part without TODO keyword, TAGS."
17062 (org-back-to-heading)
17063 (when (looking-at org-todo-line-regexp)
17064 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
17065 (txt (match-string 3))
17066 (post "")
17067 txt2)
17068 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
17069 (setq post (match-string 0 txt)
17070 txt (substring txt 0 (match-beginning 0))))
17071 (setq txt2 (read-string "Edit: " txt))
17072 (when (not (equal txt txt2))
17073 (beginning-of-line 1)
17074 (insert pre txt2 post)
17075 (delete-region (point) (point-at-eol))
17076 (org-set-tags nil t)))))
17078 (defun org-columns-edit-allowed ()
17079 "Edit the list of allowed values for the current property."
17080 (interactive)
17081 (let* ((key (get-char-property (point) 'org-columns-key))
17082 (key1 (concat key "_ALL"))
17083 (allowed (org-entry-get (point) key1 t))
17084 nval)
17085 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
17086 (setq nval (read-string "Allowed: " allowed))
17087 (org-entry-put
17088 (cond ((marker-position org-entry-property-inherited-from)
17089 org-entry-property-inherited-from)
17090 ((marker-position org-columns-top-level-marker)
17091 org-columns-top-level-marker))
17092 key1 nval)))
17094 (defmacro org-no-warnings (&rest body)
17095 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17097 (defun org-columns-eval (form)
17098 (let (hidep)
17099 (save-excursion
17100 (beginning-of-line 1)
17101 ;; `next-line' is needed here, because it skips invisible line.
17102 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17103 (setq hidep (org-on-heading-p 1)))
17104 (eval form)
17105 (and hidep (hide-entry))))
17107 (defun org-columns-previous-allowed-value ()
17108 "Switch to the previous allowed value for this column."
17109 (interactive)
17110 (org-columns-next-allowed-value t))
17112 (defun org-columns-next-allowed-value (&optional previous)
17113 "Switch to the next allowed value for this column."
17114 (interactive)
17115 (org-columns-check-computed)
17116 (let* ((col (current-column))
17117 (key (get-char-property (point) 'org-columns-key))
17118 (value (get-char-property (point) 'org-columns-value))
17119 (bol (point-at-bol)) (eol (point-at-eol))
17120 (pom (or (get-text-property bol 'org-hd-marker)
17121 (point))) ; keep despite of compiler waring
17122 (line-overlays
17123 (delq nil (mapcar (lambda (x)
17124 (and (eq (overlay-buffer x) (current-buffer))
17125 (>= (overlay-start x) bol)
17126 (<= (overlay-start x) eol)
17128 org-columns-overlays)))
17129 (allowed (or (org-property-get-allowed-values pom key)
17130 (and (memq
17131 (nth 4 (assoc key org-columns-current-fmt-compiled))
17132 '(checkbox checkbox-n-of-m checkbox-percent))
17133 '("[ ]" "[X]"))))
17134 nval)
17135 (when (equal key "ITEM")
17136 (error "Cannot edit item headline from here"))
17137 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17138 (error "Allowed values for this property have not been defined"))
17139 (if (member key '("SCHEDULED" "DEADLINE"))
17140 (setq nval (if previous 'earlier 'later))
17141 (if previous (setq allowed (reverse allowed)))
17142 (if (member value allowed)
17143 (setq nval (car (cdr (member value allowed)))))
17144 (setq nval (or nval (car allowed)))
17145 (if (equal nval value)
17146 (error "Only one allowed value for this property")))
17147 (let ((inhibit-read-only t))
17148 (remove-text-properties (1- bol) eol '(read-only t))
17149 (unwind-protect
17150 (progn
17151 (setq org-columns-overlays
17152 (org-delete-all line-overlays org-columns-overlays))
17153 (mapc 'org-delete-overlay line-overlays)
17154 (org-columns-eval '(org-entry-put pom key nval)))
17155 (org-columns-display-here)))
17156 (move-to-column col)
17157 (if (and (org-mode-p)
17158 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17159 (org-columns-update key))))
17161 (defun org-verify-version (task)
17162 (cond
17163 ((eq task 'columns)
17164 (if (or (featurep 'xemacs)
17165 (< emacs-major-version 22))
17166 (error "Emacs 22 is required for the columns feature")))))
17168 (defun org-columns-open-link (&optional arg)
17169 (interactive "P")
17170 (let ((value (get-char-property (point) 'org-columns-value)))
17171 (org-open-link-from-string value arg)))
17173 (defun org-open-link-from-string (s &optional arg)
17174 "Open a link in the string S, as if it was in Org-mode."
17175 (interactive)
17176 (with-temp-buffer
17177 (let ((org-inhibit-startup t))
17178 (org-mode)
17179 (insert s)
17180 (goto-char (point-min))
17181 (org-open-at-point arg))))
17183 (defun org-columns-get-format-and-top-level ()
17184 (let (fmt)
17185 (when (condition-case nil (org-back-to-heading) (error nil))
17186 (move-marker org-entry-property-inherited-from nil)
17187 (setq fmt (org-entry-get nil "COLUMNS" t)))
17188 (setq fmt (or fmt org-columns-default-format))
17189 (org-set-local 'org-columns-current-fmt fmt)
17190 (org-columns-compile-format fmt)
17191 (if (marker-position org-entry-property-inherited-from)
17192 (move-marker org-columns-top-level-marker
17193 org-entry-property-inherited-from)
17194 (move-marker org-columns-top-level-marker (point)))
17195 fmt))
17197 (defun org-columns ()
17198 "Turn on column view on an org-mode file."
17199 (interactive)
17200 (org-verify-version 'columns)
17201 (org-columns-remove-overlays)
17202 (move-marker org-columns-begin-marker (point))
17203 (let (beg end fmt cache maxwidths)
17204 (setq fmt (org-columns-get-format-and-top-level))
17205 (save-excursion
17206 (goto-char org-columns-top-level-marker)
17207 (setq beg (point))
17208 (unless org-columns-inhibit-recalculation
17209 (org-columns-compute-all))
17210 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17211 (point-max)))
17212 ;; Get and cache the properties
17213 (goto-char beg)
17214 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17215 (save-excursion
17216 (save-restriction
17217 (narrow-to-region beg end)
17218 (org-clock-sum))))
17219 (while (re-search-forward (concat "^" outline-regexp) end t)
17220 (push (cons (org-current-line) (org-entry-properties)) cache))
17221 (when cache
17222 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17223 (org-set-local 'org-columns-current-maxwidths maxwidths)
17224 (org-columns-display-here-title)
17225 (mapc (lambda (x)
17226 (goto-line (car x))
17227 (org-columns-display-here (cdr x)))
17228 cache)))))
17230 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17231 "Insert a new column, to the leeft o the current column."
17232 (interactive)
17233 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17234 cell)
17235 (setq prop (completing-read
17236 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17237 nil nil prop))
17238 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17239 (setq width (read-string "Column width: " (if width (number-to-string width))))
17240 (if (string-match "\\S-" width)
17241 (setq width (string-to-number width))
17242 (setq width nil))
17243 (setq fmt (completing-read "Summary [none]: "
17244 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17245 nil t))
17246 (if (string-match "\\S-" fmt)
17247 (setq fmt (intern fmt))
17248 (setq fmt nil))
17249 (if (eq fmt 'none) (setq fmt nil))
17250 (if editp
17251 (progn
17252 (setcar editp prop)
17253 (setcdr editp (list title width nil fmt)))
17254 (setq cell (nthcdr (1- (current-column))
17255 org-columns-current-fmt-compiled))
17256 (setcdr cell (cons (list prop title width nil fmt)
17257 (cdr cell))))
17258 (org-columns-store-format)
17259 (org-columns-redo)))
17261 (defun org-columns-delete ()
17262 "Delete the column at point from columns view."
17263 (interactive)
17264 (let* ((n (current-column))
17265 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17266 (when (y-or-n-p
17267 (format "Are you sure you want to remove column \"%s\"? " title))
17268 (setq org-columns-current-fmt-compiled
17269 (delq (nth n org-columns-current-fmt-compiled)
17270 org-columns-current-fmt-compiled))
17271 (org-columns-store-format)
17272 (org-columns-redo)
17273 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17274 (backward-char 1)))))
17276 (defun org-columns-edit-attributes ()
17277 "Edit the attributes of the current column."
17278 (interactive)
17279 (let* ((n (current-column))
17280 (info (nth n org-columns-current-fmt-compiled)))
17281 (apply 'org-columns-new info)))
17283 (defun org-columns-widen (arg)
17284 "Make the column wider by ARG characters."
17285 (interactive "p")
17286 (let* ((n (current-column))
17287 (entry (nth n org-columns-current-fmt-compiled))
17288 (width (or (nth 2 entry)
17289 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17290 (setq width (max 1 (+ width arg)))
17291 (setcar (nthcdr 2 entry) width)
17292 (org-columns-store-format)
17293 (org-columns-redo)))
17295 (defun org-columns-narrow (arg)
17296 "Make the column nrrower by ARG characters."
17297 (interactive "p")
17298 (org-columns-widen (- arg)))
17300 (defun org-columns-move-right ()
17301 "Swap this column with the one to the right."
17302 (interactive)
17303 (let* ((n (current-column))
17304 (cell (nthcdr n org-columns-current-fmt-compiled))
17306 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17307 (error "Cannot shift this column further to the right"))
17308 (setq e (car cell))
17309 (setcar cell (car (cdr cell)))
17310 (setcdr cell (cons e (cdr (cdr cell))))
17311 (org-columns-store-format)
17312 (org-columns-redo)
17313 (forward-char 1)))
17315 (defun org-columns-move-left ()
17316 "Swap this column with the one to the left."
17317 (interactive)
17318 (let* ((n (current-column)))
17319 (when (= n 0)
17320 (error "Cannot shift this column further to the left"))
17321 (backward-char 1)
17322 (org-columns-move-right)
17323 (backward-char 1)))
17325 (defun org-columns-store-format ()
17326 "Store the text version of the current columns format in appropriate place.
17327 This is either in the COLUMNS property of the node starting the current column
17328 display, or in the #+COLUMNS line of the current buffer."
17329 (let (fmt (cnt 0))
17330 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17331 (org-set-local 'org-columns-current-fmt fmt)
17332 (if (marker-position org-columns-top-level-marker)
17333 (save-excursion
17334 (goto-char org-columns-top-level-marker)
17335 (if (and (org-at-heading-p)
17336 (org-entry-get nil "COLUMNS"))
17337 (org-entry-put nil "COLUMNS" fmt)
17338 (goto-char (point-min))
17339 ;; Overwrite all #+COLUMNS lines....
17340 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17341 (setq cnt (1+ cnt))
17342 (replace-match (concat "#+COLUMNS: " fmt) t t))
17343 (unless (> cnt 0)
17344 (goto-char (point-min))
17345 (or (org-on-heading-p t) (outline-next-heading))
17346 (let ((inhibit-read-only t))
17347 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17348 (org-set-local 'org-columns-default-format fmt))))))
17350 (defvar org-overriding-columns-format nil
17351 "When set, overrides any other definition.")
17352 (defvar org-agenda-view-columns-initially nil
17353 "When set, switch to columns view immediately after creating the agenda.")
17355 (defun org-agenda-columns ()
17356 "Turn on column view in the agenda."
17357 (interactive)
17358 (org-verify-version 'columns)
17359 (org-columns-remove-overlays)
17360 (move-marker org-columns-begin-marker (point))
17361 (let (fmt cache maxwidths m)
17362 (cond
17363 ((and (local-variable-p 'org-overriding-columns-format)
17364 org-overriding-columns-format)
17365 (setq fmt org-overriding-columns-format))
17366 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17367 (setq fmt (org-entry-get m "COLUMNS" t)))
17368 ((and (boundp 'org-columns-current-fmt)
17369 (local-variable-p 'org-columns-current-fmt)
17370 org-columns-current-fmt)
17371 (setq fmt org-columns-current-fmt))
17372 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17373 (setq m (get-text-property m 'org-hd-marker))
17374 (setq fmt (org-entry-get m "COLUMNS" t))))
17375 (setq fmt (or fmt org-columns-default-format))
17376 (org-set-local 'org-columns-current-fmt fmt)
17377 (org-columns-compile-format fmt)
17378 (save-excursion
17379 ;; Get and cache the properties
17380 (goto-char (point-min))
17381 (while (not (eobp))
17382 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17383 (get-text-property (point) 'org-marker)))
17384 (push (cons (org-current-line) (org-entry-properties m)) cache))
17385 (beginning-of-line 2))
17386 (when cache
17387 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17388 (org-set-local 'org-columns-current-maxwidths maxwidths)
17389 (org-columns-display-here-title)
17390 (mapc (lambda (x)
17391 (goto-line (car x))
17392 (org-columns-display-here (cdr x)))
17393 cache)))))
17395 (defun org-columns-get-autowidth-alist (s cache)
17396 "Derive the maximum column widths from the format and the cache."
17397 (let ((start 0) rtn)
17398 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17399 (push (cons (match-string 1 s) 1) rtn)
17400 (setq start (match-end 0)))
17401 (mapc (lambda (x)
17402 (setcdr x (apply 'max
17403 (mapcar
17404 (lambda (y)
17405 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17406 cache))))
17407 rtn)
17408 rtn))
17410 (defun org-columns-compute-all ()
17411 "Compute all columns that have operators defined."
17412 (org-unmodified
17413 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17414 (let ((columns org-columns-current-fmt-compiled) col)
17415 (while (setq col (pop columns))
17416 (when (nth 3 col)
17417 (save-excursion
17418 (org-columns-compute (car col)))))))
17420 (defun org-columns-update (property)
17421 "Recompute PROPERTY, and update the columns display for it."
17422 (org-columns-compute property)
17423 (let (fmt val pos)
17424 (save-excursion
17425 (mapc (lambda (ov)
17426 (when (equal (org-overlay-get ov 'org-columns-key) property)
17427 (setq pos (org-overlay-start ov))
17428 (goto-char pos)
17429 (when (setq val (cdr (assoc property
17430 (get-text-property
17431 (point-at-bol) 'org-summaries))))
17432 (setq fmt (org-overlay-get ov 'org-columns-format))
17433 (org-overlay-put ov 'org-columns-value val)
17434 (org-overlay-put ov 'display (format fmt val)))))
17435 org-columns-overlays))))
17437 (defun org-columns-compute (property)
17438 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17439 (interactive)
17440 (let* ((re (concat "^" outline-regexp))
17441 (lmax 30) ; Does anyone use deeper levels???
17442 (lsum (make-vector lmax 0))
17443 (lflag (make-vector lmax nil))
17444 (level 0)
17445 (ass (assoc property org-columns-current-fmt-compiled))
17446 (format (nth 4 ass))
17447 (printf (nth 5 ass))
17448 (beg org-columns-top-level-marker)
17449 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17450 (save-excursion
17451 ;; Find the region to compute
17452 (goto-char beg)
17453 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17454 (goto-char end)
17455 ;; Walk the tree from the back and do the computations
17456 (while (re-search-backward re beg t)
17457 (setq sumpos (match-beginning 0)
17458 last-level level
17459 level (org-outline-level)
17460 val (org-entry-get nil property)
17461 valflag (and val (string-match "\\S-" val)))
17462 (cond
17463 ((< level last-level)
17464 ;; put the sum of lower levels here as a property
17465 (setq sum (aref lsum last-level) ; current sum
17466 flag (aref lflag last-level) ; any valid entries from children?
17467 str (org-column-number-to-string sum format printf)
17468 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17469 useval (if flag str1 (if valflag val ""))
17470 sum-alist (get-text-property sumpos 'org-summaries))
17471 (if (assoc property sum-alist)
17472 (setcdr (assoc property sum-alist) useval)
17473 (push (cons property useval) sum-alist)
17474 (org-unmodified
17475 (add-text-properties sumpos (1+ sumpos)
17476 (list 'org-summaries sum-alist))))
17477 (when val
17478 (org-entry-put nil property (if flag str val)))
17479 ;; add current to current level accumulator
17480 (when (or flag valflag)
17481 (aset lsum level (+ (aref lsum level)
17482 (if flag sum (org-column-string-to-number
17483 (if flag str val) format))))
17484 (aset lflag level t))
17485 ;; clear accumulators for deeper levels
17486 (loop for l from (1+ level) to (1- lmax) do
17487 (aset lsum l 0)
17488 (aset lflag l nil)))
17489 ((>= level last-level)
17490 ;; add what we have here to the accumulator for this level
17491 (aset lsum level (+ (aref lsum level)
17492 (org-column-string-to-number (or val "0") format)))
17493 (and valflag (aset lflag level t)))
17494 (t (error "This should not happen")))))))
17496 (defun org-columns-redo ()
17497 "Construct the column display again."
17498 (interactive)
17499 (message "Recomputing columns...")
17500 (save-excursion
17501 (if (marker-position org-columns-begin-marker)
17502 (goto-char org-columns-begin-marker))
17503 (org-columns-remove-overlays)
17504 (if (org-mode-p)
17505 (call-interactively 'org-columns)
17506 (call-interactively 'org-agenda-columns)))
17507 (message "Recomputing columns...done"))
17509 (defun org-columns-not-in-agenda ()
17510 (if (eq major-mode 'org-agenda-mode)
17511 (error "This command is only allowed in Org-mode buffers")))
17514 (defun org-string-to-number (s)
17515 "Convert string to number, and interpret hh:mm:ss."
17516 (if (not (string-match ":" s))
17517 (string-to-number s)
17518 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17519 (while l
17520 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17521 sum)))
17523 (defun org-column-number-to-string (n fmt &optional printf)
17524 "Convert a computed column number to a string value, according to FMT."
17525 (cond
17526 ((eq fmt 'add_times)
17527 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17528 (format "%d:%02d" h m)))
17529 ((eq fmt 'checkbox)
17530 (cond ((= n (floor n)) "[X]")
17531 ((> n 1.) "[-]")
17532 (t "[ ]")))
17533 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17534 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17535 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17536 (printf (format printf n))
17537 ((eq fmt 'currency)
17538 (format "%.2f" n))
17539 (t (number-to-string n))))
17541 (defun org-nofm-to-completion (n m &optional percent)
17542 (if (not percent)
17543 (format "[%d/%d]" n m)
17544 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17546 (defun org-column-string-to-number (s fmt)
17547 "Convert a column value to a number that can be used for column computing."
17548 (cond
17549 ((string-match ":" s)
17550 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17551 (while l
17552 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17553 sum))
17554 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17555 (if (equal s "[X]") 1. 0.000001))
17556 (t (string-to-number s))))
17558 (defun org-columns-uncompile-format (cfmt)
17559 "Turn the compiled columns format back into a string representation."
17560 (let ((rtn "") e s prop title op width fmt printf)
17561 (while (setq e (pop cfmt))
17562 (setq prop (car e)
17563 title (nth 1 e)
17564 width (nth 2 e)
17565 op (nth 3 e)
17566 fmt (nth 4 e)
17567 printf (nth 5 e))
17568 (cond
17569 ((eq fmt 'add_times) (setq op ":"))
17570 ((eq fmt 'checkbox) (setq op "X"))
17571 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17572 ((eq fmt 'checkbox-percent) (setq op "X%"))
17573 ((eq fmt 'add_numbers) (setq op "+"))
17574 ((eq fmt 'currency) (setq op "$")))
17575 (if (and op printf) (setq op (concat op ";" printf)))
17576 (if (equal title prop) (setq title nil))
17577 (setq s (concat "%" (if width (number-to-string width))
17578 prop
17579 (if title (concat "(" title ")"))
17580 (if op (concat "{" op "}"))))
17581 (setq rtn (concat rtn " " s)))
17582 (org-trim rtn)))
17584 (defun org-columns-compile-format (fmt)
17585 "Turn a column format string into an alist of specifications.
17586 The alist has one entry for each column in the format. The elements of
17587 that list are:
17588 property the property
17589 title the title field for the columns
17590 width the column width in characters, can be nil for automatic
17591 operator the operator if any
17592 format the output format for computed results, derived from operator
17593 printf a printf format for computed values"
17594 (let ((start 0) width prop title op f printf)
17595 (setq org-columns-current-fmt-compiled nil)
17596 (while (string-match
17597 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17598 fmt start)
17599 (setq start (match-end 0)
17600 width (match-string 1 fmt)
17601 prop (match-string 2 fmt)
17602 title (or (match-string 3 fmt) prop)
17603 op (match-string 4 fmt)
17604 f nil
17605 printf nil)
17606 (if width (setq width (string-to-number width)))
17607 (when (and op (string-match ";" op))
17608 (setq printf (substring op (match-end 0))
17609 op (substring op 0 (match-beginning 0))))
17610 (cond
17611 ((equal op "+") (setq f 'add_numbers))
17612 ((equal op "$") (setq f 'currency))
17613 ((equal op ":") (setq f 'add_times))
17614 ((equal op "X") (setq f 'checkbox))
17615 ((equal op "X/") (setq f 'checkbox-n-of-m))
17616 ((equal op "X%") (setq f 'checkbox-percent))
17618 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17619 (setq org-columns-current-fmt-compiled
17620 (nreverse org-columns-current-fmt-compiled))))
17623 ;;; Dynamic block for Column view
17625 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17626 "Get the column view of the current buffer or subtree.
17627 The first optional argument MAXLEVEL sets the level limit. A
17628 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17629 empty rows, an empty row being one where all the column view
17630 specifiers except ITEM are empty. This function returns a list
17631 containing the title row and all other rows. Each row is a list
17632 of fields."
17633 (save-excursion
17634 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17635 (n (length title)) row tbl)
17636 (goto-char (point-min))
17637 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17638 (or (null maxlevel)
17639 (>= maxlevel
17640 (if org-odd-levels-only
17641 (/ (1+ (length (match-string 1))) 2)
17642 (length (match-string 1))))))
17643 (when (get-char-property (match-beginning 0) 'org-columns-key)
17644 (setq row nil)
17645 (loop for i from 0 to (1- n) do
17646 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17647 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17649 row))
17650 (setq row (nreverse row))
17651 (unless (and skip-empty-rows
17652 (eq 1 (length (delete "" (delete-dups row)))))
17653 (push row tbl))))
17654 (append (list title 'hline) (nreverse tbl)))))
17656 (defun org-dblock-write:columnview (params)
17657 "Write the column view table.
17658 PARAMS is a property list of parameters:
17660 :width enforce same column widths with <N> specifiers.
17661 :id the :ID: property of the entry where the columns view
17662 should be built, as a string. When `local', call locally.
17663 When `global' call column view with the cursor at the beginning
17664 of the buffer (usually this means that the whole buffer switches
17665 to column view).
17666 :hlines When t, insert a hline before each item. When a number, insert
17667 a hline before each level <= that number.
17668 :vlines When t, make each column a colgroup to enforce vertical lines.
17669 :maxlevel When set to a number, don't capture headlines below this level.
17670 :skip-empty-rows
17671 When t, skip rows where all specifiers other than ITEM are empty."
17672 (let ((pos (move-marker (make-marker) (point)))
17673 (hlines (plist-get params :hlines))
17674 (vlines (plist-get params :vlines))
17675 (maxlevel (plist-get params :maxlevel))
17676 (skip-empty-rows (plist-get params :skip-empty-rows))
17677 tbl id idpos nfields tmp)
17678 (save-excursion
17679 (save-restriction
17680 (when (setq id (plist-get params :id))
17681 (cond ((not id) nil)
17682 ((eq id 'global) (goto-char (point-min)))
17683 ((eq id 'local) nil)
17684 ((setq idpos (org-find-entry-with-id id))
17685 (goto-char idpos))
17686 (t (error "Cannot find entry with :ID: %s" id))))
17687 (org-columns)
17688 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17689 (setq nfields (length (car tbl)))
17690 (org-columns-quit)))
17691 (goto-char pos)
17692 (move-marker pos nil)
17693 (when tbl
17694 (when (plist-get params :hlines)
17695 (setq tmp nil)
17696 (while tbl
17697 (if (eq (car tbl) 'hline)
17698 (push (pop tbl) tmp)
17699 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17700 (if (and (not (eq (car tmp) 'hline))
17701 (or (eq hlines t)
17702 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17703 (push 'hline tmp)))
17704 (push (pop tbl) tmp)))
17705 (setq tbl (nreverse tmp)))
17706 (when vlines
17707 (setq tbl (mapcar (lambda (x)
17708 (if (eq 'hline x) x (cons "" x)))
17709 tbl))
17710 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17711 (setq pos (point))
17712 (insert (org-listtable-to-string tbl))
17713 (when (plist-get params :width)
17714 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17715 org-columns-current-widths "|")))
17716 (goto-char pos)
17717 (org-table-align))))
17719 (defun org-listtable-to-string (tbl)
17720 "Convert a listtable TBL to a string that contains the Org-mode table.
17721 The table still need to be alligned. The resulting string has no leading
17722 and tailing newline characters."
17723 (mapconcat
17724 (lambda (x)
17725 (cond
17726 ((listp x)
17727 (concat "|" (mapconcat 'identity x "|") "|"))
17728 ((eq x 'hline) "|-|")
17729 (t (error "Garbage in listtable: %s" x))))
17730 tbl "\n"))
17732 (defun org-insert-columns-dblock ()
17733 "Create a dynamic block capturing a column view table."
17734 (interactive)
17735 (let ((defaults '(:name "columnview" :hlines 1))
17736 (id (completing-read
17737 "Capture columns (local, global, entry with :ID: property) [local]: "
17738 (append '(("global") ("local"))
17739 (mapcar 'list (org-property-values "ID"))))))
17740 (if (equal id "") (setq id 'local))
17741 (if (equal id "global") (setq id 'global))
17742 (setq defaults (append defaults (list :id id)))
17743 (org-create-dblock defaults)
17744 (org-update-dblock)))
17746 ;;;; Timestamps
17748 (defvar org-last-changed-timestamp nil)
17749 (defvar org-time-was-given) ; dynamically scoped parameter
17750 (defvar org-end-time-was-given) ; dynamically scoped parameter
17751 (defvar org-ts-what) ; dynamically scoped parameter
17753 (defun org-time-stamp (arg)
17754 "Prompt for a date/time and insert a time stamp.
17755 If the user specifies a time like HH:MM, or if this command is called
17756 with a prefix argument, the time stamp will contain date and time.
17757 Otherwise, only the date will be included. All parts of a date not
17758 specified by the user will be filled in from the current date/time.
17759 So if you press just return without typing anything, the time stamp
17760 will represent the current date/time. If there is already a timestamp
17761 at the cursor, it will be modified."
17762 (interactive "P")
17763 (let* ((ts nil)
17764 (default-time
17765 ;; Default time is either today, or, when entering a range,
17766 ;; the range start.
17767 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17768 (save-excursion
17769 (re-search-backward
17770 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17771 (- (point) 20) t)))
17772 (apply 'encode-time (org-parse-time-string (match-string 1)))
17773 (current-time)))
17774 (default-input (and ts (org-get-compact-tod ts)))
17775 org-time-was-given org-end-time-was-given time)
17776 (cond
17777 ((and (org-at-timestamp-p)
17778 (eq last-command 'org-time-stamp)
17779 (eq this-command 'org-time-stamp))
17780 (insert "--")
17781 (setq time (let ((this-command this-command))
17782 (org-read-date arg 'totime nil nil default-time default-input)))
17783 (org-insert-time-stamp time (or org-time-was-given arg)))
17784 ((org-at-timestamp-p)
17785 (setq time (let ((this-command this-command))
17786 (org-read-date arg 'totime nil nil default-time default-input)))
17787 (when (org-at-timestamp-p) ; just to get the match data
17788 (replace-match "")
17789 (setq org-last-changed-timestamp
17790 (org-insert-time-stamp
17791 time (or org-time-was-given arg)
17792 nil nil nil (list org-end-time-was-given))))
17793 (message "Timestamp updated"))
17795 (setq time (let ((this-command this-command))
17796 (org-read-date arg 'totime nil nil default-time default-input)))
17797 (org-insert-time-stamp time (or org-time-was-given arg)
17798 nil nil nil (list org-end-time-was-given))))))
17800 ;; FIXME: can we use this for something else????
17801 ;; like computing time differences?????
17802 (defun org-get-compact-tod (s)
17803 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17804 (let* ((t1 (match-string 1 s))
17805 (h1 (string-to-number (match-string 2 s)))
17806 (m1 (string-to-number (match-string 3 s)))
17807 (t2 (and (match-end 4) (match-string 5 s)))
17808 (h2 (and t2 (string-to-number (match-string 6 s))))
17809 (m2 (and t2 (string-to-number (match-string 7 s))))
17810 dh dm)
17811 (if (not t2)
17813 (setq dh (- h2 h1) dm (- m2 m1))
17814 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17815 (concat t1 "+" (number-to-string dh)
17816 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17818 (defun org-time-stamp-inactive (&optional arg)
17819 "Insert an inactive time stamp.
17820 An inactive time stamp is enclosed in square brackets instead of angle
17821 brackets. It is inactive in the sense that it does not trigger agenda entries,
17822 does not link to the calendar and cannot be changed with the S-cursor keys.
17823 So these are more for recording a certain time/date."
17824 (interactive "P")
17825 (let (org-time-was-given org-end-time-was-given time)
17826 (setq time (org-read-date arg 'totime))
17827 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17828 nil nil (list org-end-time-was-given))))
17830 (defvar org-date-ovl (org-make-overlay 1 1))
17831 (org-overlay-put org-date-ovl 'face 'org-warning)
17832 (org-detach-overlay org-date-ovl)
17834 (defvar org-ans1) ; dynamically scoped parameter
17835 (defvar org-ans2) ; dynamically scoped parameter
17837 (defvar org-plain-time-of-day-regexp) ; defined below
17839 (defvar org-read-date-overlay nil)
17840 (defvar org-dcst nil) ; dynamically scoped
17842 (defun org-read-date (&optional with-time to-time from-string prompt
17843 default-time default-input)
17844 "Read a date, possibly a time, and make things smooth for the user.
17845 The prompt will suggest to enter an ISO date, but you can also enter anything
17846 which will at least partially be understood by `parse-time-string'.
17847 Unrecognized parts of the date will default to the current day, month, year,
17848 hour and minute. If this command is called to replace a timestamp at point,
17849 of to enter the second timestamp of a range, the default time is taken from the
17850 existing stamp. For example,
17851 3-2-5 --> 2003-02-05
17852 feb 15 --> currentyear-02-15
17853 sep 12 9 --> 2009-09-12
17854 12:45 --> today 12:45
17855 22 sept 0:34 --> currentyear-09-22 0:34
17856 12 --> currentyear-currentmonth-12
17857 Fri --> nearest Friday (today or later)
17858 etc.
17860 Furthermore you can specify a relative date by giving, as the *first* thing
17861 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17862 change in days weeks, months, years.
17863 With a single plus or minus, the date is relative to today. With a double
17864 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17865 +4d --> four days from today
17866 +4 --> same as above
17867 +2w --> two weeks from today
17868 ++5 --> five days from default date
17870 The function understands only English month and weekday abbreviations,
17871 but this can be configured with the variables `parse-time-months' and
17872 `parse-time-weekdays'.
17874 While prompting, a calendar is popped up - you can also select the
17875 date with the mouse (button 1). The calendar shows a period of three
17876 months. To scroll it to other months, use the keys `>' and `<'.
17877 If you don't like the calendar, turn it off with
17878 \(setq org-read-date-popup-calendar nil)
17880 With optional argument TO-TIME, the date will immediately be converted
17881 to an internal time.
17882 With an optional argument WITH-TIME, the prompt will suggest to also
17883 insert a time. Note that when WITH-TIME is not set, you can still
17884 enter a time, and this function will inform the calling routine about
17885 this change. The calling routine may then choose to change the format
17886 used to insert the time stamp into the buffer to include the time.
17887 With optional argument FROM-STRING, read from this string instead from
17888 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17889 the time/date that is used for everything that is not specified by the
17890 user."
17891 (require 'parse-time)
17892 (let* ((org-time-stamp-rounding-minutes
17893 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17894 (org-dcst org-display-custom-times)
17895 (ct (org-current-time))
17896 (def (or default-time ct))
17897 (defdecode (decode-time def))
17898 (dummy (progn
17899 (when (< (nth 2 defdecode) org-extend-today-until)
17900 (setcar (nthcdr 2 defdecode) -1)
17901 (setcar (nthcdr 1 defdecode) 59)
17902 (setq def (apply 'encode-time defdecode)
17903 defdecode (decode-time def)))))
17904 (calendar-move-hook nil)
17905 (view-diary-entries-initially nil)
17906 (view-calendar-holidays-initially nil)
17907 (timestr (format-time-string
17908 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17909 (prompt (concat (if prompt (concat prompt " ") "")
17910 (format "Date+time [%s]: " timestr)))
17911 ans (org-ans0 "") org-ans1 org-ans2 final)
17913 (cond
17914 (from-string (setq ans from-string))
17915 (org-read-date-popup-calendar
17916 (save-excursion
17917 (save-window-excursion
17918 (calendar)
17919 (calendar-forward-day (- (time-to-days def)
17920 (calendar-absolute-from-gregorian
17921 (calendar-current-date))))
17922 (org-eval-in-calendar nil t)
17923 (let* ((old-map (current-local-map))
17924 (map (copy-keymap calendar-mode-map))
17925 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17926 (org-defkey map (kbd "RET") 'org-calendar-select)
17927 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17928 'org-calendar-select-mouse)
17929 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17930 'org-calendar-select-mouse)
17931 (org-defkey minibuffer-local-map [(meta shift left)]
17932 (lambda () (interactive)
17933 (org-eval-in-calendar '(calendar-backward-month 1))))
17934 (org-defkey minibuffer-local-map [(meta shift right)]
17935 (lambda () (interactive)
17936 (org-eval-in-calendar '(calendar-forward-month 1))))
17937 (org-defkey minibuffer-local-map [(meta shift up)]
17938 (lambda () (interactive)
17939 (org-eval-in-calendar '(calendar-backward-year 1))))
17940 (org-defkey minibuffer-local-map [(meta shift down)]
17941 (lambda () (interactive)
17942 (org-eval-in-calendar '(calendar-forward-year 1))))
17943 (org-defkey minibuffer-local-map [(shift up)]
17944 (lambda () (interactive)
17945 (org-eval-in-calendar '(calendar-backward-week 1))))
17946 (org-defkey minibuffer-local-map [(shift down)]
17947 (lambda () (interactive)
17948 (org-eval-in-calendar '(calendar-forward-week 1))))
17949 (org-defkey minibuffer-local-map [(shift left)]
17950 (lambda () (interactive)
17951 (org-eval-in-calendar '(calendar-backward-day 1))))
17952 (org-defkey minibuffer-local-map [(shift right)]
17953 (lambda () (interactive)
17954 (org-eval-in-calendar '(calendar-forward-day 1))))
17955 (org-defkey minibuffer-local-map ">"
17956 (lambda () (interactive)
17957 (org-eval-in-calendar '(scroll-calendar-left 1))))
17958 (org-defkey minibuffer-local-map "<"
17959 (lambda () (interactive)
17960 (org-eval-in-calendar '(scroll-calendar-right 1))))
17961 (unwind-protect
17962 (progn
17963 (use-local-map map)
17964 (add-hook 'post-command-hook 'org-read-date-display)
17965 (setq org-ans0 (read-string prompt default-input nil nil))
17966 ;; org-ans0: from prompt
17967 ;; org-ans1: from mouse click
17968 ;; org-ans2: from calendar motion
17969 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17970 (remove-hook 'post-command-hook 'org-read-date-display)
17971 (use-local-map old-map)
17972 (when org-read-date-overlay
17973 (org-delete-overlay org-read-date-overlay)
17974 (setq org-read-date-overlay nil)))))))
17976 (t ; Naked prompt only
17977 (unwind-protect
17978 (setq ans (read-string prompt default-input nil timestr))
17979 (when org-read-date-overlay
17980 (org-delete-overlay org-read-date-overlay)
17981 (setq org-read-date-overlay nil)))))
17983 (setq final (org-read-date-analyze ans def defdecode))
17985 (if to-time
17986 (apply 'encode-time final)
17987 (if (and (boundp 'org-time-was-given) org-time-was-given)
17988 (format "%04d-%02d-%02d %02d:%02d"
17989 (nth 5 final) (nth 4 final) (nth 3 final)
17990 (nth 2 final) (nth 1 final))
17991 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17992 (defvar def)
17993 (defvar defdecode)
17994 (defvar with-time)
17995 (defun org-read-date-display ()
17996 "Display the currrent date prompt interpretation in the minibuffer."
17997 (when org-read-date-display-live
17998 (when org-read-date-overlay
17999 (org-delete-overlay org-read-date-overlay))
18000 (let ((p (point)))
18001 (end-of-line 1)
18002 (while (not (equal (buffer-substring
18003 (max (point-min) (- (point) 4)) (point))
18004 " "))
18005 (insert " "))
18006 (goto-char p))
18007 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
18008 " " (or org-ans1 org-ans2)))
18009 (org-end-time-was-given nil)
18010 (f (org-read-date-analyze ans def defdecode))
18011 (fmts (if org-dcst
18012 org-time-stamp-custom-formats
18013 org-time-stamp-formats))
18014 (fmt (if (or with-time
18015 (and (boundp 'org-time-was-given) org-time-was-given))
18016 (cdr fmts)
18017 (car fmts)))
18018 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
18019 (when (and org-end-time-was-given
18020 (string-match org-plain-time-of-day-regexp txt))
18021 (setq txt (concat (substring txt 0 (match-end 0)) "-"
18022 org-end-time-was-given
18023 (substring txt (match-end 0)))))
18024 (setq org-read-date-overlay
18025 (make-overlay (1- (point-at-eol)) (point-at-eol)))
18026 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
18028 (defun org-read-date-analyze (ans def defdecode)
18029 "Analyze the combined answer of the date prompt."
18030 ;; FIXME: cleanup and comment
18031 (let (delta deltan deltaw deltadef year month day
18032 hour minute second wday pm h2 m2 tl wday1)
18034 (when (setq delta (org-read-date-get-relative ans (current-time) def))
18035 (setq ans (replace-match "" t t ans)
18036 deltan (car delta)
18037 deltaw (nth 1 delta)
18038 deltadef (nth 2 delta)))
18040 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
18041 (when (string-match
18042 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
18043 (setq year (if (match-end 2)
18044 (string-to-number (match-string 2 ans))
18045 (string-to-number (format-time-string "%Y")))
18046 month (string-to-number (match-string 3 ans))
18047 day (string-to-number (match-string 4 ans)))
18048 (if (< year 100) (setq year (+ 2000 year)))
18049 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
18050 t nil ans)))
18051 ;; Help matching am/pm times, because `parse-time-string' does not do that.
18052 ;; If there is a time with am/pm, and *no* time without it, we convert
18053 ;; so that matching will be successful.
18054 (loop for i from 1 to 2 do ; twice, for end time as well
18055 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
18056 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
18057 (setq hour (string-to-number (match-string 1 ans))
18058 minute (if (match-end 3)
18059 (string-to-number (match-string 3 ans))
18061 pm (equal ?p
18062 (string-to-char (downcase (match-string 4 ans)))))
18063 (if (and (= hour 12) (not pm))
18064 (setq hour 0)
18065 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
18066 (setq ans (replace-match (format "%02d:%02d" hour minute)
18067 t t ans))))
18069 ;; Check if a time range is given as a duration
18070 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
18071 (setq hour (string-to-number (match-string 1 ans))
18072 h2 (+ hour (string-to-number (match-string 3 ans)))
18073 minute (string-to-number (match-string 2 ans))
18074 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
18075 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
18076 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
18078 ;; Check if there is a time range
18079 (when (boundp 'org-end-time-was-given)
18080 (setq org-time-was-given nil)
18081 (when (and (string-match org-plain-time-of-day-regexp ans)
18082 (match-end 8))
18083 (setq org-end-time-was-given (match-string 8 ans))
18084 (setq ans (concat (substring ans 0 (match-beginning 7))
18085 (substring ans (match-end 7))))))
18087 (setq tl (parse-time-string ans)
18088 day (or (nth 3 tl) (nth 3 defdecode))
18089 month (or (nth 4 tl)
18090 (if (and org-read-date-prefer-future
18091 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
18092 (1+ (nth 4 defdecode))
18093 (nth 4 defdecode)))
18094 year (or (nth 5 tl)
18095 (if (and org-read-date-prefer-future
18096 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18097 (1+ (nth 5 defdecode))
18098 (nth 5 defdecode)))
18099 hour (or (nth 2 tl) (nth 2 defdecode))
18100 minute (or (nth 1 tl) (nth 1 defdecode))
18101 second (or (nth 0 tl) 0)
18102 wday (nth 6 tl))
18103 (when deltan
18104 (unless deltadef
18105 (let ((now (decode-time (current-time))))
18106 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18107 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18108 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18109 ((equal deltaw "m") (setq month (+ month deltan)))
18110 ((equal deltaw "y") (setq year (+ year deltan)))))
18111 (when (and wday (not (nth 3 tl)))
18112 ;; Weekday was given, but no day, so pick that day in the week
18113 ;; on or after the derived date.
18114 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18115 (unless (equal wday wday1)
18116 (setq day (+ day (% (- wday wday1 -7) 7)))))
18117 (if (and (boundp 'org-time-was-given)
18118 (nth 2 tl))
18119 (setq org-time-was-given t))
18120 (if (< year 100) (setq year (+ 2000 year)))
18121 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18122 (list second minute hour day month year)))
18124 (defvar parse-time-weekdays)
18126 (defun org-read-date-get-relative (s today default)
18127 "Check string S for special relative date string.
18128 TODAY and DEFAULT are internal times, for today and for a default.
18129 Return shift list (N what def-flag)
18130 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18131 N is the number of WHATs to shift.
18132 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18133 the DEFAULT date rather than TODAY."
18134 (when (string-match
18135 (concat
18136 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18137 "\\([0-9]+\\)?"
18138 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18139 "\\([ \t]\\|$\\)") s)
18140 (let* ((dir (if (match-end 1)
18141 (string-to-char (substring (match-string 1 s) -1))
18142 ?+))
18143 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18144 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18145 (what (if (match-end 3) (match-string 3 s) "d"))
18146 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18147 (date (if rel default today))
18148 (wday (nth 6 (decode-time date)))
18149 delta)
18150 (if wday1
18151 (progn
18152 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18153 (if (= dir ?-) (setq delta (- delta 7)))
18154 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18155 (list delta "d" rel))
18156 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18158 (defun org-eval-in-calendar (form &optional keepdate)
18159 "Eval FORM in the calendar window and return to current window.
18160 Also, store the cursor date in variable org-ans2."
18161 (let ((sw (selected-window)))
18162 (select-window (get-buffer-window "*Calendar*"))
18163 (eval form)
18164 (when (and (not keepdate) (calendar-cursor-to-date))
18165 (let* ((date (calendar-cursor-to-date))
18166 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18167 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18168 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18169 (select-window sw)))
18171 ; ;; Update the prompt to show new default date
18172 ; (save-excursion
18173 ; (goto-char (point-min))
18174 ; (when (and org-ans2
18175 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18176 ; (get-text-property (match-end 0) 'field))
18177 ; (let ((inhibit-read-only t))
18178 ; (replace-match (concat "[" org-ans2 "]") t t)
18179 ; (add-text-properties (point-min) (1+ (match-end 0))
18180 ; (text-properties-at (1+ (point-min)))))))))
18182 (defun org-calendar-select ()
18183 "Return to `org-read-date' with the date currently selected.
18184 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18185 (interactive)
18186 (when (calendar-cursor-to-date)
18187 (let* ((date (calendar-cursor-to-date))
18188 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18189 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18190 (if (active-minibuffer-window) (exit-minibuffer))))
18192 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18193 "Insert a date stamp for the date given by the internal TIME.
18194 WITH-HM means, use the stamp format that includes the time of the day.
18195 INACTIVE means use square brackets instead of angular ones, so that the
18196 stamp will not contribute to the agenda.
18197 PRE and POST are optional strings to be inserted before and after the
18198 stamp.
18199 The command returns the inserted time stamp."
18200 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18201 stamp)
18202 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18203 (insert-before-markers (or pre ""))
18204 (insert-before-markers (setq stamp (format-time-string fmt time)))
18205 (when (listp extra)
18206 (setq extra (car extra))
18207 (if (and (stringp extra)
18208 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18209 (setq extra (format "-%02d:%02d"
18210 (string-to-number (match-string 1 extra))
18211 (string-to-number (match-string 2 extra))))
18212 (setq extra nil)))
18213 (when extra
18214 (backward-char 1)
18215 (insert-before-markers extra)
18216 (forward-char 1))
18217 (insert-before-markers (or post ""))
18218 stamp))
18220 (defun org-toggle-time-stamp-overlays ()
18221 "Toggle the use of custom time stamp formats."
18222 (interactive)
18223 (setq org-display-custom-times (not org-display-custom-times))
18224 (unless org-display-custom-times
18225 (let ((p (point-min)) (bmp (buffer-modified-p)))
18226 (while (setq p (next-single-property-change p 'display))
18227 (if (and (get-text-property p 'display)
18228 (eq (get-text-property p 'face) 'org-date))
18229 (remove-text-properties
18230 p (setq p (next-single-property-change p 'display))
18231 '(display t))))
18232 (set-buffer-modified-p bmp)))
18233 (if (featurep 'xemacs)
18234 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18235 (org-restart-font-lock)
18236 (setq org-table-may-need-update t)
18237 (if org-display-custom-times
18238 (message "Time stamps are overlayed with custom format")
18239 (message "Time stamp overlays removed")))
18241 (defun org-display-custom-time (beg end)
18242 "Overlay modified time stamp format over timestamp between BED and END."
18243 (let* ((ts (buffer-substring beg end))
18244 t1 w1 with-hm tf time str w2 (off 0))
18245 (save-match-data
18246 (setq t1 (org-parse-time-string ts t))
18247 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
18248 (setq off (- (match-end 0) (match-beginning 0)))))
18249 (setq end (- end off))
18250 (setq w1 (- end beg)
18251 with-hm (and (nth 1 t1) (nth 2 t1))
18252 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18253 time (org-fix-decoded-time t1)
18254 str (org-add-props
18255 (format-time-string
18256 (substring tf 1 -1) (apply 'encode-time time))
18257 nil 'mouse-face 'highlight)
18258 w2 (length str))
18259 (if (not (= w2 w1))
18260 (add-text-properties (1+ beg) (+ 2 beg)
18261 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18262 (if (featurep 'xemacs)
18263 (progn
18264 (put-text-property beg end 'invisible t)
18265 (put-text-property beg end 'end-glyph (make-glyph str)))
18266 (put-text-property beg end 'display str))))
18268 (defun org-translate-time (string)
18269 "Translate all timestamps in STRING to custom format.
18270 But do this only if the variable `org-display-custom-times' is set."
18271 (when org-display-custom-times
18272 (save-match-data
18273 (let* ((start 0)
18274 (re org-ts-regexp-both)
18275 t1 with-hm inactive tf time str beg end)
18276 (while (setq start (string-match re string start))
18277 (setq beg (match-beginning 0)
18278 end (match-end 0)
18279 t1 (save-match-data
18280 (org-parse-time-string (substring string beg end) t))
18281 with-hm (and (nth 1 t1) (nth 2 t1))
18282 inactive (equal (substring string beg (1+ beg)) "[")
18283 tf (funcall (if with-hm 'cdr 'car)
18284 org-time-stamp-custom-formats)
18285 time (org-fix-decoded-time t1)
18286 str (format-time-string
18287 (concat
18288 (if inactive "[" "<") (substring tf 1 -1)
18289 (if inactive "]" ">"))
18290 (apply 'encode-time time))
18291 string (replace-match str t t string)
18292 start (+ start (length str)))))))
18293 string)
18295 (defun org-fix-decoded-time (time)
18296 "Set 0 instead of nil for the first 6 elements of time.
18297 Don't touch the rest."
18298 (let ((n 0))
18299 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18301 (defun org-days-to-time (timestamp-string)
18302 "Difference between TIMESTAMP-STRING and now in days."
18303 (- (time-to-days (org-time-string-to-time timestamp-string))
18304 (time-to-days (current-time))))
18306 (defun org-deadline-close (timestamp-string &optional ndays)
18307 "Is the time in TIMESTAMP-STRING close to the current date?"
18308 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18309 (and (< (org-days-to-time timestamp-string) ndays)
18310 (not (org-entry-is-done-p))))
18312 (defun org-get-wdays (ts)
18313 "Get the deadline lead time appropriate for timestring TS."
18314 (cond
18315 ((<= org-deadline-warning-days 0)
18316 ;; 0 or negative, enforce this value no matter what
18317 (- org-deadline-warning-days))
18318 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18319 ;; lead time is specified.
18320 (floor (* (string-to-number (match-string 1 ts))
18321 (cdr (assoc (match-string 2 ts)
18322 '(("d" . 1) ("w" . 7)
18323 ("m" . 30.4) ("y" . 365.25)))))))
18324 ;; go for the default.
18325 (t org-deadline-warning-days)))
18327 (defun org-calendar-select-mouse (ev)
18328 "Return to `org-read-date' with the date currently selected.
18329 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18330 (interactive "e")
18331 (mouse-set-point ev)
18332 (when (calendar-cursor-to-date)
18333 (let* ((date (calendar-cursor-to-date))
18334 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18335 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18336 (if (active-minibuffer-window) (exit-minibuffer))))
18338 (defun org-check-deadlines (ndays)
18339 "Check if there are any deadlines due or past due.
18340 A deadline is considered due if it happens within `org-deadline-warning-days'
18341 days from today's date. If the deadline appears in an entry marked DONE,
18342 it is not shown. The prefix arg NDAYS can be used to test that many
18343 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18344 (interactive "P")
18345 (let* ((org-warn-days
18346 (cond
18347 ((equal ndays '(4)) 100000)
18348 (ndays (prefix-numeric-value ndays))
18349 (t (abs org-deadline-warning-days))))
18350 (case-fold-search nil)
18351 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18352 (callback
18353 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18355 (message "%d deadlines past-due or due within %d days"
18356 (org-occur regexp nil callback)
18357 org-warn-days)))
18359 (defun org-check-before-date (date)
18360 "Check if there are deadlines or scheduled entries before DATE."
18361 (interactive (list (org-read-date)))
18362 (let ((case-fold-search nil)
18363 (regexp (concat "\\<\\(" org-deadline-string
18364 "\\|" org-scheduled-string
18365 "\\) *<\\([^>]+\\)>"))
18366 (callback
18367 (lambda () (time-less-p
18368 (org-time-string-to-time (match-string 2))
18369 (org-time-string-to-time date)))))
18370 (message "%d entries before %s"
18371 (org-occur regexp nil callback) date)))
18373 (defun org-evaluate-time-range (&optional to-buffer)
18374 "Evaluate a time range by computing the difference between start and end.
18375 Normally the result is just printed in the echo area, but with prefix arg
18376 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18377 If the time range is actually in a table, the result is inserted into the
18378 next column.
18379 For time difference computation, a year is assumed to be exactly 365
18380 days in order to avoid rounding problems."
18381 (interactive "P")
18383 (org-clock-update-time-maybe)
18384 (save-excursion
18385 (unless (org-at-date-range-p t)
18386 (goto-char (point-at-bol))
18387 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18388 (if (not (org-at-date-range-p t))
18389 (error "Not at a time-stamp range, and none found in current line")))
18390 (let* ((ts1 (match-string 1))
18391 (ts2 (match-string 2))
18392 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18393 (match-end (match-end 0))
18394 (time1 (org-time-string-to-time ts1))
18395 (time2 (org-time-string-to-time ts2))
18396 (t1 (time-to-seconds time1))
18397 (t2 (time-to-seconds time2))
18398 (diff (abs (- t2 t1)))
18399 (negative (< (- t2 t1) 0))
18400 ;; (ys (floor (* 365 24 60 60)))
18401 (ds (* 24 60 60))
18402 (hs (* 60 60))
18403 (fy "%dy %dd %02d:%02d")
18404 (fy1 "%dy %dd")
18405 (fd "%dd %02d:%02d")
18406 (fd1 "%dd")
18407 (fh "%02d:%02d")
18408 y d h m align)
18409 (if havetime
18410 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18412 d (floor (/ diff ds)) diff (mod diff ds)
18413 h (floor (/ diff hs)) diff (mod diff hs)
18414 m (floor (/ diff 60)))
18415 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18417 d (floor (+ (/ diff ds) 0.5))
18418 h 0 m 0))
18419 (if (not to-buffer)
18420 (message "%s" (org-make-tdiff-string y d h m))
18421 (if (org-at-table-p)
18422 (progn
18423 (goto-char match-end)
18424 (setq align t)
18425 (and (looking-at " *|") (goto-char (match-end 0))))
18426 (goto-char match-end))
18427 (if (looking-at
18428 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18429 (replace-match ""))
18430 (if negative (insert " -"))
18431 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18432 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18433 (insert " " (format fh h m))))
18434 (if align (org-table-align))
18435 (message "Time difference inserted")))))
18437 (defun org-make-tdiff-string (y d h m)
18438 (let ((fmt "")
18439 (l nil))
18440 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18441 l (push y l)))
18442 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18443 l (push d l)))
18444 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18445 l (push h l)))
18446 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18447 l (push m l)))
18448 (apply 'format fmt (nreverse l))))
18450 (defun org-time-string-to-time (s)
18451 (apply 'encode-time (org-parse-time-string s)))
18453 (defun org-time-string-to-absolute (s &optional daynr prefer)
18454 "Convert a time stamp to an absolute day number.
18455 If there is a specifyer for a cyclic time stamp, get the closest date to
18456 DAYNR."
18457 (cond
18458 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18459 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18460 daynr
18461 (+ daynr 1000)))
18462 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18463 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18464 (time-to-days (current-time))) (match-string 0 s)
18465 prefer))
18466 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18468 (defun org-time-from-absolute (d)
18469 "Return the time corresponding to date D.
18470 D may be an absolute day number, or a calendar-type list (month day year)."
18471 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18472 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18474 (defun org-calendar-holiday ()
18475 "List of holidays, for Diary display in Org-mode."
18476 (require 'holidays)
18477 (let ((hl (funcall
18478 (if (fboundp 'calendar-check-holidays)
18479 'calendar-check-holidays 'check-calendar-holidays) date)))
18480 (if hl (mapconcat 'identity hl "; "))))
18482 (defun org-diary-sexp-entry (sexp entry date)
18483 "Process a SEXP diary ENTRY for DATE."
18484 (require 'diary-lib)
18485 (let ((result (if calendar-debug-sexp
18486 (let ((stack-trace-on-error t))
18487 (eval (car (read-from-string sexp))))
18488 (condition-case nil
18489 (eval (car (read-from-string sexp)))
18490 (error
18491 (beep)
18492 (message "Bad sexp at line %d in %s: %s"
18493 (org-current-line)
18494 (buffer-file-name) sexp)
18495 (sleep-for 2))))))
18496 (cond ((stringp result) result)
18497 ((and (consp result)
18498 (stringp (cdr result))) (cdr result))
18499 (result entry)
18500 (t nil))))
18502 (defun org-diary-to-ical-string (frombuf)
18503 "Get iCalendar entries from diary entries in buffer FROMBUF.
18504 This uses the icalendar.el library."
18505 (let* ((tmpdir (if (featurep 'xemacs)
18506 (temp-directory)
18507 temporary-file-directory))
18508 (tmpfile (make-temp-name
18509 (expand-file-name "orgics" tmpdir)))
18510 buf rtn b e)
18511 (save-excursion
18512 (set-buffer frombuf)
18513 (icalendar-export-region (point-min) (point-max) tmpfile)
18514 (setq buf (find-buffer-visiting tmpfile))
18515 (set-buffer buf)
18516 (goto-char (point-min))
18517 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18518 (setq b (match-beginning 0)))
18519 (goto-char (point-max))
18520 (if (re-search-backward "^END:VEVENT" nil t)
18521 (setq e (match-end 0)))
18522 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18523 (kill-buffer buf)
18524 (kill-buffer frombuf)
18525 (delete-file tmpfile)
18526 rtn))
18528 (defun org-closest-date (start current change prefer)
18529 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18530 When PREFER is `past' return a date that is either CURRENT or past.
18531 When PREFER is `future', return a date that is either CURRENT or future."
18532 ;; Make the proper lists from the dates
18533 (catch 'exit
18534 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18535 dn dw sday cday n1 n2
18536 d m y y1 y2 date1 date2 nmonths nm ny m2)
18538 (setq start (org-date-to-gregorian start)
18539 current (org-date-to-gregorian
18540 (if org-agenda-repeating-timestamp-show-all
18541 current
18542 (time-to-days (current-time))))
18543 sday (calendar-absolute-from-gregorian start)
18544 cday (calendar-absolute-from-gregorian current))
18546 (if (<= cday sday) (throw 'exit sday))
18548 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18549 (setq dn (string-to-number (match-string 1 change))
18550 dw (cdr (assoc (match-string 2 change) a1)))
18551 (error "Invalid change specifyer: %s" change))
18552 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18553 (cond
18554 ((eq dw 'day)
18555 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18556 n2 (+ n1 dn)))
18557 ((eq dw 'year)
18558 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18559 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18560 (setq date1 (list m d y1)
18561 n1 (calendar-absolute-from-gregorian date1)
18562 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18563 n2 (calendar-absolute-from-gregorian date2)))
18564 ((eq dw 'month)
18565 ;; approx number of month between the tow dates
18566 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18567 ;; How often does dn fit in there?
18568 (setq d (nth 1 start) m (car start) y (nth 2 start)
18569 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18570 m (+ m nm)
18571 ny (floor (/ m 12))
18572 y (+ y ny)
18573 m (- m (* ny 12)))
18574 (while (> m 12) (setq m (- m 12) y (1+ y)))
18575 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18576 (setq m2 (+ m dn) y2 y)
18577 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18578 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18579 (while (< n2 cday)
18580 (setq n1 n2 m m2 y y2)
18581 (setq m2 (+ m dn) y2 y)
18582 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18583 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18585 (if org-agenda-repeating-timestamp-show-all
18586 (cond
18587 ((eq prefer 'past) n1)
18588 ((eq prefer 'future) (if (= cday n1) n1 n2))
18589 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18590 (cond
18591 ((eq prefer 'past) n1)
18592 ((eq prefer 'future) (if (= cday n1) n1 n2))
18593 (t (if (= cday n1) n1 n2)))))))
18595 (defun org-date-to-gregorian (date)
18596 "Turn any specification of DATE into a gregorian date for the calendar."
18597 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18598 ((and (listp date) (= (length date) 3)) date)
18599 ((stringp date)
18600 (setq date (org-parse-time-string date))
18601 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18602 ((listp date)
18603 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18605 (defun org-parse-time-string (s &optional nodefault)
18606 "Parse the standard Org-mode time string.
18607 This should be a lot faster than the normal `parse-time-string'.
18608 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18609 hour and minute fields will be nil if not given."
18610 (if (string-match org-ts-regexp0 s)
18611 (list 0
18612 (if (or (match-beginning 8) (not nodefault))
18613 (string-to-number (or (match-string 8 s) "0")))
18614 (if (or (match-beginning 7) (not nodefault))
18615 (string-to-number (or (match-string 7 s) "0")))
18616 (string-to-number (match-string 4 s))
18617 (string-to-number (match-string 3 s))
18618 (string-to-number (match-string 2 s))
18619 nil nil nil)
18620 (make-list 9 0)))
18622 (defun org-timestamp-up (&optional arg)
18623 "Increase the date item at the cursor by one.
18624 If the cursor is on the year, change the year. If it is on the month or
18625 the day, change that.
18626 With prefix ARG, change by that many units."
18627 (interactive "p")
18628 (org-timestamp-change (prefix-numeric-value arg)))
18630 (defun org-timestamp-down (&optional arg)
18631 "Decrease the date item at the cursor by one.
18632 If the cursor is on the year, change the year. If it is on the month or
18633 the day, change that.
18634 With prefix ARG, change by that many units."
18635 (interactive "p")
18636 (org-timestamp-change (- (prefix-numeric-value arg))))
18638 (defun org-timestamp-up-day (&optional arg)
18639 "Increase the date in the time stamp by one day.
18640 With prefix ARG, change that many days."
18641 (interactive "p")
18642 (if (and (not (org-at-timestamp-p t))
18643 (org-on-heading-p))
18644 (org-todo 'up)
18645 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18647 (defun org-timestamp-down-day (&optional arg)
18648 "Decrease the date in the time stamp by one day.
18649 With prefix ARG, change that many days."
18650 (interactive "p")
18651 (if (and (not (org-at-timestamp-p t))
18652 (org-on-heading-p))
18653 (org-todo 'down)
18654 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18656 (defsubst org-pos-in-match-range (pos n)
18657 (and (match-beginning n)
18658 (<= (match-beginning n) pos)
18659 (>= (match-end n) pos)))
18661 (defun org-at-timestamp-p (&optional inactive-ok)
18662 "Determine if the cursor is in or at a timestamp."
18663 (interactive)
18664 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18665 (pos (point))
18666 (ans (or (looking-at tsr)
18667 (save-excursion
18668 (skip-chars-backward "^[<\n\r\t")
18669 (if (> (point) (point-min)) (backward-char 1))
18670 (and (looking-at tsr)
18671 (> (- (match-end 0) pos) -1))))))
18672 (and ans
18673 (boundp 'org-ts-what)
18674 (setq org-ts-what
18675 (cond
18676 ((= pos (match-beginning 0)) 'bracket)
18677 ((= pos (1- (match-end 0))) 'bracket)
18678 ((org-pos-in-match-range pos 2) 'year)
18679 ((org-pos-in-match-range pos 3) 'month)
18680 ((org-pos-in-match-range pos 7) 'hour)
18681 ((org-pos-in-match-range pos 8) 'minute)
18682 ((or (org-pos-in-match-range pos 4)
18683 (org-pos-in-match-range pos 5)) 'day)
18684 ((and (> pos (or (match-end 8) (match-end 5)))
18685 (< pos (match-end 0)))
18686 (- pos (or (match-end 8) (match-end 5))))
18687 (t 'day))))
18688 ans))
18690 (defun org-toggle-timestamp-type ()
18691 "Toggle the type (<active> or [inactive]) of a time stamp."
18692 (interactive)
18693 (when (org-at-timestamp-p t)
18694 (save-excursion
18695 (goto-char (match-beginning 0))
18696 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18697 (goto-char (1- (match-end 0)))
18698 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18699 (message "Timestamp is now %sactive"
18700 (if (equal (char-before) ?>) "in" ""))))
18702 (defun org-timestamp-change (n &optional what)
18703 "Change the date in the time stamp at point.
18704 The date will be changed by N times WHAT. WHAT can be `day', `month',
18705 `year', `minute', `second'. If WHAT is not given, the cursor position
18706 in the timestamp determines what will be changed."
18707 (let ((pos (point))
18708 with-hm inactive
18709 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18710 org-ts-what
18711 extra rem
18712 ts time time0)
18713 (if (not (org-at-timestamp-p t))
18714 (error "Not at a timestamp"))
18715 (if (and (not what) (eq org-ts-what 'bracket))
18716 (org-toggle-timestamp-type)
18717 (if (and (not what) (not (eq org-ts-what 'day))
18718 org-display-custom-times
18719 (get-text-property (point) 'display)
18720 (not (get-text-property (1- (point)) 'display)))
18721 (setq org-ts-what 'day))
18722 (setq org-ts-what (or what org-ts-what)
18723 inactive (= (char-after (match-beginning 0)) ?\[)
18724 ts (match-string 0))
18725 (replace-match "")
18726 (if (string-match
18727 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18729 (setq extra (match-string 1 ts)))
18730 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18731 (setq with-hm t))
18732 (setq time0 (org-parse-time-string ts))
18733 (when (and (eq org-ts-what 'minute)
18734 (eq current-prefix-arg nil))
18735 (setq n (* dm (org-no-warnings (signum n))))
18736 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18737 (setcar (cdr time0) (+ (nth 1 time0)
18738 (if (> n 0) (- rem) (- dm rem))))))
18739 (setq time
18740 (encode-time (or (car time0) 0)
18741 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18742 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18743 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18744 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18745 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18746 (nthcdr 6 time0)))
18747 (when (integerp org-ts-what)
18748 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18749 (if (eq what 'calendar)
18750 (let ((cal-date (org-get-date-from-calendar)))
18751 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18752 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18753 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18754 (setcar time0 (or (car time0) 0))
18755 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18756 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18757 (setq time (apply 'encode-time time0))))
18758 (setq org-last-changed-timestamp
18759 (org-insert-time-stamp time with-hm inactive nil nil extra))
18760 (org-clock-update-time-maybe)
18761 (goto-char pos)
18762 ;; Try to recenter the calendar window, if any
18763 (if (and org-calendar-follow-timestamp-change
18764 (get-buffer-window "*Calendar*" t)
18765 (memq org-ts-what '(day month year)))
18766 (org-recenter-calendar (time-to-days time))))))
18768 ;; FIXME: does not yet work for lead times
18769 (defun org-modify-ts-extra (s pos n dm)
18770 "Change the different parts of the lead-time and repeat fields in timestamp."
18771 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18772 ng h m new rem)
18773 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18774 (cond
18775 ((or (org-pos-in-match-range pos 2)
18776 (org-pos-in-match-range pos 3))
18777 (setq m (string-to-number (match-string 3 s))
18778 h (string-to-number (match-string 2 s)))
18779 (if (org-pos-in-match-range pos 2)
18780 (setq h (+ h n))
18781 (setq n (* dm (org-no-warnings (signum n))))
18782 (when (not (= 0 (setq rem (% m dm))))
18783 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18784 (setq m (+ m n)))
18785 (if (< m 0) (setq m (+ m 60) h (1- h)))
18786 (if (> m 59) (setq m (- m 60) h (1+ h)))
18787 (setq h (min 24 (max 0 h)))
18788 (setq ng 1 new (format "-%02d:%02d" h m)))
18789 ((org-pos-in-match-range pos 6)
18790 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18791 ((org-pos-in-match-range pos 5)
18792 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18794 ((org-pos-in-match-range pos 9)
18795 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18796 ((org-pos-in-match-range pos 8)
18797 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18799 (when ng
18800 (setq s (concat
18801 (substring s 0 (match-beginning ng))
18803 (substring s (match-end ng))))))
18806 (defun org-recenter-calendar (date)
18807 "If the calendar is visible, recenter it to DATE."
18808 (let* ((win (selected-window))
18809 (cwin (get-buffer-window "*Calendar*" t))
18810 (calendar-move-hook nil))
18811 (when cwin
18812 (select-window cwin)
18813 (calendar-goto-date (if (listp date) date
18814 (calendar-gregorian-from-absolute date)))
18815 (select-window win))))
18817 (defun org-goto-calendar (&optional arg)
18818 "Go to the Emacs calendar at the current date.
18819 If there is a time stamp in the current line, go to that date.
18820 A prefix ARG can be used to force the current date."
18821 (interactive "P")
18822 (let ((tsr org-ts-regexp) diff
18823 (calendar-move-hook nil)
18824 (view-calendar-holidays-initially nil)
18825 (view-diary-entries-initially nil))
18826 (if (or (org-at-timestamp-p)
18827 (save-excursion
18828 (beginning-of-line 1)
18829 (looking-at (concat ".*" tsr))))
18830 (let ((d1 (time-to-days (current-time)))
18831 (d2 (time-to-days
18832 (org-time-string-to-time (match-string 1)))))
18833 (setq diff (- d2 d1))))
18834 (calendar)
18835 (calendar-goto-today)
18836 (if (and diff (not arg)) (calendar-forward-day diff))))
18838 (defun org-get-date-from-calendar ()
18839 "Return a list (month day year) of date at point in calendar."
18840 (with-current-buffer "*Calendar*"
18841 (save-match-data
18842 (calendar-cursor-to-date))))
18844 (defun org-date-from-calendar ()
18845 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18846 If there is already a time stamp at the cursor position, update it."
18847 (interactive)
18848 (if (org-at-timestamp-p t)
18849 (org-timestamp-change 0 'calendar)
18850 (let ((cal-date (org-get-date-from-calendar)))
18851 (org-insert-time-stamp
18852 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18854 (defvar appt-time-msg-list)
18856 ;;;###autoload
18857 (defun org-agenda-to-appt (&optional refresh filter)
18858 "Activate appointments found in `org-agenda-files'.
18859 With a \\[universal-argument] prefix, refresh the list of
18860 appointements.
18862 If FILTER is t, interactively prompt the user for a regular
18863 expression, and filter out entries that don't match it.
18865 If FILTER is a string, use this string as a regular expression
18866 for filtering entries out.
18868 FILTER can also be an alist with the car of each cell being
18869 either 'headline or 'category. For example:
18871 '((headline \"IMPORTANT\")
18872 (category \"Work\"))
18874 will only add headlines containing IMPORTANT or headlines
18875 belonging to the \"Work\" category."
18876 (interactive "P")
18877 (require 'calendar)
18878 (if refresh (setq appt-time-msg-list nil))
18879 (if (eq filter t)
18880 (setq filter (read-from-minibuffer "Regexp filter: ")))
18881 (let* ((cnt 0) ; count added events
18882 (org-agenda-new-buffers nil)
18883 (org-deadline-warning-days 0)
18884 (today (org-date-to-gregorian
18885 (time-to-days (current-time))))
18886 (files (org-agenda-files)) entries file)
18887 ;; Get all entries which may contain an appt
18888 (while (setq file (pop files))
18889 (setq entries
18890 (append entries
18891 (org-agenda-get-day-entries
18892 file today :timestamp :scheduled :deadline))))
18893 (setq entries (delq nil entries))
18894 ;; Map thru entries and find if we should filter them out
18895 (mapc
18896 (lambda(x)
18897 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18898 (cat (get-text-property 1 'org-category x))
18899 (tod (get-text-property 1 'time-of-day x))
18900 (ok (or (null filter)
18901 (and (stringp filter) (string-match filter evt))
18902 (and (listp filter)
18903 (or (string-match
18904 (cadr (assoc 'category filter)) cat)
18905 (string-match
18906 (cadr (assoc 'headline filter)) evt))))))
18907 ;; FIXME: Shall we remove text-properties for the appt text?
18908 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18909 (when (and ok tod)
18910 (setq tod (number-to-string tod)
18911 tod (when (string-match
18912 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18913 (concat (match-string 1 tod) ":"
18914 (match-string 2 tod))))
18915 (appt-add tod evt)
18916 (setq cnt (1+ cnt))))) entries)
18917 (org-release-buffers org-agenda-new-buffers)
18918 (if (eq cnt 0)
18919 (message "No event to add")
18920 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18922 ;;; The clock for measuring work time.
18924 (defvar org-mode-line-string "")
18925 (put 'org-mode-line-string 'risky-local-variable t)
18927 (defvar org-mode-line-timer nil)
18928 (defvar org-clock-heading "")
18929 (defvar org-clock-start-time "")
18931 (defun org-update-mode-line ()
18932 (let* ((delta (- (time-to-seconds (current-time))
18933 (time-to-seconds org-clock-start-time)))
18934 (h (floor delta 3600))
18935 (m (floor (- delta (* 3600 h)) 60)))
18936 (setq org-mode-line-string
18937 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18938 'help-echo "Org-mode clock is running"))
18939 (force-mode-line-update)))
18941 (defvar org-clock-marker (make-marker)
18942 "Marker recording the last clock-in.")
18943 (defvar org-clock-mode-line-entry nil
18944 "Information for the modeline about the running clock.")
18946 (defun org-clock-in ()
18947 "Start the clock on the current item.
18948 If necessary, clock-out of the currently active clock."
18949 (interactive)
18950 (org-clock-out t)
18951 (let (ts)
18952 (save-excursion
18953 (org-back-to-heading t)
18954 (when (and org-clock-in-switch-to-state
18955 (not (looking-at (concat outline-regexp "[ \t]*"
18956 org-clock-in-switch-to-state
18957 "\\>"))))
18958 (org-todo org-clock-in-switch-to-state))
18959 (if (and org-clock-heading-function
18960 (functionp org-clock-heading-function))
18961 (setq org-clock-heading (funcall org-clock-heading-function))
18962 (if (looking-at org-complex-heading-regexp)
18963 (setq org-clock-heading (match-string 4))
18964 (setq org-clock-heading "???")))
18965 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18966 (org-clock-find-position)
18968 (insert "\n") (backward-char 1)
18969 (indent-relative)
18970 (insert org-clock-string " ")
18971 (setq org-clock-start-time (current-time))
18972 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18973 (move-marker org-clock-marker (point) (buffer-base-buffer))
18974 (or global-mode-string (setq global-mode-string '("")))
18975 (or (memq 'org-mode-line-string global-mode-string)
18976 (setq global-mode-string
18977 (append global-mode-string '(org-mode-line-string))))
18978 (org-update-mode-line)
18979 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18980 (message "Clock started at %s" ts))))
18982 (defun org-clock-find-position ()
18983 "Find the location where the next clock line should be inserted."
18984 (org-back-to-heading t)
18985 (catch 'exit
18986 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18987 (re (concat "^[ \t]*" org-clock-string))
18988 (cnt 0)
18989 first last)
18990 (goto-char beg)
18991 (when (eobp) (newline) (setq end (max (point) end)))
18992 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18993 ;; we seem to have a CLOCK drawer, so go there.
18994 (beginning-of-line 2)
18995 (throw 'exit t))
18996 ;; Lets count the CLOCK lines
18997 (goto-char beg)
18998 (while (re-search-forward re end t)
18999 (setq first (or first (match-beginning 0))
19000 last (match-beginning 0)
19001 cnt (1+ cnt)))
19002 (when (and (integerp org-clock-into-drawer)
19003 (>= (1+ cnt) org-clock-into-drawer))
19004 ;; Wrap current entries into a new drawer
19005 (goto-char last)
19006 (beginning-of-line 2)
19007 (if (org-at-item-p) (org-end-of-item))
19008 (insert ":END:\n")
19009 (beginning-of-line 0)
19010 (org-indent-line-function)
19011 (goto-char first)
19012 (insert ":CLOCK:\n")
19013 (beginning-of-line 0)
19014 (org-indent-line-function)
19015 (org-flag-drawer t)
19016 (beginning-of-line 2)
19017 (throw 'exit nil))
19019 (goto-char beg)
19020 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19021 (not (equal (match-string 1) org-clock-string)))
19022 ;; Planning info, skip to after it
19023 (beginning-of-line 2)
19024 (or (bolp) (newline)))
19025 (when (eq t org-clock-into-drawer)
19026 (insert ":CLOCK:\n:END:\n")
19027 (beginning-of-line -1)
19028 (org-indent-line-function)
19029 (org-flag-drawer t)
19030 (beginning-of-line 2)
19031 (org-indent-line-function)))))
19033 (defun org-clock-out (&optional fail-quietly)
19034 "Stop the currently running clock.
19035 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
19036 (interactive)
19037 (catch 'exit
19038 (if (not (marker-buffer org-clock-marker))
19039 (if fail-quietly (throw 'exit t) (error "No active clock")))
19040 (let (ts te s h m)
19041 (save-excursion
19042 (set-buffer (marker-buffer org-clock-marker))
19043 (goto-char org-clock-marker)
19044 (beginning-of-line 1)
19045 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19046 (equal (match-string 1) org-clock-string))
19047 (setq ts (match-string 2))
19048 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
19049 (goto-char (match-end 0))
19050 (delete-region (point) (point-at-eol))
19051 (insert "--")
19052 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
19053 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
19054 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
19055 h (floor (/ s 3600))
19056 s (- s (* 3600 h))
19057 m (floor (/ s 60))
19058 s (- s (* 60 s)))
19059 (insert " => " (format "%2d:%02d" h m))
19060 (move-marker org-clock-marker nil)
19061 (when org-log-note-clock-out
19062 (org-add-log-maybe 'clock-out))
19063 (when org-mode-line-timer
19064 (cancel-timer org-mode-line-timer)
19065 (setq org-mode-line-timer nil))
19066 (setq global-mode-string
19067 (delq 'org-mode-line-string global-mode-string))
19068 (force-mode-line-update)
19069 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
19071 (defun org-clock-cancel ()
19072 "Cancel the running clock be removing the start timestamp."
19073 (interactive)
19074 (if (not (marker-buffer org-clock-marker))
19075 (error "No active clock"))
19076 (save-excursion
19077 (set-buffer (marker-buffer org-clock-marker))
19078 (goto-char org-clock-marker)
19079 (delete-region (1- (point-at-bol)) (point-at-eol)))
19080 (setq global-mode-string
19081 (delq 'org-mode-line-string global-mode-string))
19082 (force-mode-line-update)
19083 (message "Clock canceled"))
19085 (defun org-clock-goto (&optional delete-windows)
19086 "Go to the currently clocked-in entry."
19087 (interactive "P")
19088 (if (not (marker-buffer org-clock-marker))
19089 (error "No active clock"))
19090 (switch-to-buffer-other-window
19091 (marker-buffer org-clock-marker))
19092 (if delete-windows (delete-other-windows))
19093 (goto-char org-clock-marker)
19094 (org-show-entry)
19095 (org-back-to-heading)
19096 (recenter))
19098 (defvar org-clock-file-total-minutes nil
19099 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
19100 (make-variable-buffer-local 'org-clock-file-total-minutes)
19102 (defun org-clock-sum (&optional tstart tend)
19103 "Sum the times for each subtree.
19104 Puts the resulting times in minutes as a text property on each headline."
19105 (interactive)
19106 (let* ((bmp (buffer-modified-p))
19107 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19108 org-clock-string
19109 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19110 (lmax 30)
19111 (ltimes (make-vector lmax 0))
19112 (t1 0)
19113 (level 0)
19114 ts te dt
19115 time)
19116 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19117 (save-excursion
19118 (goto-char (point-max))
19119 (while (re-search-backward re nil t)
19120 (cond
19121 ((match-end 2)
19122 ;; Two time stamps
19123 (setq ts (match-string 2)
19124 te (match-string 3)
19125 ts (time-to-seconds
19126 (apply 'encode-time (org-parse-time-string ts)))
19127 te (time-to-seconds
19128 (apply 'encode-time (org-parse-time-string te)))
19129 ts (if tstart (max ts tstart) ts)
19130 te (if tend (min te tend) te)
19131 dt (- te ts)
19132 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19133 ((match-end 4)
19134 ;; A naket time
19135 (setq t1 (+ t1 (string-to-number (match-string 5))
19136 (* 60 (string-to-number (match-string 4))))))
19137 (t ;; A headline
19138 (setq level (- (match-end 1) (match-beginning 1)))
19139 (when (or (> t1 0) (> (aref ltimes level) 0))
19140 (loop for l from 0 to level do
19141 (aset ltimes l (+ (aref ltimes l) t1)))
19142 (setq t1 0 time (aref ltimes level))
19143 (loop for l from level to (1- lmax) do
19144 (aset ltimes l 0))
19145 (goto-char (match-beginning 0))
19146 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19147 (setq org-clock-file-total-minutes (aref ltimes 0)))
19148 (set-buffer-modified-p bmp)))
19150 (defun org-clock-display (&optional total-only)
19151 "Show subtree times in the entire buffer.
19152 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19153 in the echo area."
19154 (interactive)
19155 (org-remove-clock-overlays)
19156 (let (time h m p)
19157 (org-clock-sum)
19158 (unless total-only
19159 (save-excursion
19160 (goto-char (point-min))
19161 (while (or (and (equal (setq p (point)) (point-min))
19162 (get-text-property p :org-clock-minutes))
19163 (setq p (next-single-property-change
19164 (point) :org-clock-minutes)))
19165 (goto-char p)
19166 (when (setq time (get-text-property p :org-clock-minutes))
19167 (org-put-clock-overlay time (funcall outline-level))))
19168 (setq h (/ org-clock-file-total-minutes 60)
19169 m (- org-clock-file-total-minutes (* 60 h)))
19170 ;; Arrange to remove the overlays upon next change.
19171 (when org-remove-highlights-with-change
19172 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19173 nil 'local))))
19174 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19176 (defvar org-clock-overlays nil)
19177 (make-variable-buffer-local 'org-clock-overlays)
19179 (defun org-put-clock-overlay (time &optional level)
19180 "Put an overlays on the current line, displaying TIME.
19181 If LEVEL is given, prefix time with a corresponding number of stars.
19182 This creates a new overlay and stores it in `org-clock-overlays', so that it
19183 will be easy to remove."
19184 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19185 (l (if level (org-get-valid-level level 0) 0))
19186 (off 0)
19187 ov tx)
19188 (move-to-column c)
19189 (unless (eolp) (skip-chars-backward "^ \t"))
19190 (skip-chars-backward " \t")
19191 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19192 tx (concat (buffer-substring (1- (point)) (point))
19193 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19194 (org-add-props (format "%s %2d:%02d%s"
19195 (make-string l ?*) h m
19196 (make-string (- 16 l) ?\ ))
19197 '(face secondary-selection))
19198 ""))
19199 (if (not (featurep 'xemacs))
19200 (org-overlay-put ov 'display tx)
19201 (org-overlay-put ov 'invisible t)
19202 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19203 (push ov org-clock-overlays)))
19205 (defun org-remove-clock-overlays (&optional beg end noremove)
19206 "Remove the occur highlights from the buffer.
19207 BEG and END are ignored. If NOREMOVE is nil, remove this function
19208 from the `before-change-functions' in the current buffer."
19209 (interactive)
19210 (unless org-inhibit-highlight-removal
19211 (mapc 'org-delete-overlay org-clock-overlays)
19212 (setq org-clock-overlays nil)
19213 (unless noremove
19214 (remove-hook 'before-change-functions
19215 'org-remove-clock-overlays 'local))))
19217 (defun org-clock-out-if-current ()
19218 "Clock out if the current entry contains the running clock.
19219 This is used to stop the clock after a TODO entry is marked DONE,
19220 and is only done if the variable `org-clock-out-when-done' is not nil."
19221 (when (and org-clock-out-when-done
19222 (member state org-done-keywords)
19223 (equal (marker-buffer org-clock-marker) (current-buffer))
19224 (< (point) org-clock-marker)
19225 (> (save-excursion (outline-next-heading) (point))
19226 org-clock-marker))
19227 ;; Clock out, but don't accept a logging message for this.
19228 (let ((org-log-note-clock-out nil))
19229 (org-clock-out))))
19231 (add-hook 'org-after-todo-state-change-hook
19232 'org-clock-out-if-current)
19234 (defun org-check-running-clock ()
19235 "Check if the current buffer contains the running clock.
19236 If yes, offer to stop it and to save the buffer with the changes."
19237 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19238 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19239 (buffer-name))))
19240 (org-clock-out)
19241 (when (y-or-n-p "Save changed buffer?")
19242 (save-buffer))))
19244 (defun org-clock-report (&optional arg)
19245 "Create a table containing a report about clocked time.
19246 If the cursor is inside an existing clocktable block, then the table
19247 will be updated. If not, a new clocktable will be inserted.
19248 When called with a prefix argument, move to the first clock table in the
19249 buffer and update it."
19250 (interactive "P")
19251 (org-remove-clock-overlays)
19252 (when arg
19253 (org-find-dblock "clocktable")
19254 (org-show-entry))
19255 (if (org-in-clocktable-p)
19256 (goto-char (org-in-clocktable-p))
19257 (org-create-dblock (list :name "clocktable"
19258 :maxlevel 2 :scope 'file)))
19259 (org-update-dblock))
19261 (defun org-in-clocktable-p ()
19262 "Check if the cursor is in a clocktable."
19263 (let ((pos (point)) start)
19264 (save-excursion
19265 (end-of-line 1)
19266 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19267 (setq start (match-beginning 0))
19268 (re-search-forward "^#\\+END:.*" nil t)
19269 (>= (match-end 0) pos)
19270 start))))
19272 (defun org-clock-update-time-maybe ()
19273 "If this is a CLOCK line, update it and return t.
19274 Otherwise, return nil."
19275 (interactive)
19276 (save-excursion
19277 (beginning-of-line 1)
19278 (skip-chars-forward " \t")
19279 (when (looking-at org-clock-string)
19280 (let ((re (concat "[ \t]*" org-clock-string
19281 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19282 "\\([ \t]*=>.*\\)?"))
19283 ts te h m s)
19284 (if (not (looking-at re))
19286 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19287 (end-of-line 1)
19288 (setq ts (match-string 1)
19289 te (match-string 2))
19290 (setq s (- (time-to-seconds
19291 (apply 'encode-time (org-parse-time-string te)))
19292 (time-to-seconds
19293 (apply 'encode-time (org-parse-time-string ts))))
19294 h (floor (/ s 3600))
19295 s (- s (* 3600 h))
19296 m (floor (/ s 60))
19297 s (- s (* 60 s)))
19298 (insert " => " (format "%2d:%02d" h m))
19299 t)))))
19301 (defun org-clock-special-range (key &optional time as-strings)
19302 "Return two times bordering a special time range.
19303 Key is a symbol specifying the range and can be one of `today', `yesterday',
19304 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19305 A week starts Monday 0:00 and ends Sunday 24:00.
19306 The range is determined relative to TIME. TIME defaults to the current time.
19307 The return value is a cons cell with two internal times like the ones
19308 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19309 the returned times will be formatted strings."
19310 (let* ((tm (decode-time (or time (current-time))))
19311 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19312 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19313 (dow (nth 6 tm))
19314 s1 m1 h1 d1 month1 y1 diff ts te fm)
19315 (cond
19316 ((eq key 'today)
19317 (setq h 0 m 0 h1 24 m1 0))
19318 ((eq key 'yesterday)
19319 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19320 ((eq key 'thisweek)
19321 (setq diff (if (= dow 0) 6 (1- dow))
19322 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19323 ((eq key 'lastweek)
19324 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19325 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19326 ((eq key 'thismonth)
19327 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19328 ((eq key 'lastmonth)
19329 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19330 ((eq key 'thisyear)
19331 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19332 ((eq key 'lastyear)
19333 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19334 (t (error "No such time block %s" key)))
19335 (setq ts (encode-time s m h d month y)
19336 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19337 (or d1 d) (or month1 month) (or y1 y)))
19338 (setq fm (cdr org-time-stamp-formats))
19339 (if as-strings
19340 (cons (format-time-string fm ts) (format-time-string fm te))
19341 (cons ts te))))
19343 (defun org-dblock-write:clocktable (params)
19344 "Write the standard clocktable."
19345 (catch 'exit
19346 (let* ((hlchars '((1 . "*") (2 . "/")))
19347 (ins (make-marker))
19348 (total-time nil)
19349 (scope (plist-get params :scope))
19350 (tostring (plist-get params :tostring))
19351 (multifile (plist-get params :multifile))
19352 (header (plist-get params :header))
19353 (maxlevel (or (plist-get params :maxlevel) 3))
19354 (step (plist-get params :step))
19355 (emph (plist-get params :emphasize))
19356 (ts (plist-get params :tstart))
19357 (te (plist-get params :tend))
19358 (block (plist-get params :block))
19359 (link (plist-get params :link))
19360 ipos time h m p level hlc hdl
19361 cc beg end pos tbl)
19362 (when step
19363 (org-clocktable-steps params)
19364 (throw 'exit nil))
19365 (when block
19366 (setq cc (org-clock-special-range block nil t)
19367 ts (car cc) te (cdr cc)))
19368 (if ts (setq ts (time-to-seconds
19369 (apply 'encode-time (org-parse-time-string ts)))))
19370 (if te (setq te (time-to-seconds
19371 (apply 'encode-time (org-parse-time-string te)))))
19372 (move-marker ins (point))
19373 (setq ipos (point))
19375 ;; Get the right scope
19376 (setq pos (point))
19377 (save-restriction
19378 (cond
19379 ((not scope))
19380 ((eq scope 'file) (widen))
19381 ((eq scope 'subtree) (org-narrow-to-subtree))
19382 ((eq scope 'tree)
19383 (while (org-up-heading-safe))
19384 (org-narrow-to-subtree))
19385 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19386 (symbol-name scope)))
19387 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19388 (catch 'exit
19389 (while (org-up-heading-safe)
19390 (looking-at outline-regexp)
19391 (if (<= (org-reduced-level (funcall outline-level)) level)
19392 (throw 'exit nil))))
19393 (org-narrow-to-subtree))
19394 ((or (listp scope) (eq scope 'agenda))
19395 (let* ((files (if (listp scope) scope (org-agenda-files)))
19396 (scope 'agenda)
19397 (p1 (copy-sequence params))
19398 file)
19399 (plist-put p1 :tostring t)
19400 (plist-put p1 :multifile t)
19401 (plist-put p1 :scope 'file)
19402 (org-prepare-agenda-buffers files)
19403 (while (setq file (pop files))
19404 (with-current-buffer (find-buffer-visiting file)
19405 (push (org-clocktable-add-file
19406 file (org-dblock-write:clocktable p1)) tbl)
19407 (setq total-time (+ (or total-time 0)
19408 org-clock-file-total-minutes)))))))
19409 (goto-char pos)
19411 (unless (eq scope 'agenda)
19412 (org-clock-sum ts te)
19413 (goto-char (point-min))
19414 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19415 (goto-char p)
19416 (when (setq time (get-text-property p :org-clock-minutes))
19417 (save-excursion
19418 (beginning-of-line 1)
19419 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19420 (setq level (org-reduced-level
19421 (- (match-end 1) (match-beginning 1))))
19422 (<= level maxlevel))
19423 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19424 hdl (if (not link)
19425 (match-string 2)
19426 (org-make-link-string
19427 (format "file:%s::%s"
19428 (buffer-file-name)
19429 (save-match-data
19430 (org-make-org-heading-search-string
19431 (match-string 2))))
19432 (match-string 2)))
19433 h (/ time 60)
19434 m (- time (* 60 h)))
19435 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19436 (push (concat
19437 "| " (int-to-string level) "|" hlc hdl hlc " |"
19438 (make-string (1- level) ?|)
19439 hlc (format "%d:%02d" h m) hlc
19440 " |") tbl))))))
19441 (setq tbl (nreverse tbl))
19442 (if tostring
19443 (if tbl (mapconcat 'identity tbl "\n") nil)
19444 (goto-char ins)
19445 (insert-before-markers
19446 (or header
19447 (concat
19448 "Clock summary at ["
19449 (substring
19450 (format-time-string (cdr org-time-stamp-formats))
19451 1 -1)
19452 "]."
19453 (if block
19454 (format " Considered range is /%s/." block)
19456 "\n\n"))
19457 (if (eq scope 'agenda) "|File" "")
19458 "|L|Headline|Time|\n")
19459 (setq total-time (or total-time org-clock-file-total-minutes)
19460 h (/ total-time 60)
19461 m (- total-time (* 60 h)))
19462 (insert-before-markers
19463 "|-\n|"
19464 (if (eq scope 'agenda) "|" "")
19466 "*Total time*| "
19467 (format "*%d:%02d*" h m)
19468 "|\n|-\n")
19469 (setq tbl (delq nil tbl))
19470 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19471 (equal (substring (car tbl) 0 2) "|-"))
19472 (pop tbl))
19473 (insert-before-markers (mapconcat
19474 'identity (delq nil tbl)
19475 (if (eq scope 'agenda) "\n|-\n" "\n")))
19476 (backward-delete-char 1)
19477 (goto-char ipos)
19478 (skip-chars-forward "^|")
19479 (org-table-align))))))
19481 (defun org-clocktable-steps (params)
19482 (let* ((p1 (copy-sequence params))
19483 (ts (plist-get p1 :tstart))
19484 (te (plist-get p1 :tend))
19485 (step0 (plist-get p1 :step))
19486 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19487 (block (plist-get p1 :block))
19489 (when block
19490 (setq cc (org-clock-special-range block nil t)
19491 ts (car cc) te (cdr cc)))
19492 (if ts (setq ts (time-to-seconds
19493 (apply 'encode-time (org-parse-time-string ts)))))
19494 (if te (setq te (time-to-seconds
19495 (apply 'encode-time (org-parse-time-string te)))))
19496 (plist-put p1 :header "")
19497 (plist-put p1 :step nil)
19498 (plist-put p1 :block nil)
19499 (while (< ts te)
19500 (or (bolp) (insert "\n"))
19501 (plist-put p1 :tstart (format-time-string
19502 (car org-time-stamp-formats)
19503 (seconds-to-time ts)))
19504 (plist-put p1 :tend (format-time-string
19505 (car org-time-stamp-formats)
19506 (seconds-to-time (setq ts (+ ts step)))))
19507 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19508 (plist-get p1 :tstart) "\n")
19509 (org-dblock-write:clocktable p1)
19510 (re-search-forward "#\\+END:")
19511 (end-of-line 0))))
19514 (defun org-clocktable-add-file (file table)
19515 (if table
19516 (let ((lines (org-split-string table "\n"))
19517 (ff (file-name-nondirectory file)))
19518 (mapconcat 'identity
19519 (mapcar (lambda (x)
19520 (if (string-match org-table-dataline-regexp x)
19521 (concat "|" ff x)
19523 lines)
19524 "\n"))))
19526 ;; FIXME: I don't think anybody uses this, ask David
19527 (defun org-collect-clock-time-entries ()
19528 "Return an internal list with clocking information.
19529 This list has one entry for each CLOCK interval.
19530 FIXME: describe the elements."
19531 (interactive)
19532 (let ((re (concat "^[ \t]*" org-clock-string
19533 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19534 rtn beg end next cont level title total closedp leafp
19535 clockpos titlepos h m donep)
19536 (save-excursion
19537 (org-clock-sum)
19538 (goto-char (point-min))
19539 (while (re-search-forward re nil t)
19540 (setq clockpos (match-beginning 0)
19541 beg (match-string 1) end (match-string 2)
19542 cont (match-end 0))
19543 (setq beg (apply 'encode-time (org-parse-time-string beg))
19544 end (apply 'encode-time (org-parse-time-string end)))
19545 (org-back-to-heading t)
19546 (setq donep (org-entry-is-done-p))
19547 (setq titlepos (point)
19548 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19549 h (/ total 60) m (- total (* 60 h))
19550 total (cons h m))
19551 (looking-at "\\(\\*+\\) +\\(.*\\)")
19552 (setq level (- (match-end 1) (match-beginning 1))
19553 title (org-match-string-no-properties 2))
19554 (save-excursion (outline-next-heading) (setq next (point)))
19555 (setq closedp (re-search-forward org-closed-time-regexp next t))
19556 (goto-char next)
19557 (setq leafp (and (looking-at "^\\*+ ")
19558 (<= (- (match-end 0) (point)) level)))
19559 (push (list beg end clockpos closedp donep
19560 total title titlepos level leafp)
19561 rtn)
19562 (goto-char cont)))
19563 (nreverse rtn)))
19565 ;;;; Agenda, and Diary Integration
19567 ;;; Define the Org-agenda-mode
19569 (defvar org-agenda-mode-map (make-sparse-keymap)
19570 "Keymap for `org-agenda-mode'.")
19572 (defvar org-agenda-menu) ; defined later in this file.
19573 (defvar org-agenda-follow-mode nil)
19574 (defvar org-agenda-show-log nil)
19575 (defvar org-agenda-redo-command nil)
19576 (defvar org-agenda-query-string nil)
19577 (defvar org-agenda-mode-hook nil)
19578 (defvar org-agenda-type nil)
19579 (defvar org-agenda-force-single-file nil)
19581 (defun org-agenda-mode ()
19582 "Mode for time-sorted view on action items in Org-mode files.
19584 The following commands are available:
19586 \\{org-agenda-mode-map}"
19587 (interactive)
19588 (kill-all-local-variables)
19589 (setq org-agenda-undo-list nil
19590 org-agenda-pending-undo-list nil)
19591 (setq major-mode 'org-agenda-mode)
19592 ;; Keep global-font-lock-mode from turning on font-lock-mode
19593 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19594 (setq mode-name "Org-Agenda")
19595 (use-local-map org-agenda-mode-map)
19596 (easy-menu-add org-agenda-menu)
19597 (if org-startup-truncated (setq truncate-lines t))
19598 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19599 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19600 ;; Make sure properties are removed when copying text
19601 (when (boundp 'buffer-substring-filters)
19602 (org-set-local 'buffer-substring-filters
19603 (cons (lambda (x)
19604 (set-text-properties 0 (length x) nil x) x)
19605 buffer-substring-filters)))
19606 (unless org-agenda-keep-modes
19607 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19608 org-agenda-show-log nil))
19609 (easy-menu-change
19610 '("Agenda") "Agenda Files"
19611 (append
19612 (list
19613 (vector
19614 (if (get 'org-agenda-files 'org-restrict)
19615 "Restricted to single file"
19616 "Edit File List")
19617 '(org-edit-agenda-file-list)
19618 (not (get 'org-agenda-files 'org-restrict)))
19619 "--")
19620 (mapcar 'org-file-menu-entry (org-agenda-files))))
19621 (org-agenda-set-mode-name)
19622 (apply
19623 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19624 (list 'org-agenda-mode-hook)))
19626 (substitute-key-definition 'undo 'org-agenda-undo
19627 org-agenda-mode-map global-map)
19628 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19629 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19630 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19631 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19632 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19633 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19634 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19635 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19636 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19637 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19638 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19639 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19640 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19641 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19642 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19643 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19644 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19645 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19646 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19647 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19648 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19649 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19650 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19651 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19652 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19653 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19654 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19655 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19656 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19658 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19659 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19660 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19661 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19662 (while l (org-defkey org-agenda-mode-map
19663 (int-to-string (pop l)) 'digit-argument)))
19665 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19666 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19667 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19668 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19669 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19670 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19671 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19672 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19673 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19674 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19675 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19676 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19677 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19678 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19679 (org-defkey org-agenda-mode-map "n" 'next-line)
19680 (org-defkey org-agenda-mode-map "p" 'previous-line)
19681 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19682 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19683 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19684 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19685 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19686 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19687 (eval-after-load "calendar"
19688 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19689 'org-calendar-goto-agenda))
19690 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19691 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19692 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19693 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19694 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19695 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19696 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19697 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19698 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19699 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19700 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19701 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19702 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19703 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19704 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19705 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19706 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19707 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19708 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19709 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19710 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19711 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19713 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19714 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19715 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19716 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19718 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19719 "Local keymap for agenda entries from Org-mode.")
19721 (org-defkey org-agenda-keymap
19722 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19723 (org-defkey org-agenda-keymap
19724 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19725 (when org-agenda-mouse-1-follows-link
19726 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19727 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19728 '("Agenda"
19729 ("Agenda Files")
19730 "--"
19731 ["Show" org-agenda-show t]
19732 ["Go To (other window)" org-agenda-goto t]
19733 ["Go To (this window)" org-agenda-switch-to t]
19734 ["Follow Mode" org-agenda-follow-mode
19735 :style toggle :selected org-agenda-follow-mode :active t]
19736 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19737 "--"
19738 ["Cycle TODO" org-agenda-todo t]
19739 ["Archive subtree" org-agenda-archive t]
19740 ["Delete subtree" org-agenda-kill t]
19741 "--"
19742 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19743 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19744 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19745 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19746 "--"
19747 ("Tags and Properties"
19748 ["Show all Tags" org-agenda-show-tags t]
19749 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19750 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19751 "--"
19752 ["Column View" org-columns t])
19753 ("Date/Schedule"
19754 ["Schedule" org-agenda-schedule t]
19755 ["Set Deadline" org-agenda-deadline t]
19756 "--"
19757 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19758 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19759 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19760 ("Clock"
19761 ["Clock in" org-agenda-clock-in t]
19762 ["Clock out" org-agenda-clock-out t]
19763 ["Clock cancel" org-agenda-clock-cancel t]
19764 ["Goto running clock" org-clock-goto t])
19765 ("Priority"
19766 ["Set Priority" org-agenda-priority t]
19767 ["Increase Priority" org-agenda-priority-up t]
19768 ["Decrease Priority" org-agenda-priority-down t]
19769 ["Show Priority" org-agenda-show-priority t])
19770 ("Calendar/Diary"
19771 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19772 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19773 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19774 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19775 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19776 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19777 "--"
19778 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19779 "--"
19780 ("View"
19781 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19782 :style radio :selected (equal org-agenda-ndays 1)]
19783 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19784 :style radio :selected (equal org-agenda-ndays 7)]
19785 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19786 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19787 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19788 :style radio :selected (member org-agenda-ndays '(365 366))]
19789 "--"
19790 ["Show Logbook entries" org-agenda-log-mode
19791 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19792 ["Include Diary" org-agenda-toggle-diary
19793 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19794 ["Use Time Grid" org-agenda-toggle-time-grid
19795 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19796 ["Write view to file" org-write-agenda t]
19797 ["Rebuild buffer" org-agenda-redo t]
19798 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19799 "--"
19800 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19801 "--"
19802 ["Quit" org-agenda-quit t]
19803 ["Exit and Release Buffers" org-agenda-exit t]
19806 ;;; Agenda undo
19808 (defvar org-agenda-allow-remote-undo t
19809 "Non-nil means, allow remote undo from the agenda buffer.")
19810 (defvar org-agenda-undo-list nil
19811 "List of undoable operations in the agenda since last refresh.")
19812 (defvar org-agenda-undo-has-started-in nil
19813 "Buffers that have already seen `undo-start' in the current undo sequence.")
19814 (defvar org-agenda-pending-undo-list nil
19815 "In a series of undo commands, this is the list of remaning undo items.")
19817 (defmacro org-if-unprotected (&rest body)
19818 "Execute BODY if there is no `org-protected' text property at point."
19819 (declare (debug t))
19820 `(unless (get-text-property (point) 'org-protected)
19821 ,@body))
19823 (defmacro org-with-remote-undo (_buffer &rest _body)
19824 "Execute BODY while recording undo information in two buffers."
19825 (declare (indent 1) (debug t))
19826 `(let ((_cline (org-current-line))
19827 (_cmd this-command)
19828 (_buf1 (current-buffer))
19829 (_buf2 ,_buffer)
19830 (_undo1 buffer-undo-list)
19831 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19832 _c1 _c2)
19833 ,@_body
19834 (when org-agenda-allow-remote-undo
19835 (setq _c1 (org-verify-change-for-undo
19836 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19837 _c2 (org-verify-change-for-undo
19838 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19839 (when (or _c1 _c2)
19840 ;; make sure there are undo boundaries
19841 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19842 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19843 ;; remember which buffer to undo
19844 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19845 org-agenda-undo-list)))))
19847 (defun org-agenda-undo ()
19848 "Undo a remote editing step in the agenda.
19849 This undoes changes both in the agenda buffer and in the remote buffer
19850 that have been changed along."
19851 (interactive)
19852 (or org-agenda-allow-remote-undo
19853 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19854 (if (not (eq this-command last-command))
19855 (setq org-agenda-undo-has-started-in nil
19856 org-agenda-pending-undo-list org-agenda-undo-list))
19857 (if (not org-agenda-pending-undo-list)
19858 (error "No further undo information"))
19859 (let* ((entry (pop org-agenda-pending-undo-list))
19860 buf line cmd rembuf)
19861 (setq cmd (pop entry) line (pop entry))
19862 (setq rembuf (nth 2 entry))
19863 (org-with-remote-undo rembuf
19864 (while (bufferp (setq buf (pop entry)))
19865 (if (pop entry)
19866 (with-current-buffer buf
19867 (let ((last-undo-buffer buf)
19868 (inhibit-read-only t))
19869 (unless (memq buf org-agenda-undo-has-started-in)
19870 (push buf org-agenda-undo-has-started-in)
19871 (make-local-variable 'pending-undo-list)
19872 (undo-start))
19873 (while (and pending-undo-list
19874 (listp pending-undo-list)
19875 (not (car pending-undo-list)))
19876 (pop pending-undo-list))
19877 (undo-more 1))))))
19878 (goto-line line)
19879 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19881 (defun org-verify-change-for-undo (l1 l2)
19882 "Verify that a real change occurred between the undo lists L1 and L2."
19883 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19884 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19885 (not (eq l1 l2)))
19887 ;;; Agenda dispatch
19889 (defvar org-agenda-restrict nil)
19890 (defvar org-agenda-restrict-begin (make-marker))
19891 (defvar org-agenda-restrict-end (make-marker))
19892 (defvar org-agenda-last-dispatch-buffer nil)
19893 (defvar org-agenda-overriding-restriction nil)
19895 ;;;###autoload
19896 (defun org-agenda (arg &optional keys restriction)
19897 "Dispatch agenda commands to collect entries to the agenda buffer.
19898 Prompts for a command to execute. Any prefix arg will be passed
19899 on to the selected command. The default selections are:
19901 a Call `org-agenda-list' to display the agenda for current day or week.
19902 t Call `org-todo-list' to display the global todo list.
19903 T Call `org-todo-list' to display the global todo list, select only
19904 entries with a specific TODO keyword (the user gets a prompt).
19905 m Call `org-tags-view' to display headlines with tags matching
19906 a condition (the user is prompted for the condition).
19907 M Like `m', but select only TODO entries, no ordinary headlines.
19908 L Create a timeline for the current buffer.
19909 e Export views to associated files.
19911 More commands can be added by configuring the variable
19912 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19913 searches can be pre-defined in this way.
19915 If the current buffer is in Org-mode and visiting a file, you can also
19916 first press `<' once to indicate that the agenda should be temporarily
19917 \(until the next use of \\[org-agenda]) restricted to the current file.
19918 Pressing `<' twice means to restrict to the current subtree or region
19919 \(if active)."
19920 (interactive "P")
19921 (catch 'exit
19922 (let* ((prefix-descriptions nil)
19923 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19924 (org-agenda-custom-commands
19925 ;; normalize different versions
19926 (delq nil
19927 (mapcar
19928 (lambda (x)
19929 (cond ((stringp (cdr x))
19930 (push x prefix-descriptions)
19931 nil)
19932 ((stringp (nth 1 x)) x)
19933 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19934 (t (cons (car x) (cons "" (cdr x))))))
19935 org-agenda-custom-commands)))
19936 (buf (current-buffer))
19937 (bfn (buffer-file-name (buffer-base-buffer)))
19938 entry key type match lprops ans)
19939 ;; Turn off restriction unless there is an overriding one
19940 (unless org-agenda-overriding-restriction
19941 (put 'org-agenda-files 'org-restrict nil)
19942 (setq org-agenda-restrict nil)
19943 (move-marker org-agenda-restrict-begin nil)
19944 (move-marker org-agenda-restrict-end nil))
19945 ;; Delete old local properties
19946 (put 'org-agenda-redo-command 'org-lprops nil)
19947 ;; Remember where this call originated
19948 (setq org-agenda-last-dispatch-buffer (current-buffer))
19949 (unless keys
19950 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19951 keys (car ans)
19952 restriction (cdr ans)))
19953 ;; Estabish the restriction, if any
19954 (when (and (not org-agenda-overriding-restriction) restriction)
19955 (put 'org-agenda-files 'org-restrict (list bfn))
19956 (cond
19957 ((eq restriction 'region)
19958 (setq org-agenda-restrict t)
19959 (move-marker org-agenda-restrict-begin (region-beginning))
19960 (move-marker org-agenda-restrict-end (region-end)))
19961 ((eq restriction 'subtree)
19962 (save-excursion
19963 (setq org-agenda-restrict t)
19964 (org-back-to-heading t)
19965 (move-marker org-agenda-restrict-begin (point))
19966 (move-marker org-agenda-restrict-end
19967 (progn (org-end-of-subtree t)))))))
19969 (require 'calendar) ; FIXME: can we avoid this for some commands?
19970 ;; For example the todo list should not need it (but does...)
19971 (cond
19972 ((setq entry (assoc keys org-agenda-custom-commands))
19973 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19974 (progn
19975 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19976 (put 'org-agenda-redo-command 'org-lprops lprops)
19977 (cond
19978 ((eq type 'agenda)
19979 (org-let lprops '(org-agenda-list current-prefix-arg)))
19980 ((eq type 'alltodo)
19981 (org-let lprops '(org-todo-list current-prefix-arg)))
19982 ((eq type 'search)
19983 (org-let lprops '(org-search-view current-prefix-arg match)))
19984 ((eq type 'stuck)
19985 (org-let lprops '(org-agenda-list-stuck-projects
19986 current-prefix-arg)))
19987 ((eq type 'tags)
19988 (org-let lprops '(org-tags-view current-prefix-arg match)))
19989 ((eq type 'tags-todo)
19990 (org-let lprops '(org-tags-view '(4) match)))
19991 ((eq type 'todo)
19992 (org-let lprops '(org-todo-list match)))
19993 ((eq type 'tags-tree)
19994 (org-check-for-org-mode)
19995 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
19996 ((eq type 'todo-tree)
19997 (org-check-for-org-mode)
19998 (org-let lprops
19999 '(org-occur (concat "^" outline-regexp "[ \t]*"
20000 (regexp-quote match) "\\>"))))
20001 ((eq type 'occur-tree)
20002 (org-check-for-org-mode)
20003 (org-let lprops '(org-occur match)))
20004 ((functionp type)
20005 (org-let lprops '(funcall type match)))
20006 ((fboundp type)
20007 (org-let lprops '(funcall type match)))
20008 (t (error "Invalid custom agenda command type %s" type))))
20009 (org-run-agenda-series (nth 1 entry) (cddr entry))))
20010 ((equal keys "C")
20011 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
20012 (customize-variable 'org-agenda-custom-commands))
20013 ((equal keys "a") (call-interactively 'org-agenda-list))
20014 ((equal keys "s") (call-interactively 'org-search-view))
20015 ((equal keys "t") (call-interactively 'org-todo-list))
20016 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
20017 ((equal keys "m") (call-interactively 'org-tags-view))
20018 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
20019 ((equal keys "e") (call-interactively 'org-store-agenda-views))
20020 ((equal keys "L")
20021 (unless (org-mode-p)
20022 (error "This is not an Org-mode file"))
20023 (unless restriction
20024 (put 'org-agenda-files 'org-restrict (list bfn))
20025 (org-call-with-arg 'org-timeline arg)))
20026 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
20027 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
20028 ((equal keys "!") (customize-variable 'org-stuck-projects))
20029 (t (error "Invalid agenda key"))))))
20031 (defun org-agenda-normalize-custom-commands (cmds)
20032 (delq nil
20033 (mapcar
20034 (lambda (x)
20035 (cond ((stringp (cdr x)) nil)
20036 ((stringp (nth 1 x)) x)
20037 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
20038 (t (cons (car x) (cons "" (cdr x))))))
20039 cmds)))
20041 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
20042 "The user interface for selecting an agenda command."
20043 (catch 'exit
20044 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
20045 (restrict-ok (and bfn (org-mode-p)))
20046 (region-p (org-region-active-p))
20047 (custom org-agenda-custom-commands)
20048 (selstring "")
20049 restriction second-time
20050 c entry key type match prefixes rmheader header-end custom1 desc)
20051 (save-window-excursion
20052 (delete-other-windows)
20053 (org-switch-to-buffer-other-window " *Agenda Commands*")
20054 (erase-buffer)
20055 (insert (eval-when-compile
20056 (let ((header
20058 Press key for an agenda command: < Buffer,subtree/region restriction
20059 -------------------------------- > Remove restriction
20060 a Agenda for current week or day e Export agenda views
20061 t List of all TODO entries T Entries with special TODO kwd
20062 m Match a TAGS query M Like m, but only TODO entries
20063 L Timeline for current buffer # List stuck projects (!=configure)
20064 s Search for keywords C Configure custom agenda commands
20065 / Multi-occur
20067 (start 0))
20068 (while (string-match
20069 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
20070 header start)
20071 (setq start (match-end 0))
20072 (add-text-properties (match-beginning 2) (match-end 2)
20073 '(face bold) header))
20074 header)))
20075 (setq header-end (move-marker (make-marker) (point)))
20076 (while t
20077 (setq custom1 custom)
20078 (when (eq rmheader t)
20079 (goto-line 1)
20080 (re-search-forward ":" nil t)
20081 (delete-region (match-end 0) (point-at-eol))
20082 (forward-char 1)
20083 (looking-at "-+")
20084 (delete-region (match-end 0) (point-at-eol))
20085 (move-marker header-end (match-end 0)))
20086 (goto-char header-end)
20087 (delete-region (point) (point-max))
20088 (while (setq entry (pop custom1))
20089 (setq key (car entry) desc (nth 1 entry)
20090 type (nth 2 entry) match (nth 3 entry))
20091 (if (> (length key) 1)
20092 (add-to-list 'prefixes (string-to-char key))
20093 (insert
20094 (format
20095 "\n%-4s%-14s: %s"
20096 (org-add-props (copy-sequence key)
20097 '(face bold))
20098 (cond
20099 ((string-match "\\S-" desc) desc)
20100 ((eq type 'agenda) "Agenda for current week or day")
20101 ((eq type 'alltodo) "List of all TODO entries")
20102 ((eq type 'search) "Word search")
20103 ((eq type 'stuck) "List of stuck projects")
20104 ((eq type 'todo) "TODO keyword")
20105 ((eq type 'tags) "Tags query")
20106 ((eq type 'tags-todo) "Tags (TODO)")
20107 ((eq type 'tags-tree) "Tags tree")
20108 ((eq type 'todo-tree) "TODO kwd tree")
20109 ((eq type 'occur-tree) "Occur tree")
20110 ((functionp type) (if (symbolp type)
20111 (symbol-name type)
20112 "Lambda expression"))
20113 (t "???"))
20114 (cond
20115 ((stringp match)
20116 (org-add-props match nil 'face 'org-warning))
20117 (match
20118 (format "set of %d commands" (length match)))
20119 (t ""))))))
20120 (when prefixes
20121 (mapc (lambda (x)
20122 (insert
20123 (format "\n%s %s"
20124 (org-add-props (char-to-string x)
20125 nil 'face 'bold)
20126 (or (cdr (assoc (concat selstring (char-to-string x))
20127 prefix-descriptions))
20128 "Prefix key"))))
20129 prefixes))
20130 (goto-char (point-min))
20131 (when (fboundp 'fit-window-to-buffer)
20132 (if second-time
20133 (if (not (pos-visible-in-window-p (point-max)))
20134 (fit-window-to-buffer))
20135 (setq second-time t)
20136 (fit-window-to-buffer)))
20137 (message "Press key for agenda command%s:"
20138 (if (or restrict-ok org-agenda-overriding-restriction)
20139 (if org-agenda-overriding-restriction
20140 " (restriction lock active)"
20141 (if restriction
20142 (format " (restricted to %s)" restriction)
20143 " (unrestricted)"))
20144 ""))
20145 (setq c (read-char-exclusive))
20146 (message "")
20147 (cond
20148 ((assoc (char-to-string c) custom)
20149 (setq selstring (concat selstring (char-to-string c)))
20150 (throw 'exit (cons selstring restriction)))
20151 ((memq c prefixes)
20152 (setq selstring (concat selstring (char-to-string c))
20153 prefixes nil
20154 rmheader (or rmheader t)
20155 custom (delq nil (mapcar
20156 (lambda (x)
20157 (if (or (= (length (car x)) 1)
20158 (/= (string-to-char (car x)) c))
20160 (cons (substring (car x) 1) (cdr x))))
20161 custom))))
20162 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20163 (message "Restriction is only possible in Org-mode buffers")
20164 (ding) (sit-for 1))
20165 ((eq c ?1)
20166 (org-agenda-remove-restriction-lock 'noupdate)
20167 (setq restriction 'buffer))
20168 ((eq c ?0)
20169 (org-agenda-remove-restriction-lock 'noupdate)
20170 (setq restriction (if region-p 'region 'subtree)))
20171 ((eq c ?<)
20172 (org-agenda-remove-restriction-lock 'noupdate)
20173 (setq restriction
20174 (cond
20175 ((eq restriction 'buffer)
20176 (if region-p 'region 'subtree))
20177 ((memq restriction '(subtree region))
20178 nil)
20179 (t 'buffer))))
20180 ((eq c ?>)
20181 (org-agenda-remove-restriction-lock 'noupdate)
20182 (setq restriction nil))
20183 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20184 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20185 ((and (> (length selstring) 0) (eq c ?\d))
20186 (delete-window)
20187 (org-agenda-get-restriction-and-command prefix-descriptions))
20189 ((equal c ?q) (error "Abort"))
20190 (t (error "Invalid key %c" c))))))))
20192 (defun org-run-agenda-series (name series)
20193 (org-prepare-agenda name)
20194 (let* ((org-agenda-multi t)
20195 (redo (list 'org-run-agenda-series name (list 'quote series)))
20196 (cmds (car series))
20197 (gprops (nth 1 series))
20198 match ;; The byte compiler incorrectly complains about this. Keep it!
20199 cmd type lprops)
20200 (while (setq cmd (pop cmds))
20201 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20202 (cond
20203 ((eq type 'agenda)
20204 (org-let2 gprops lprops
20205 '(call-interactively 'org-agenda-list)))
20206 ((eq type 'alltodo)
20207 (org-let2 gprops lprops
20208 '(call-interactively 'org-todo-list)))
20209 ((eq type 'search)
20210 (org-let2 gprops lprops
20211 '(org-search-view current-prefix-arg match)))
20212 ((eq type 'stuck)
20213 (org-let2 gprops lprops
20214 '(call-interactively 'org-agenda-list-stuck-projects)))
20215 ((eq type 'tags)
20216 (org-let2 gprops lprops
20217 '(org-tags-view current-prefix-arg match)))
20218 ((eq type 'tags-todo)
20219 (org-let2 gprops lprops
20220 '(org-tags-view '(4) match)))
20221 ((eq type 'todo)
20222 (org-let2 gprops lprops
20223 '(org-todo-list match)))
20224 ((fboundp type)
20225 (org-let2 gprops lprops
20226 '(funcall type match)))
20227 (t (error "Invalid type in command series"))))
20228 (widen)
20229 (setq org-agenda-redo-command redo)
20230 (goto-char (point-min)))
20231 (org-finalize-agenda))
20233 ;;;###autoload
20234 (defmacro org-batch-agenda (cmd-key &rest parameters)
20235 "Run an agenda command in batch mode and send the result to STDOUT.
20236 If CMD-KEY is a string of length 1, it is used as a key in
20237 `org-agenda-custom-commands' and triggers this command. If it is a
20238 longer string it is used as a tags/todo match string.
20239 Paramters are alternating variable names and values that will be bound
20240 before running the agenda command."
20241 (let (pars)
20242 (while parameters
20243 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20244 (if (> (length cmd-key) 2)
20245 (eval (list 'let (nreverse pars)
20246 (list 'org-tags-view nil cmd-key)))
20247 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20248 (set-buffer org-agenda-buffer-name)
20249 (princ (org-encode-for-stdout (buffer-string)))))
20251 (defun org-encode-for-stdout (string)
20252 (if (fboundp 'encode-coding-string)
20253 (encode-coding-string string buffer-file-coding-system)
20254 string))
20256 (defvar org-agenda-info nil)
20258 ;;;###autoload
20259 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20260 "Run an agenda command in batch mode and send the result to STDOUT.
20261 If CMD-KEY is a string of length 1, it is used as a key in
20262 `org-agenda-custom-commands' and triggers this command. If it is a
20263 longer string it is used as a tags/todo match string.
20264 Paramters are alternating variable names and values that will be bound
20265 before running the agenda command.
20267 The output gives a line for each selected agenda item. Each
20268 item is a list of comma-separated values, like this:
20270 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20272 category The category of the item
20273 head The headline, without TODO kwd, TAGS and PRIORITY
20274 type The type of the agenda entry, can be
20275 todo selected in TODO match
20276 tagsmatch selected in tags match
20277 diary imported from diary
20278 deadline a deadline on given date
20279 scheduled scheduled on given date
20280 timestamp entry has timestamp on given date
20281 closed entry was closed on given date
20282 upcoming-deadline warning about deadline
20283 past-scheduled forwarded scheduled item
20284 block entry has date block including g. date
20285 todo The todo keyword, if any
20286 tags All tags including inherited ones, separated by colons
20287 date The relevant date, like 2007-2-14
20288 time The time, like 15:00-16:50
20289 extra Sting with extra planning info
20290 priority-l The priority letter if any was given
20291 priority-n The computed numerical priority
20292 agenda-day The day in the agenda where this is listed"
20294 (let (pars)
20295 (while parameters
20296 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20297 (push (list 'org-agenda-remove-tags t) pars)
20298 (if (> (length cmd-key) 2)
20299 (eval (list 'let (nreverse pars)
20300 (list 'org-tags-view nil cmd-key)))
20301 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20302 (set-buffer org-agenda-buffer-name)
20303 (let* ((lines (org-split-string (buffer-string) "\n"))
20304 line)
20305 (while (setq line (pop lines))
20306 (catch 'next
20307 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20308 (setq org-agenda-info
20309 (org-fix-agenda-info (text-properties-at 0 line)))
20310 (princ
20311 (org-encode-for-stdout
20312 (mapconcat 'org-agenda-export-csv-mapper
20313 '(org-category txt type todo tags date time-of-day extra
20314 priority-letter priority agenda-day)
20315 ",")))
20316 (princ "\n"))))))
20318 (defun org-fix-agenda-info (props)
20319 "Make sure all properties on an agenda item have a canonical form,
20320 so the export commands can easily use it."
20321 (let (tmp re)
20322 (when (setq tmp (plist-get props 'tags))
20323 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20324 (when (setq tmp (plist-get props 'date))
20325 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20326 (let ((calendar-date-display-form '(year "-" month "-" day)))
20327 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20329 (setq tmp (calendar-date-string tmp)))
20330 (setq props (plist-put props 'date tmp)))
20331 (when (setq tmp (plist-get props 'day))
20332 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20333 (let ((calendar-date-display-form '(year "-" month "-" day)))
20334 (setq tmp (calendar-date-string tmp)))
20335 (setq props (plist-put props 'day tmp))
20336 (setq props (plist-put props 'agenda-day tmp)))
20337 (when (setq tmp (plist-get props 'txt))
20338 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20339 (plist-put props 'priority-letter (match-string 1 tmp))
20340 (setq tmp (replace-match "" t t tmp)))
20341 (when (and (setq re (plist-get props 'org-todo-regexp))
20342 (setq re (concat "\\`\\.*" re " ?"))
20343 (string-match re tmp))
20344 (plist-put props 'todo (match-string 1 tmp))
20345 (setq tmp (replace-match "" t t tmp)))
20346 (plist-put props 'txt tmp)))
20347 props)
20349 (defun org-agenda-export-csv-mapper (prop)
20350 (let ((res (plist-get org-agenda-info prop)))
20351 (setq res
20352 (cond
20353 ((not res) "")
20354 ((stringp res) res)
20355 (t (prin1-to-string res))))
20356 (while (string-match "," res)
20357 (setq res (replace-match ";" t t res)))
20358 (org-trim res)))
20361 ;;;###autoload
20362 (defun org-store-agenda-views (&rest parameters)
20363 (interactive)
20364 (eval (list 'org-batch-store-agenda-views)))
20366 ;; FIXME, why is this a macro?????
20367 ;;;###autoload
20368 (defmacro org-batch-store-agenda-views (&rest parameters)
20369 "Run all custom agenda commands that have a file argument."
20370 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20371 (pop-up-frames nil)
20372 (dir default-directory)
20373 pars cmd thiscmdkey files opts)
20374 (while parameters
20375 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20376 (setq pars (reverse pars))
20377 (save-window-excursion
20378 (while cmds
20379 (setq cmd (pop cmds)
20380 thiscmdkey (car cmd)
20381 opts (nth 4 cmd)
20382 files (nth 5 cmd))
20383 (if (stringp files) (setq files (list files)))
20384 (when files
20385 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20386 (list 'org-agenda nil thiscmdkey)))
20387 (set-buffer org-agenda-buffer-name)
20388 (while files
20389 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20390 (list 'org-write-agenda
20391 (expand-file-name (pop files) dir) t))))
20392 (and (get-buffer org-agenda-buffer-name)
20393 (kill-buffer org-agenda-buffer-name)))))))
20395 (defun org-write-agenda (file &optional nosettings)
20396 "Write the current buffer (an agenda view) as a file.
20397 Depending on the extension of the file name, plain text (.txt),
20398 HTML (.html or .htm) or Postscript (.ps) is produced.
20399 If NOSETTINGS is given, do not scope the settings of
20400 `org-agenda-exporter-settings' into the export commands. This is used when
20401 the settings have already been scoped and we do not wish to overrule other,
20402 higher priority settings."
20403 (interactive "FWrite agenda to file: ")
20404 (if (not (file-writable-p file))
20405 (error "Cannot write agenda to file %s" file))
20406 (cond
20407 ((string-match "\\.html?\\'" file) (require 'htmlize))
20408 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20409 (org-let (if nosettings nil org-agenda-exporter-settings)
20410 '(save-excursion
20411 (save-window-excursion
20412 (cond
20413 ((string-match "\\.html?\\'" file)
20414 (set-buffer (htmlize-buffer (current-buffer)))
20416 (when (and org-agenda-export-html-style
20417 (string-match "<style>" org-agenda-export-html-style))
20418 ;; replace <style> section with org-agenda-export-html-style
20419 (goto-char (point-min))
20420 (kill-region (- (search-forward "<style") 6)
20421 (search-forward "</style>"))
20422 (insert org-agenda-export-html-style))
20423 (write-file file)
20424 (kill-buffer (current-buffer))
20425 (message "HTML written to %s" file))
20426 ((string-match "\\.ps\\'" file)
20427 (ps-print-buffer-with-faces file)
20428 (message "Postscript written to %s" file))
20430 (let ((bs (buffer-string)))
20431 (find-file file)
20432 (insert bs)
20433 (save-buffer 0)
20434 (kill-buffer (current-buffer))
20435 (message "Plain text written to %s" file))))))
20436 (set-buffer org-agenda-buffer-name)))
20438 (defmacro org-no-read-only (&rest body)
20439 "Inhibit read-only for BODY."
20440 `(let ((inhibit-read-only t)) ,@body))
20442 (defun org-check-for-org-mode ()
20443 "Make sure current buffer is in org-mode. Error if not."
20444 (or (org-mode-p)
20445 (error "Cannot execute org-mode agenda command on buffer in %s."
20446 major-mode)))
20448 (defun org-fit-agenda-window ()
20449 "Fit the window to the buffer size."
20450 (and (memq org-agenda-window-setup '(reorganize-frame))
20451 (fboundp 'fit-window-to-buffer)
20452 (fit-window-to-buffer
20454 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20455 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20457 ;;; Agenda file list
20459 (defun org-agenda-files (&optional unrestricted)
20460 "Get the list of agenda files.
20461 Optional UNRESTRICTED means return the full list even if a restriction
20462 is currently in place."
20463 (let ((files
20464 (cond
20465 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20466 ((stringp org-agenda-files) (org-read-agenda-file-list))
20467 ((listp org-agenda-files) org-agenda-files)
20468 (t (error "Invalid value of `org-agenda-files'")))))
20469 (setq files (apply 'append
20470 (mapcar (lambda (f)
20471 (if (file-directory-p f)
20472 (directory-files f t
20473 org-agenda-file-regexp)
20474 (list f)))
20475 files)))
20476 (if org-agenda-skip-unavailable-files
20477 (delq nil
20478 (mapcar (function
20479 (lambda (file)
20480 (and (file-readable-p file) file)))
20481 files))
20482 files))) ; `org-check-agenda-file' will remove them from the list
20484 (defun org-edit-agenda-file-list ()
20485 "Edit the list of agenda files.
20486 Depending on setup, this either uses customize to edit the variable
20487 `org-agenda-files', or it visits the file that is holding the list. In the
20488 latter case, the buffer is set up in a way that saving it automatically kills
20489 the buffer and restores the previous window configuration."
20490 (interactive)
20491 (if (stringp org-agenda-files)
20492 (let ((cw (current-window-configuration)))
20493 (find-file org-agenda-files)
20494 (org-set-local 'org-window-configuration cw)
20495 (org-add-hook 'after-save-hook
20496 (lambda ()
20497 (set-window-configuration
20498 (prog1 org-window-configuration
20499 (kill-buffer (current-buffer))))
20500 (org-install-agenda-files-menu)
20501 (message "New agenda file list installed"))
20502 nil 'local)
20503 (message "%s" (substitute-command-keys
20504 "Edit list and finish with \\[save-buffer]")))
20505 (customize-variable 'org-agenda-files)))
20507 (defun org-store-new-agenda-file-list (list)
20508 "Set new value for the agenda file list and save it correcly."
20509 (if (stringp org-agenda-files)
20510 (let ((f org-agenda-files) b)
20511 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20512 (with-temp-file f
20513 (insert (mapconcat 'identity list "\n") "\n")))
20514 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20515 (setq org-agenda-files list)
20516 (customize-save-variable 'org-agenda-files org-agenda-files))))
20518 (defun org-read-agenda-file-list ()
20519 "Read the list of agenda files from a file."
20520 (when (stringp org-agenda-files)
20521 (with-temp-buffer
20522 (insert-file-contents org-agenda-files)
20523 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20526 ;;;###autoload
20527 (defun org-cycle-agenda-files ()
20528 "Cycle through the files in `org-agenda-files'.
20529 If the current buffer visits an agenda file, find the next one in the list.
20530 If the current buffer does not, find the first agenda file."
20531 (interactive)
20532 (let* ((fs (org-agenda-files t))
20533 (files (append fs (list (car fs))))
20534 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20535 file)
20536 (unless files (error "No agenda files"))
20537 (catch 'exit
20538 (while (setq file (pop files))
20539 (if (equal (file-truename file) tcf)
20540 (when (car files)
20541 (find-file (car files))
20542 (throw 'exit t))))
20543 (find-file (car fs)))
20544 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20546 (defun org-agenda-file-to-front (&optional to-end)
20547 "Move/add the current file to the top of the agenda file list.
20548 If the file is not present in the list, it is added to the front. If it is
20549 present, it is moved there. With optional argument TO-END, add/move to the
20550 end of the list."
20551 (interactive "P")
20552 (let ((org-agenda-skip-unavailable-files nil)
20553 (file-alist (mapcar (lambda (x)
20554 (cons (file-truename x) x))
20555 (org-agenda-files t)))
20556 (ctf (file-truename buffer-file-name))
20557 x had)
20558 (setq x (assoc ctf file-alist) had x)
20560 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20561 (if to-end
20562 (setq file-alist (append (delq x file-alist) (list x)))
20563 (setq file-alist (cons x (delq x file-alist))))
20564 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20565 (org-install-agenda-files-menu)
20566 (message "File %s to %s of agenda file list"
20567 (if had "moved" "added") (if to-end "end" "front"))))
20569 (defun org-remove-file (&optional file)
20570 "Remove current file from the list of files in variable `org-agenda-files'.
20571 These are the files which are being checked for agenda entries.
20572 Optional argument FILE means, use this file instead of the current."
20573 (interactive)
20574 (let* ((org-agenda-skip-unavailable-files nil)
20575 (file (or file buffer-file-name))
20576 (true-file (file-truename file))
20577 (afile (abbreviate-file-name file))
20578 (files (delq nil (mapcar
20579 (lambda (x)
20580 (if (equal true-file
20581 (file-truename x))
20582 nil x))
20583 (org-agenda-files t)))))
20584 (if (not (= (length files) (length (org-agenda-files t))))
20585 (progn
20586 (org-store-new-agenda-file-list files)
20587 (org-install-agenda-files-menu)
20588 (message "Removed file: %s" afile))
20589 (message "File was not in list: %s (not removed)" afile))))
20591 (defun org-file-menu-entry (file)
20592 (vector file (list 'find-file file) t))
20594 (defun org-check-agenda-file (file)
20595 "Make sure FILE exists. If not, ask user what to do."
20596 (when (not (file-exists-p file))
20597 (message "non-existent file %s. [R]emove from list or [A]bort?"
20598 (abbreviate-file-name file))
20599 (let ((r (downcase (read-char-exclusive))))
20600 (cond
20601 ((equal r ?r)
20602 (org-remove-file file)
20603 (throw 'nextfile t))
20604 (t (error "Abort"))))))
20606 ;;; Agenda prepare and finalize
20608 (defvar org-agenda-multi nil) ; dynammically scoped
20609 (defvar org-agenda-buffer-name "*Org Agenda*")
20610 (defvar org-pre-agenda-window-conf nil)
20611 (defvar org-agenda-name nil)
20612 (defun org-prepare-agenda (&optional name)
20613 (setq org-todo-keywords-for-agenda nil)
20614 (setq org-done-keywords-for-agenda nil)
20615 (if org-agenda-multi
20616 (progn
20617 (setq buffer-read-only nil)
20618 (goto-char (point-max))
20619 (unless (or (bobp) org-agenda-compact-blocks)
20620 (insert "\n" (make-string (window-width) ?=) "\n"))
20621 (narrow-to-region (point) (point-max)))
20622 (org-agenda-reset-markers)
20623 (org-prepare-agenda-buffers (org-agenda-files))
20624 (setq org-todo-keywords-for-agenda
20625 (org-uniquify org-todo-keywords-for-agenda))
20626 (setq org-done-keywords-for-agenda
20627 (org-uniquify org-done-keywords-for-agenda))
20628 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20629 (awin (get-buffer-window abuf)))
20630 (cond
20631 ((equal (current-buffer) abuf) nil)
20632 (awin (select-window awin))
20633 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20634 ((equal org-agenda-window-setup 'current-window)
20635 (switch-to-buffer abuf))
20636 ((equal org-agenda-window-setup 'other-window)
20637 (org-switch-to-buffer-other-window abuf))
20638 ((equal org-agenda-window-setup 'other-frame)
20639 (switch-to-buffer-other-frame abuf))
20640 ((equal org-agenda-window-setup 'reorganize-frame)
20641 (delete-other-windows)
20642 (org-switch-to-buffer-other-window abuf))))
20643 (setq buffer-read-only nil)
20644 (erase-buffer)
20645 (org-agenda-mode)
20646 (and name (not org-agenda-name)
20647 (org-set-local 'org-agenda-name name)))
20648 (setq buffer-read-only nil))
20650 (defun org-finalize-agenda ()
20651 "Finishing touch for the agenda buffer, called just before displaying it."
20652 (unless org-agenda-multi
20653 (save-excursion
20654 (let ((inhibit-read-only t))
20655 (goto-char (point-min))
20656 (while (org-activate-bracket-links (point-max))
20657 (add-text-properties (match-beginning 0) (match-end 0)
20658 '(face org-link)))
20659 (org-agenda-align-tags)
20660 (unless org-agenda-with-colors
20661 (remove-text-properties (point-min) (point-max) '(face nil))))
20662 (if (and (boundp 'org-overriding-columns-format)
20663 org-overriding-columns-format)
20664 (org-set-local 'org-overriding-columns-format
20665 org-overriding-columns-format))
20666 (if (and (boundp 'org-agenda-view-columns-initially)
20667 org-agenda-view-columns-initially)
20668 (org-agenda-columns))
20669 (when org-agenda-fontify-priorities
20670 (org-fontify-priorities))
20671 (run-hooks 'org-finalize-agenda-hook)
20672 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20675 (defun org-fontify-priorities ()
20676 "Make highest priority lines bold, and lowest italic."
20677 (interactive)
20678 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20679 (org-delete-overlay o)))
20680 (org-overlays-in (point-min) (point-max)))
20681 (save-excursion
20682 (let ((inhibit-read-only t)
20683 b e p ov h l)
20684 (goto-char (point-min))
20685 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20686 (setq h (or (get-char-property (point) 'org-highest-priority)
20687 org-highest-priority)
20688 l (or (get-char-property (point) 'org-lowest-priority)
20689 org-lowest-priority)
20690 p (string-to-char (match-string 1))
20691 b (match-beginning 0) e (point-at-eol)
20692 ov (org-make-overlay b e))
20693 (org-overlay-put
20694 ov 'face
20695 (cond ((listp org-agenda-fontify-priorities)
20696 (cdr (assoc p org-agenda-fontify-priorities)))
20697 ((equal p l) 'italic)
20698 ((equal p h) 'bold)))
20699 (org-overlay-put ov 'org-type 'org-priority)))))
20701 (defun org-prepare-agenda-buffers (files)
20702 "Create buffers for all agenda files, protect archived trees and comments."
20703 (interactive)
20704 (let ((pa '(:org-archived t))
20705 (pc '(:org-comment t))
20706 (pall '(:org-archived t :org-comment t))
20707 (inhibit-read-only t)
20708 (rea (concat ":" org-archive-tag ":"))
20709 bmp file re)
20710 (save-excursion
20711 (save-restriction
20712 (while (setq file (pop files))
20713 (if (bufferp file)
20714 (set-buffer file)
20715 (org-check-agenda-file file)
20716 (set-buffer (org-get-agenda-file-buffer file)))
20717 (widen)
20718 (setq bmp (buffer-modified-p))
20719 (org-refresh-category-properties)
20720 (setq org-todo-keywords-for-agenda
20721 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20722 (setq org-done-keywords-for-agenda
20723 (append org-done-keywords-for-agenda org-done-keywords))
20724 (save-excursion
20725 (remove-text-properties (point-min) (point-max) pall)
20726 (when org-agenda-skip-archived-trees
20727 (goto-char (point-min))
20728 (while (re-search-forward rea nil t)
20729 (if (org-on-heading-p t)
20730 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20731 (goto-char (point-min))
20732 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20733 (while (re-search-forward re nil t)
20734 (add-text-properties
20735 (match-beginning 0) (org-end-of-subtree t) pc)))
20736 (set-buffer-modified-p bmp))))))
20738 (defvar org-agenda-skip-function nil
20739 "Function to be called at each match during agenda construction.
20740 If this function returns nil, the current match should not be skipped.
20741 Otherwise, the function must return a position from where the search
20742 should be continued.
20743 This may also be a Lisp form, it will be evaluated.
20744 Never set this variable using `setq' or so, because then it will apply
20745 to all future agenda commands. Instead, bind it with `let' to scope
20746 it dynamically into the agenda-constructing command. A good way to set
20747 it is through options in org-agenda-custom-commands.")
20749 (defun org-agenda-skip ()
20750 "Throw to `:skip' in places that should be skipped.
20751 Also moves point to the end of the skipped region, so that search can
20752 continue from there."
20753 (let ((p (point-at-bol)) to fp)
20754 (and org-agenda-skip-archived-trees
20755 (get-text-property p :org-archived)
20756 (org-end-of-subtree t)
20757 (throw :skip t))
20758 (and (get-text-property p :org-comment)
20759 (org-end-of-subtree t)
20760 (throw :skip t))
20761 (if (equal (char-after p) ?#) (throw :skip t))
20762 (when (and (or (setq fp (functionp org-agenda-skip-function))
20763 (consp org-agenda-skip-function))
20764 (setq to (save-excursion
20765 (save-match-data
20766 (if fp
20767 (funcall org-agenda-skip-function)
20768 (eval org-agenda-skip-function))))))
20769 (goto-char to)
20770 (throw :skip t))))
20772 (defvar org-agenda-markers nil
20773 "List of all currently active markers created by `org-agenda'.")
20774 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20775 "Creation time of the last agenda marker.")
20777 (defun org-agenda-new-marker (&optional pos)
20778 "Return a new agenda marker.
20779 Org-mode keeps a list of these markers and resets them when they are
20780 no longer in use."
20781 (let ((m (copy-marker (or pos (point)))))
20782 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20783 (push m org-agenda-markers)
20786 (defun org-agenda-reset-markers ()
20787 "Reset markers created by `org-agenda'."
20788 (while org-agenda-markers
20789 (move-marker (pop org-agenda-markers) nil)))
20791 (defun org-get-agenda-file-buffer (file)
20792 "Get a buffer visiting FILE. If the buffer needs to be created, add
20793 it to the list of buffers which might be released later."
20794 (let ((buf (org-find-base-buffer-visiting file)))
20795 (if buf
20796 buf ; just return it
20797 ;; Make a new buffer and remember it
20798 (setq buf (find-file-noselect file))
20799 (if buf (push buf org-agenda-new-buffers))
20800 buf)))
20802 (defun org-release-buffers (blist)
20803 "Release all buffers in list, asking the user for confirmation when needed.
20804 When a buffer is unmodified, it is just killed. When modified, it is saved
20805 \(if the user agrees) and then killed."
20806 (let (buf file)
20807 (while (setq buf (pop blist))
20808 (setq file (buffer-file-name buf))
20809 (when (and (buffer-modified-p buf)
20810 file
20811 (y-or-n-p (format "Save file %s? " file)))
20812 (with-current-buffer buf (save-buffer)))
20813 (kill-buffer buf))))
20815 (defun org-get-category (&optional pos)
20816 "Get the category applying to position POS."
20817 (get-text-property (or pos (point)) 'org-category))
20819 ;;; Agenda timeline
20821 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20823 (defun org-timeline (&optional include-all)
20824 "Show a time-sorted view of the entries in the current org file.
20825 Only entries with a time stamp of today or later will be listed. With
20826 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20827 under the current date.
20828 If the buffer contains an active region, only check the region for
20829 dates."
20830 (interactive "P")
20831 (require 'calendar)
20832 (org-compile-prefix-format 'timeline)
20833 (org-set-sorting-strategy 'timeline)
20834 (let* ((dopast t)
20835 (dotodo include-all)
20836 (doclosed org-agenda-show-log)
20837 (entry buffer-file-name)
20838 (date (calendar-current-date))
20839 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20840 (end (if (org-region-active-p) (region-end) (point-max)))
20841 (day-numbers (org-get-all-dates beg end 'no-ranges
20842 t doclosed ; always include today
20843 org-timeline-show-empty-dates))
20844 (org-deadline-warning-days 0)
20845 (org-agenda-only-exact-dates t)
20846 (today (time-to-days (current-time)))
20847 (past t)
20848 args
20849 s e rtn d emptyp)
20850 (setq org-agenda-redo-command
20851 (list 'progn
20852 (list 'org-switch-to-buffer-other-window (current-buffer))
20853 (list 'org-timeline (list 'quote include-all))))
20854 (if (not dopast)
20855 ;; Remove past dates from the list of dates.
20856 (setq day-numbers (delq nil (mapcar (lambda(x)
20857 (if (>= x today) x nil))
20858 day-numbers))))
20859 (org-prepare-agenda (concat "Timeline "
20860 (file-name-nondirectory buffer-file-name)))
20861 (if doclosed (push :closed args))
20862 (push :timestamp args)
20863 (push :deadline args)
20864 (push :scheduled args)
20865 (push :sexp args)
20866 (if dotodo (push :todo args))
20867 (while (setq d (pop day-numbers))
20868 (if (and (listp d) (eq (car d) :omitted))
20869 (progn
20870 (setq s (point))
20871 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20872 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20873 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20874 (if (and (>= d today)
20875 dopast
20876 past)
20877 (progn
20878 (setq past nil)
20879 (insert (make-string 79 ?-) "\n")))
20880 (setq date (calendar-gregorian-from-absolute d))
20881 (setq s (point))
20882 (setq rtn (and (not emptyp)
20883 (apply 'org-agenda-get-day-entries entry
20884 date args)))
20885 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20886 (progn
20887 (insert
20888 (if (stringp org-agenda-format-date)
20889 (format-time-string org-agenda-format-date
20890 (org-time-from-absolute date))
20891 (funcall org-agenda-format-date date))
20892 "\n")
20893 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20894 (put-text-property s (1- (point)) 'org-date-line t)
20895 (if (equal d today)
20896 (put-text-property s (1- (point)) 'org-today t))
20897 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20898 (put-text-property s (1- (point)) 'day d)))))
20899 (goto-char (point-min))
20900 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20901 (point-min)))
20902 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20903 (org-finalize-agenda)
20904 (setq buffer-read-only t)))
20906 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20907 "Return a list of all relevant day numbers from BEG to END buffer positions.
20908 If NO-RANGES is non-nil, include only the start and end dates of a range,
20909 not every single day in the range. If FORCE-TODAY is non-nil, make
20910 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20911 inactive time stamps (those in square brackets) are included.
20912 When EMPTY is non-nil, also include days without any entries."
20913 (let ((re (concat
20914 (if pre-re pre-re "")
20915 (if inactive org-ts-regexp-both org-ts-regexp)))
20916 dates dates1 date day day1 day2 ts1 ts2)
20917 (if force-today
20918 (setq dates (list (time-to-days (current-time)))))
20919 (save-excursion
20920 (goto-char beg)
20921 (while (re-search-forward re end t)
20922 (setq day (time-to-days (org-time-string-to-time
20923 (substring (match-string 1) 0 10))))
20924 (or (memq day dates) (push day dates)))
20925 (unless no-ranges
20926 (goto-char beg)
20927 (while (re-search-forward org-tr-regexp end t)
20928 (setq ts1 (substring (match-string 1) 0 10)
20929 ts2 (substring (match-string 2) 0 10)
20930 day1 (time-to-days (org-time-string-to-time ts1))
20931 day2 (time-to-days (org-time-string-to-time ts2)))
20932 (while (< (setq day1 (1+ day1)) day2)
20933 (or (memq day1 dates) (push day1 dates)))))
20934 (setq dates (sort dates '<))
20935 (when empty
20936 (while (setq day (pop dates))
20937 (setq day2 (car dates))
20938 (push day dates1)
20939 (when (and day2 empty)
20940 (if (or (eq empty t)
20941 (and (numberp empty) (<= (- day2 day) empty)))
20942 (while (< (setq day (1+ day)) day2)
20943 (push (list day) dates1))
20944 (push (cons :omitted (- day2 day)) dates1))))
20945 (setq dates (nreverse dates1)))
20946 dates)))
20948 ;;; Agenda Daily/Weekly
20950 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
20951 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
20952 (defvar org-agenda-last-arguments nil
20953 "The arguments of the previous call to org-agenda")
20954 (defvar org-starting-day nil) ; local variable in the agenda buffer
20955 (defvar org-agenda-span nil) ; local variable in the agenda buffer
20956 (defvar org-include-all-loc nil) ; local variable
20957 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
20959 ;;;###autoload
20960 (defun org-agenda-list (&optional include-all start-day ndays)
20961 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
20962 The view will be for the current day or week, but from the overview buffer
20963 you will be able to go to other days/weeks.
20965 With one \\[universal-argument] prefix argument INCLUDE-ALL,
20966 all unfinished TODO items will also be shown, before the agenda.
20967 This feature is considered obsolete, please use the TODO list or a block
20968 agenda instead.
20970 With a numeric prefix argument in an interactive call, the agenda will
20971 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
20972 the number of days. NDAYS defaults to `org-agenda-ndays'.
20974 START-DAY defaults to TODAY, or to the most recent match for the weekday
20975 given in `org-agenda-start-on-weekday'."
20976 (interactive "P")
20977 (if (and (integerp include-all) (> include-all 0))
20978 (setq ndays include-all include-all nil))
20979 (setq ndays (or ndays org-agenda-ndays)
20980 start-day (or start-day org-agenda-start-day))
20981 (if org-agenda-overriding-arguments
20982 (setq include-all (car org-agenda-overriding-arguments)
20983 start-day (nth 1 org-agenda-overriding-arguments)
20984 ndays (nth 2 org-agenda-overriding-arguments)))
20985 (if (stringp start-day)
20986 ;; Convert to an absolute day number
20987 (setq start-day (time-to-days (org-read-date nil t start-day))))
20988 (setq org-agenda-last-arguments (list include-all start-day ndays))
20989 (org-compile-prefix-format 'agenda)
20990 (org-set-sorting-strategy 'agenda)
20991 (require 'calendar)
20992 (let* ((org-agenda-start-on-weekday
20993 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
20994 org-agenda-start-on-weekday nil))
20995 (thefiles (org-agenda-files))
20996 (files thefiles)
20997 (today (time-to-days
20998 (time-subtract (current-time)
20999 (list 0 (* 3600 org-extend-today-until) 0))))
21000 (sd (or start-day today))
21001 (start (if (or (null org-agenda-start-on-weekday)
21002 (< org-agenda-ndays 7))
21004 (let* ((nt (calendar-day-of-week
21005 (calendar-gregorian-from-absolute sd)))
21006 (n1 org-agenda-start-on-weekday)
21007 (d (- nt n1)))
21008 (- sd (+ (if (< d 0) 7 0) d)))))
21009 (day-numbers (list start))
21010 (day-cnt 0)
21011 (inhibit-redisplay (not debug-on-error))
21012 s e rtn rtnall file date d start-pos end-pos todayp nd)
21013 (setq org-agenda-redo-command
21014 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
21015 ;; Make the list of days
21016 (setq ndays (or ndays org-agenda-ndays)
21017 nd ndays)
21018 (while (> ndays 1)
21019 (push (1+ (car day-numbers)) day-numbers)
21020 (setq ndays (1- ndays)))
21021 (setq day-numbers (nreverse day-numbers))
21022 (org-prepare-agenda "Day/Week")
21023 (org-set-local 'org-starting-day (car day-numbers))
21024 (org-set-local 'org-include-all-loc include-all)
21025 (org-set-local 'org-agenda-span
21026 (org-agenda-ndays-to-span nd))
21027 (when (and (or include-all org-agenda-include-all-todo)
21028 (member today day-numbers))
21029 (setq files thefiles
21030 rtnall nil)
21031 (while (setq file (pop files))
21032 (catch 'nextfile
21033 (org-check-agenda-file file)
21034 (setq date (calendar-gregorian-from-absolute today)
21035 rtn (org-agenda-get-day-entries
21036 file date :todo))
21037 (setq rtnall (append rtnall rtn))))
21038 (when rtnall
21039 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
21040 (add-text-properties (point-min) (1- (point))
21041 (list 'face 'org-agenda-structure))
21042 (insert (org-finalize-agenda-entries rtnall) "\n")))
21043 (unless org-agenda-compact-blocks
21044 (setq s (point))
21045 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
21046 "-agenda:\n")
21047 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
21048 'org-date-line t)))
21049 (while (setq d (pop day-numbers))
21050 (setq date (calendar-gregorian-from-absolute d)
21051 s (point))
21052 (if (or (setq todayp (= d today))
21053 (and (not start-pos) (= d sd)))
21054 (setq start-pos (point))
21055 (if (and start-pos (not end-pos))
21056 (setq end-pos (point))))
21057 (setq files thefiles
21058 rtnall nil)
21059 (while (setq file (pop files))
21060 (catch 'nextfile
21061 (org-check-agenda-file file)
21062 (if org-agenda-show-log
21063 (setq rtn (org-agenda-get-day-entries
21064 file date
21065 :deadline :scheduled :timestamp :sexp :closed))
21066 (setq rtn (org-agenda-get-day-entries
21067 file date
21068 :deadline :scheduled :sexp :timestamp)))
21069 (setq rtnall (append rtnall rtn))))
21070 (if org-agenda-include-diary
21071 (progn
21072 (require 'diary-lib)
21073 (setq rtn (org-get-entries-from-diary date))
21074 (setq rtnall (append rtnall rtn))))
21075 (if (or rtnall org-agenda-show-all-dates)
21076 (progn
21077 (setq day-cnt (1+ day-cnt))
21078 (insert
21079 (if (stringp org-agenda-format-date)
21080 (format-time-string org-agenda-format-date
21081 (org-time-from-absolute date))
21082 (funcall org-agenda-format-date date))
21083 "\n")
21084 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
21085 (put-text-property s (1- (point)) 'org-date-line t)
21086 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
21087 (if todayp (put-text-property s (1- (point)) 'org-today t))
21088 (if rtnall (insert
21089 (org-finalize-agenda-entries
21090 (org-agenda-add-time-grid-maybe
21091 rtnall nd todayp))
21092 "\n"))
21093 (put-text-property s (1- (point)) 'day d)
21094 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
21095 (goto-char (point-min))
21096 (org-fit-agenda-window)
21097 (unless (and (pos-visible-in-window-p (point-min))
21098 (pos-visible-in-window-p (point-max)))
21099 (goto-char (1- (point-max)))
21100 (recenter -1)
21101 (if (not (pos-visible-in-window-p (or start-pos 1)))
21102 (progn
21103 (goto-char (or start-pos 1))
21104 (recenter 1))))
21105 (goto-char (or start-pos 1))
21106 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
21107 (org-finalize-agenda)
21108 (setq buffer-read-only t)
21109 (message "")))
21111 (defun org-agenda-ndays-to-span (n)
21112 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21114 ;;; Agenda word search
21116 (defvar org-agenda-search-history nil)
21118 ;;;###autoload
21119 (defun org-search-view (&optional arg string)
21120 "Show all entries that contain words or regular expressions.
21121 If the first character of the search string is an asterisks,
21122 search only the headlines.
21124 The search string is broken into \"words\" by splitting at whitespace.
21125 The individual words are then interpreted as a boolean expression with
21126 logical AND. Words prefixed with a minus must not occur in the entry.
21127 Words without a prefix or prefixed with a plus must occur in the entry.
21128 Matching is case-insensitive and the words are enclosed by word delimiters.
21130 Words enclosed by curly braces are interpreted as regular expressions
21131 that must or must not match in the entry.
21133 This command searches the agenda files, and in addition the files listed
21134 in `org-agenda-text-search-extra-files'."
21135 (interactive "P")
21136 (org-compile-prefix-format 'search)
21137 (org-set-sorting-strategy 'search)
21138 (org-prepare-agenda "SEARCH")
21139 (let* ((props (list 'face nil
21140 'done-face 'org-done
21141 'org-not-done-regexp org-not-done-regexp
21142 'org-todo-regexp org-todo-regexp
21143 'mouse-face 'highlight
21144 'keymap org-agenda-keymap
21145 'help-echo (format "mouse-2 or RET jump to location")))
21146 regexp rtn rtnall files file pos
21147 marker priority category tags c neg re
21148 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21149 (unless (and (not arg)
21150 (stringp string)
21151 (string-match "\\S-" string))
21152 (setq string (read-string "[+-]Word/{Regexp} ...: "
21153 (cond
21154 ((integerp arg) (cons string arg))
21155 (arg string))
21156 'org-agenda-search-history)))
21157 (setq org-agenda-redo-command
21158 (list 'org-search-view 'current-prefix-arg string))
21159 (setq org-agenda-query-string string)
21161 (if (equal (string-to-char string) ?*)
21162 (setq hdl-only t
21163 words (substring string 1))
21164 (setq words string))
21165 (setq words (org-split-string words))
21166 (mapc (lambda (w)
21167 (setq c (string-to-char w))
21168 (if (equal c ?-)
21169 (setq neg t w (substring w 1))
21170 (if (equal c ?+)
21171 (setq neg nil w (substring w 1))
21172 (setq neg nil)))
21173 (if (string-match "\\`{.*}\\'" w)
21174 (setq re (substring w 1 -1))
21175 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21176 (if neg (push re regexps-) (push re regexps+)))
21177 words)
21178 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21179 (if (not regexps+)
21180 (setq regexp (concat "^" org-outline-regexp))
21181 (setq regexp (pop regexps+))
21182 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21183 regexp))))
21184 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21185 rtnall nil)
21186 (while (setq file (pop files))
21187 (setq ee nil)
21188 (catch 'nextfile
21189 (org-check-agenda-file file)
21190 (setq buffer (if (file-exists-p file)
21191 (org-get-agenda-file-buffer file)
21192 (error "No such file %s" file)))
21193 (if (not buffer)
21194 ;; If file does not exist, make sure an error message is sent
21195 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21196 file))))
21197 (with-current-buffer buffer
21198 (unless (org-mode-p)
21199 (error "Agenda file %s is not in `org-mode'" file))
21200 (let ((case-fold-search t))
21201 (save-excursion
21202 (save-restriction
21203 (if org-agenda-restrict
21204 (narrow-to-region org-agenda-restrict-begin
21205 org-agenda-restrict-end)
21206 (widen))
21207 (goto-char (point-min))
21208 (unless (or (org-on-heading-p)
21209 (outline-next-heading))
21210 (throw 'nextfile t))
21211 (goto-char (max (point-min) (1- (point))))
21212 (while (re-search-forward regexp nil t)
21213 (org-back-to-heading t)
21214 (skip-chars-forward "* ")
21215 (setq beg (point-at-bol)
21216 beg1 (point)
21217 end (progn (outline-next-heading) (point)))
21218 (catch :skip
21219 (goto-char beg)
21220 (org-agenda-skip)
21221 (setq str (buffer-substring-no-properties
21222 (point-at-bol)
21223 (if hdl-only (point-at-eol) end)))
21224 (mapc (lambda (wr) (when (string-match wr str)
21225 (goto-char (1- end))
21226 (throw :skip t)))
21227 regexps-)
21228 (mapc (lambda (wr) (unless (string-match wr str)
21229 (goto-char (1- end))
21230 (throw :skip t)))
21231 regexps+)
21232 (goto-char beg)
21233 (setq marker (org-agenda-new-marker (point))
21234 category (org-get-category)
21235 tags (org-get-tags-at (point))
21236 txt (org-format-agenda-item
21238 (buffer-substring-no-properties
21239 beg1 (point-at-eol))
21240 category tags))
21241 (org-add-props txt props
21242 'org-marker marker 'org-hd-marker marker
21243 'priority 1000 'org-category category
21244 'type "search")
21245 (push txt ee)
21246 (goto-char (1- end)))))))))
21247 (setq rtn (nreverse ee))
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 "Search words: ")
21253 (add-text-properties (point-min) (1- (point))
21254 (list 'face 'org-agenda-structure))
21255 (setq pos (point))
21256 (insert string "\n")
21257 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21258 (setq pos (point))
21259 (unless org-agenda-multi
21260 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21261 (add-text-properties pos (1- (point))
21262 (list 'face 'org-agenda-structure))))
21263 (when rtnall
21264 (insert (org-finalize-agenda-entries rtnall) "\n"))
21265 (goto-char (point-min))
21266 (org-fit-agenda-window)
21267 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21268 (org-finalize-agenda)
21269 (setq buffer-read-only t)))
21271 ;;; Agenda TODO list
21273 (defvar org-select-this-todo-keyword nil)
21274 (defvar org-last-arg nil)
21276 ;;;###autoload
21277 (defun org-todo-list (arg)
21278 "Show all TODO entries from all agenda file in a single list.
21279 The prefix arg can be used to select a specific TODO keyword and limit
21280 the list to these. When using \\[universal-argument], you will be prompted
21281 for a keyword. A numeric prefix directly selects the Nth keyword in
21282 `org-todo-keywords-1'."
21283 (interactive "P")
21284 (require 'calendar)
21285 (org-compile-prefix-format 'todo)
21286 (org-set-sorting-strategy 'todo)
21287 (org-prepare-agenda "TODO")
21288 (let* ((today (time-to-days (current-time)))
21289 (date (calendar-gregorian-from-absolute today))
21290 (kwds org-todo-keywords-for-agenda)
21291 (completion-ignore-case t)
21292 (org-select-this-todo-keyword
21293 (if (stringp arg) arg
21294 (and arg (integerp arg) (> arg 0)
21295 (nth (1- arg) kwds))))
21296 rtn rtnall files file pos)
21297 (when (equal arg '(4))
21298 (setq org-select-this-todo-keyword
21299 (completing-read "Keyword (or KWD1|K2D2|...): "
21300 (mapcar 'list kwds) nil nil)))
21301 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21302 (org-set-local 'org-last-arg arg)
21303 (setq org-agenda-redo-command
21304 '(org-todo-list (or current-prefix-arg org-last-arg)))
21305 (setq files (org-agenda-files)
21306 rtnall nil)
21307 (while (setq file (pop files))
21308 (catch 'nextfile
21309 (org-check-agenda-file file)
21310 (setq rtn (org-agenda-get-day-entries file date :todo))
21311 (setq rtnall (append rtnall rtn))))
21312 (if org-agenda-overriding-header
21313 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21314 nil 'face 'org-agenda-structure) "\n")
21315 (insert "Global list of TODO items of type: ")
21316 (add-text-properties (point-min) (1- (point))
21317 (list 'face 'org-agenda-structure))
21318 (setq pos (point))
21319 (insert (or org-select-this-todo-keyword "ALL") "\n")
21320 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21321 (setq pos (point))
21322 (unless org-agenda-multi
21323 (insert "Available with `N r': (0)ALL")
21324 (let ((n 0) s)
21325 (mapc (lambda (x)
21326 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21327 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21328 (insert "\n "))
21329 (insert " " s))
21330 kwds))
21331 (insert "\n"))
21332 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21333 (when rtnall
21334 (insert (org-finalize-agenda-entries rtnall) "\n"))
21335 (goto-char (point-min))
21336 (org-fit-agenda-window)
21337 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21338 (org-finalize-agenda)
21339 (setq buffer-read-only t)))
21341 ;;; Agenda tags match
21343 ;;;###autoload
21344 (defun org-tags-view (&optional todo-only match)
21345 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21346 The prefix arg TODO-ONLY limits the search to TODO entries."
21347 (interactive "P")
21348 (org-compile-prefix-format 'tags)
21349 (org-set-sorting-strategy 'tags)
21350 (let* ((org-tags-match-list-sublevels
21351 (if todo-only t org-tags-match-list-sublevels))
21352 (completion-ignore-case t)
21353 rtn rtnall files file pos matcher
21354 buffer)
21355 (setq matcher (org-make-tags-matcher match)
21356 match (car matcher) matcher (cdr matcher))
21357 (org-prepare-agenda (concat "TAGS " match))
21358 (setq org-agenda-query-string match)
21359 (setq org-agenda-redo-command
21360 (list 'org-tags-view (list 'quote todo-only)
21361 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21362 (setq files (org-agenda-files)
21363 rtnall nil)
21364 (while (setq file (pop files))
21365 (catch 'nextfile
21366 (org-check-agenda-file file)
21367 (setq buffer (if (file-exists-p file)
21368 (org-get-agenda-file-buffer file)
21369 (error "No such file %s" file)))
21370 (if (not buffer)
21371 ;; If file does not exist, merror message to agenda
21372 (setq rtn (list
21373 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21374 rtnall (append rtnall rtn))
21375 (with-current-buffer buffer
21376 (unless (org-mode-p)
21377 (error "Agenda file %s is not in `org-mode'" file))
21378 (save-excursion
21379 (save-restriction
21380 (if org-agenda-restrict
21381 (narrow-to-region org-agenda-restrict-begin
21382 org-agenda-restrict-end)
21383 (widen))
21384 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21385 (setq rtnall (append rtnall rtn))))))))
21386 (if org-agenda-overriding-header
21387 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21388 nil 'face 'org-agenda-structure) "\n")
21389 (insert "Headlines with TAGS match: ")
21390 (add-text-properties (point-min) (1- (point))
21391 (list 'face 'org-agenda-structure))
21392 (setq pos (point))
21393 (insert match "\n")
21394 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21395 (setq pos (point))
21396 (unless org-agenda-multi
21397 (insert "Press `C-u r' to search again with new search string\n"))
21398 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21399 (when rtnall
21400 (insert (org-finalize-agenda-entries rtnall) "\n"))
21401 (goto-char (point-min))
21402 (org-fit-agenda-window)
21403 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21404 (org-finalize-agenda)
21405 (setq buffer-read-only t)))
21407 ;;; Agenda Finding stuck projects
21409 (defvar org-agenda-skip-regexp nil
21410 "Regular expression used in skipping subtrees for the agenda.
21411 This is basically a temporary global variable that can be set and then
21412 used by user-defined selections using `org-agenda-skip-function'.")
21414 (defvar org-agenda-overriding-header nil
21415 "When this is set during todo and tags searches, will replace header.")
21417 (defun org-agenda-skip-subtree-when-regexp-matches ()
21418 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21419 If yes, it returns the end position of this tree, causing agenda commands
21420 to skip this subtree. This is a function that can be put into
21421 `org-agenda-skip-function' for the duration of a command."
21422 (let ((end (save-excursion (org-end-of-subtree t)))
21423 skip)
21424 (save-excursion
21425 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21426 (and skip end)))
21428 (defun org-agenda-skip-entry-if (&rest conditions)
21429 "Skip entry if any of CONDITIONS is true.
21430 See `org-agenda-skip-if' for details."
21431 (org-agenda-skip-if nil conditions))
21433 (defun org-agenda-skip-subtree-if (&rest conditions)
21434 "Skip entry if any of CONDITIONS is true.
21435 See `org-agenda-skip-if' for details."
21436 (org-agenda-skip-if t conditions))
21438 (defun org-agenda-skip-if (subtree conditions)
21439 "Checks current entity for CONDITIONS.
21440 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21441 the entry, i.e. the text before the next heading is checked.
21443 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21444 from different tests. Valid conditions are:
21446 scheduled Check if there is a scheduled cookie
21447 notscheduled Check if there is no scheduled cookie
21448 deadline Check if there is a deadline
21449 notdeadline Check if there is no deadline
21450 regexp Check if regexp matches
21451 notregexp Check if regexp does not match.
21453 The regexp is taken from the conditions list, it must come right after
21454 the `regexp' or `notregexp' element.
21456 If any of these conditions is met, this function returns the end point of
21457 the entity, causing the search to continue from there. This is a function
21458 that can be put into `org-agenda-skip-function' for the duration of a command."
21459 (let (beg end m)
21460 (org-back-to-heading t)
21461 (setq beg (point)
21462 end (if subtree
21463 (progn (org-end-of-subtree t) (point))
21464 (progn (outline-next-heading) (1- (point)))))
21465 (goto-char beg)
21466 (and
21468 (and (memq 'scheduled conditions)
21469 (re-search-forward org-scheduled-time-regexp end t))
21470 (and (memq 'notscheduled conditions)
21471 (not (re-search-forward org-scheduled-time-regexp end t)))
21472 (and (memq 'deadline conditions)
21473 (re-search-forward org-deadline-time-regexp end t))
21474 (and (memq 'notdeadline conditions)
21475 (not (re-search-forward org-deadline-time-regexp end t)))
21476 (and (setq m (memq 'regexp conditions))
21477 (stringp (nth 1 m))
21478 (re-search-forward (nth 1 m) end t))
21479 (and (setq m (memq 'notregexp conditions))
21480 (stringp (nth 1 m))
21481 (not (re-search-forward (nth 1 m) end t))))
21482 end)))
21484 ;;;###autoload
21485 (defun org-agenda-list-stuck-projects (&rest ignore)
21486 "Create agenda view for projects that are stuck.
21487 Stuck projects are project that have no next actions. For the definitions
21488 of what a project is and how to check if it stuck, customize the variable
21489 `org-stuck-projects'.
21490 MATCH is being ignored."
21491 (interactive)
21492 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21493 ;; FIXME: we could have used org-agenda-skip-if here.
21494 (org-agenda-overriding-header "List of stuck projects: ")
21495 (matcher (nth 0 org-stuck-projects))
21496 (todo (nth 1 org-stuck-projects))
21497 (todo-wds (if (member "*" todo)
21498 (progn
21499 (org-prepare-agenda-buffers (org-agenda-files))
21500 (org-delete-all
21501 org-done-keywords-for-agenda
21502 (copy-sequence org-todo-keywords-for-agenda)))
21503 todo))
21504 (todo-re (concat "^\\*+[ \t]+\\("
21505 (mapconcat 'identity todo-wds "\\|")
21506 "\\)\\>"))
21507 (tags (nth 2 org-stuck-projects))
21508 (tags-re (if (member "*" tags)
21509 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21510 (concat "^\\*+ .*:\\("
21511 (mapconcat 'identity tags "\\|")
21512 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21513 (gen-re (nth 3 org-stuck-projects))
21514 (re-list
21515 (delq nil
21516 (list
21517 (if todo todo-re)
21518 (if tags tags-re)
21519 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21520 gen-re)))))
21521 (setq org-agenda-skip-regexp
21522 (if re-list
21523 (mapconcat 'identity re-list "\\|")
21524 (error "No information how to identify unstuck projects")))
21525 (org-tags-view nil matcher)
21526 (with-current-buffer org-agenda-buffer-name
21527 (setq org-agenda-redo-command
21528 '(org-agenda-list-stuck-projects
21529 (or current-prefix-arg org-last-arg))))))
21531 ;;; Diary integration
21533 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21535 (defun org-get-entries-from-diary (date)
21536 "Get the (Emacs Calendar) diary entries for DATE."
21537 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21538 (diary-display-hook '(fancy-diary-display))
21539 (pop-up-frames nil)
21540 (list-diary-entries-hook
21541 (cons 'org-diary-default-entry list-diary-entries-hook))
21542 (diary-file-name-prefix-function nil) ; turn this feature off
21543 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21544 entries
21545 (org-disable-agenda-to-diary t))
21546 (save-excursion
21547 (save-window-excursion
21548 (funcall (if (fboundp 'diary-list-entries)
21549 'diary-list-entries 'list-diary-entries)
21550 date 1)))
21551 (if (not (get-buffer fancy-diary-buffer))
21552 (setq entries nil)
21553 (with-current-buffer fancy-diary-buffer
21554 (setq buffer-read-only nil)
21555 (if (zerop (buffer-size))
21556 ;; No entries
21557 (setq entries nil)
21558 ;; Omit the date and other unnecessary stuff
21559 (org-agenda-cleanup-fancy-diary)
21560 ;; Add prefix to each line and extend the text properties
21561 (if (zerop (buffer-size))
21562 (setq entries nil)
21563 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21564 (set-buffer-modified-p nil)
21565 (kill-buffer fancy-diary-buffer)))
21566 (when entries
21567 (setq entries (org-split-string entries "\n"))
21568 (setq entries
21569 (mapcar
21570 (lambda (x)
21571 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21572 ;; Extend the text properties to the beginning of the line
21573 (org-add-props x (text-properties-at (1- (length x)) x)
21574 'type "diary" 'date date))
21575 entries)))))
21577 (defun org-agenda-cleanup-fancy-diary ()
21578 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21579 This gets rid of the date, the underline under the date, and
21580 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21581 date. It also removes lines that contain only whitespace."
21582 (goto-char (point-min))
21583 (if (looking-at ".*?:[ \t]*")
21584 (progn
21585 (replace-match "")
21586 (re-search-forward "\n=+$" nil t)
21587 (replace-match "")
21588 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21589 (re-search-forward "\n=+$" nil t)
21590 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21591 (goto-char (point-min))
21592 (while (re-search-forward "^ +\n" nil t)
21593 (replace-match ""))
21594 (goto-char (point-min))
21595 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21596 (replace-match "")))
21598 ;; Make sure entries from the diary have the right text properties.
21599 (eval-after-load "diary-lib"
21600 '(if (boundp 'diary-modify-entry-list-string-function)
21601 ;; We can rely on the hook, nothing to do
21603 ;; Hook not avaiable, must use advice to make this work
21604 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21605 "Make the position visible."
21606 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21607 (stringp string)
21608 buffer-file-name)
21609 (setq string (org-modify-diary-entry-string string))))))
21611 (defun org-modify-diary-entry-string (string)
21612 "Add text properties to string, allowing org-mode to act on it."
21613 (org-add-props string nil
21614 'mouse-face 'highlight
21615 'keymap org-agenda-keymap
21616 'help-echo (if buffer-file-name
21617 (format "mouse-2 or RET jump to diary file %s"
21618 (abbreviate-file-name buffer-file-name))
21620 'org-agenda-diary-link t
21621 'org-marker (org-agenda-new-marker (point-at-bol))))
21623 (defun org-diary-default-entry ()
21624 "Add a dummy entry to the diary.
21625 Needed to avoid empty dates which mess up holiday display."
21626 ;; Catch the error if dealing with the new add-to-diary-alist
21627 (when org-disable-agenda-to-diary
21628 (condition-case nil
21629 (add-to-diary-list original-date "Org-mode dummy" "")
21630 (error
21631 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21633 ;;;###autoload
21634 (defun org-diary (&rest args)
21635 "Return diary information from org-files.
21636 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21637 It accesses org files and extracts information from those files to be
21638 listed in the diary. The function accepts arguments specifying what
21639 items should be listed. The following arguments are allowed:
21641 :timestamp List the headlines of items containing a date stamp or
21642 date range matching the selected date. Deadlines will
21643 also be listed, on the expiration day.
21645 :sexp List entries resulting from diary-like sexps.
21647 :deadline List any deadlines past due, or due within
21648 `org-deadline-warning-days'. The listing occurs only
21649 in the diary for *today*, not at any other date. If
21650 an entry is marked DONE, it is no longer listed.
21652 :scheduled List all items which are scheduled for the given date.
21653 The diary for *today* also contains items which were
21654 scheduled earlier and are not yet marked DONE.
21656 :todo List all TODO items from the org-file. This may be a
21657 long list - so this is not turned on by default.
21658 Like deadlines, these entries only show up in the
21659 diary for *today*, not at any other date.
21661 The call in the diary file should look like this:
21663 &%%(org-diary) ~/path/to/some/orgfile.org
21665 Use a separate line for each org file to check. Or, if you omit the file name,
21666 all files listed in `org-agenda-files' will be checked automatically:
21668 &%%(org-diary)
21670 If you don't give any arguments (as in the example above), the default
21671 arguments (:deadline :scheduled :timestamp :sexp) are used.
21672 So the example above may also be written as
21674 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21676 The function expects the lisp variables `entry' and `date' to be provided
21677 by the caller, because this is how the calendar works. Don't use this
21678 function from a program - use `org-agenda-get-day-entries' instead."
21679 (when (> (- (time-to-seconds (current-time))
21680 org-agenda-last-marker-time)
21682 (org-agenda-reset-markers))
21683 (org-compile-prefix-format 'agenda)
21684 (org-set-sorting-strategy 'agenda)
21685 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21686 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21687 (list entry)
21688 (org-agenda-files t)))
21689 file rtn results)
21690 (org-prepare-agenda-buffers files)
21691 ;; If this is called during org-agenda, don't return any entries to
21692 ;; the calendar. Org Agenda will list these entries itself.
21693 (if org-disable-agenda-to-diary (setq files nil))
21694 (while (setq file (pop files))
21695 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21696 (setq results (append results rtn)))
21697 (if results
21698 (concat (org-finalize-agenda-entries results) "\n"))))
21700 ;;; Agenda entry finders
21702 (defun org-agenda-get-day-entries (file date &rest args)
21703 "Does the work for `org-diary' and `org-agenda'.
21704 FILE is the path to a file to be checked for entries. DATE is date like
21705 the one returned by `calendar-current-date'. ARGS are symbols indicating
21706 which kind of entries should be extracted. For details about these, see
21707 the documentation of `org-diary'."
21708 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21709 (let* ((org-startup-folded nil)
21710 (org-startup-align-all-tables nil)
21711 (buffer (if (file-exists-p file)
21712 (org-get-agenda-file-buffer file)
21713 (error "No such file %s" file)))
21714 arg results rtn)
21715 (if (not buffer)
21716 ;; If file does not exist, make sure an error message ends up in diary
21717 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21718 (with-current-buffer buffer
21719 (unless (org-mode-p)
21720 (error "Agenda file %s is not in `org-mode'" file))
21721 (let ((case-fold-search nil))
21722 (save-excursion
21723 (save-restriction
21724 (if org-agenda-restrict
21725 (narrow-to-region org-agenda-restrict-begin
21726 org-agenda-restrict-end)
21727 (widen))
21728 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21729 (while (setq arg (pop args))
21730 (cond
21731 ((and (eq arg :todo)
21732 (equal date (calendar-current-date)))
21733 (setq rtn (org-agenda-get-todos))
21734 (setq results (append results rtn)))
21735 ((eq arg :timestamp)
21736 (setq rtn (org-agenda-get-blocks))
21737 (setq results (append results rtn))
21738 (setq rtn (org-agenda-get-timestamps))
21739 (setq results (append results rtn)))
21740 ((eq arg :sexp)
21741 (setq rtn (org-agenda-get-sexps))
21742 (setq results (append results rtn)))
21743 ((eq arg :scheduled)
21744 (setq rtn (org-agenda-get-scheduled))
21745 (setq results (append results rtn)))
21746 ((eq arg :closed)
21747 (setq rtn (org-agenda-get-closed))
21748 (setq results (append results rtn)))
21749 ((eq arg :deadline)
21750 (setq rtn (org-agenda-get-deadlines))
21751 (setq results (append results rtn))))))))
21752 results))))
21754 (defun org-entry-is-todo-p ()
21755 (member (org-get-todo-state) org-not-done-keywords))
21757 (defun org-entry-is-done-p ()
21758 (member (org-get-todo-state) org-done-keywords))
21760 (defun org-get-todo-state ()
21761 (save-excursion
21762 (org-back-to-heading t)
21763 (and (looking-at org-todo-line-regexp)
21764 (match-end 2)
21765 (match-string 2))))
21767 (defun org-at-date-range-p (&optional inactive-ok)
21768 "Is the cursor inside a date range?"
21769 (interactive)
21770 (save-excursion
21771 (catch 'exit
21772 (let ((pos (point)))
21773 (skip-chars-backward "^[<\r\n")
21774 (skip-chars-backward "<[")
21775 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21776 (>= (match-end 0) pos)
21777 (throw 'exit t))
21778 (skip-chars-backward "^<[\r\n")
21779 (skip-chars-backward "<[")
21780 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21781 (>= (match-end 0) pos)
21782 (throw 'exit t)))
21783 nil)))
21785 (defun org-agenda-get-todos ()
21786 "Return the TODO information for agenda display."
21787 (let* ((props (list 'face nil
21788 'done-face 'org-done
21789 'org-not-done-regexp org-not-done-regexp
21790 'org-todo-regexp org-todo-regexp
21791 'mouse-face 'highlight
21792 'keymap org-agenda-keymap
21793 'help-echo
21794 (format "mouse-2 or RET jump to org file %s"
21795 (abbreviate-file-name buffer-file-name))))
21796 ;; FIXME: get rid of the \n at some point but watch out
21797 (regexp (concat "^\\*+[ \t]+\\("
21798 (if org-select-this-todo-keyword
21799 (if (equal org-select-this-todo-keyword "*")
21800 org-todo-regexp
21801 (concat "\\<\\("
21802 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21803 "\\)\\>"))
21804 org-not-done-regexp)
21805 "[^\n\r]*\\)"))
21806 marker priority category tags
21807 ee txt beg end)
21808 (goto-char (point-min))
21809 (while (re-search-forward regexp nil t)
21810 (catch :skip
21811 (save-match-data
21812 (beginning-of-line)
21813 (setq beg (point) end (progn (outline-next-heading) (point)))
21814 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21815 (re-search-forward org-ts-regexp end t))
21816 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21817 (re-search-forward org-scheduled-time-regexp end t))
21818 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21819 (re-search-forward org-deadline-time-regexp end t)
21820 (org-deadline-close (match-string 1))))
21821 (goto-char (1+ beg))
21822 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21823 (throw :skip nil)))
21824 (goto-char beg)
21825 (org-agenda-skip)
21826 (goto-char (match-beginning 1))
21827 (setq marker (org-agenda-new-marker (match-beginning 0))
21828 category (org-get-category)
21829 tags (org-get-tags-at (point))
21830 txt (org-format-agenda-item "" (match-string 1) category tags)
21831 priority (1+ (org-get-priority txt)))
21832 (org-add-props txt props
21833 'org-marker marker 'org-hd-marker marker
21834 'priority priority 'org-category category
21835 'type "todo")
21836 (push txt ee)
21837 (if org-agenda-todo-list-sublevels
21838 (goto-char (match-end 1))
21839 (org-end-of-subtree 'invisible))))
21840 (nreverse ee)))
21842 (defconst org-agenda-no-heading-message
21843 "No heading for this item in buffer or region.")
21845 (defun org-agenda-get-timestamps ()
21846 "Return the date stamp information for agenda display."
21847 (let* ((props (list 'face nil
21848 'org-not-done-regexp org-not-done-regexp
21849 'org-todo-regexp org-todo-regexp
21850 'mouse-face 'highlight
21851 'keymap org-agenda-keymap
21852 'help-echo
21853 (format "mouse-2 or RET jump to org file %s"
21854 (abbreviate-file-name buffer-file-name))))
21855 (d1 (calendar-absolute-from-gregorian date))
21856 (remove-re
21857 (concat
21858 (regexp-quote
21859 (format-time-string
21860 "<%Y-%m-%d"
21861 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21862 ".*?>"))
21863 (regexp
21864 (concat
21865 (regexp-quote
21866 (substring
21867 (format-time-string
21868 (car org-time-stamp-formats)
21869 (apply 'encode-time ; DATE bound by calendar
21870 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21871 0 11))
21872 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21873 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21874 marker hdmarker deadlinep scheduledp donep tmp priority category
21875 ee txt timestr tags b0 b3 e3 head)
21876 (goto-char (point-min))
21877 (while (re-search-forward regexp nil t)
21878 (setq b0 (match-beginning 0)
21879 b3 (match-beginning 3) e3 (match-end 3))
21880 (catch :skip
21881 (and (org-at-date-range-p) (throw :skip nil))
21882 (org-agenda-skip)
21883 (if (and (match-end 1)
21884 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21885 (throw :skip nil))
21886 (if (and e3
21887 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21888 (throw :skip nil))
21889 (setq marker (org-agenda-new-marker b0)
21890 category (org-get-category b0)
21891 tmp (buffer-substring (max (point-min)
21892 (- b0 org-ds-keyword-length))
21894 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21895 deadlinep (string-match org-deadline-regexp tmp)
21896 scheduledp (string-match org-scheduled-regexp tmp)
21897 donep (org-entry-is-done-p))
21898 (if (or scheduledp deadlinep) (throw :skip t))
21899 (if (string-match ">" timestr)
21900 ;; substring should only run to end of time stamp
21901 (setq timestr (substring timestr 0 (match-end 0))))
21902 (save-excursion
21903 (if (re-search-backward "^\\*+ " nil t)
21904 (progn
21905 (goto-char (match-beginning 0))
21906 (setq hdmarker (org-agenda-new-marker)
21907 tags (org-get-tags-at))
21908 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21909 (setq head (match-string 1))
21910 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21911 (setq txt (org-format-agenda-item
21912 nil head category tags timestr nil
21913 remove-re)))
21914 (setq txt org-agenda-no-heading-message))
21915 (setq priority (org-get-priority txt))
21916 (org-add-props txt props
21917 'org-marker marker 'org-hd-marker hdmarker)
21918 (org-add-props txt nil 'priority priority
21919 'org-category category 'date date
21920 'type "timestamp")
21921 (push txt ee))
21922 (outline-next-heading)))
21923 (nreverse ee)))
21925 (defun org-agenda-get-sexps ()
21926 "Return the sexp information for agenda display."
21927 (require 'diary-lib)
21928 (let* ((props (list 'face nil
21929 'mouse-face 'highlight
21930 'keymap org-agenda-keymap
21931 'help-echo
21932 (format "mouse-2 or RET jump to org file %s"
21933 (abbreviate-file-name buffer-file-name))))
21934 (regexp "^&?%%(")
21935 marker category ee txt tags entry result beg b sexp sexp-entry)
21936 (goto-char (point-min))
21937 (while (re-search-forward regexp nil t)
21938 (catch :skip
21939 (org-agenda-skip)
21940 (setq beg (match-beginning 0))
21941 (goto-char (1- (match-end 0)))
21942 (setq b (point))
21943 (forward-sexp 1)
21944 (setq sexp (buffer-substring b (point)))
21945 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
21946 (org-trim (match-string 1))
21947 ""))
21948 (setq result (org-diary-sexp-entry sexp sexp-entry date))
21949 (when result
21950 (setq marker (org-agenda-new-marker beg)
21951 category (org-get-category beg))
21953 (if (string-match "\\S-" result)
21954 (setq txt result)
21955 (setq txt "SEXP entry returned empty string"))
21957 (setq txt (org-format-agenda-item
21958 "" txt category tags 'time))
21959 (org-add-props txt props 'org-marker marker)
21960 (org-add-props txt nil
21961 'org-category category 'date date
21962 'type "sexp")
21963 (push txt ee))))
21964 (nreverse ee)))
21966 (defun org-agenda-get-closed ()
21967 "Return the logged TODO entries for agenda display."
21968 (let* ((props (list 'mouse-face 'highlight
21969 'org-not-done-regexp org-not-done-regexp
21970 'org-todo-regexp org-todo-regexp
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 (concat
21976 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
21977 (regexp-quote
21978 (substring
21979 (format-time-string
21980 (car org-time-stamp-formats)
21981 (apply 'encode-time ; DATE bound by calendar
21982 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21983 1 11))))
21984 marker hdmarker priority category tags closedp
21985 ee txt timestr)
21986 (goto-char (point-min))
21987 (while (re-search-forward regexp nil t)
21988 (catch :skip
21989 (org-agenda-skip)
21990 (setq marker (org-agenda-new-marker (match-beginning 0))
21991 closedp (equal (match-string 1) org-closed-string)
21992 category (org-get-category (match-beginning 0))
21993 timestr (buffer-substring (match-beginning 0) (point-at-eol))
21994 ;; donep (org-entry-is-done-p)
21996 (if (string-match "\\]" timestr)
21997 ;; substring should only run to end of time stamp
21998 (setq timestr (substring timestr 0 (match-end 0))))
21999 (save-excursion
22000 (if (re-search-backward "^\\*+ " nil t)
22001 (progn
22002 (goto-char (match-beginning 0))
22003 (setq hdmarker (org-agenda-new-marker)
22004 tags (org-get-tags-at))
22005 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22006 (setq txt (org-format-agenda-item
22007 (if closedp "Closed: " "Clocked: ")
22008 (match-string 1) category tags timestr)))
22009 (setq txt org-agenda-no-heading-message))
22010 (setq priority 100000)
22011 (org-add-props txt props
22012 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
22013 'priority priority 'org-category category
22014 'type "closed" 'date date
22015 'undone-face 'org-warning 'done-face 'org-done)
22016 (push txt ee))
22017 (goto-char (point-at-eol))))
22018 (nreverse ee)))
22020 (defun org-agenda-get-deadlines ()
22021 "Return the deadline information for agenda display."
22022 (let* ((props (list 'mouse-face 'highlight
22023 'org-not-done-regexp org-not-done-regexp
22024 'org-todo-regexp org-todo-regexp
22025 'keymap org-agenda-keymap
22026 'help-echo
22027 (format "mouse-2 or RET jump to org file %s"
22028 (abbreviate-file-name buffer-file-name))))
22029 (regexp org-deadline-time-regexp)
22030 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22031 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22032 d2 diff dfrac wdays pos pos1 category tags
22033 ee txt head face s upcomingp donep timestr)
22034 (goto-char (point-min))
22035 (while (re-search-forward regexp nil t)
22036 (catch :skip
22037 (org-agenda-skip)
22038 (setq s (match-string 1)
22039 pos (1- (match-beginning 1))
22040 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22041 diff (- d2 d1)
22042 wdays (org-get-wdays s)
22043 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
22044 upcomingp (and todayp (> diff 0)))
22045 ;; When to show a deadline in the calendar:
22046 ;; If the expiration is within wdays warning time.
22047 ;; Past-due deadlines are only shown on the current date
22048 (if (or (and (<= diff wdays)
22049 (and todayp (not org-agenda-only-exact-dates)))
22050 (= diff 0))
22051 (save-excursion
22052 (setq category (org-get-category))
22053 (if (re-search-backward "^\\*+[ \t]+" nil t)
22054 (progn
22055 (goto-char (match-end 0))
22056 (setq pos1 (match-beginning 0))
22057 (setq tags (org-get-tags-at pos1))
22058 (setq head (buffer-substring-no-properties
22059 (point)
22060 (progn (skip-chars-forward "^\r\n")
22061 (point))))
22062 (setq donep (string-match org-looking-at-done-regexp head))
22063 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22064 (setq timestr
22065 (concat (substring s (match-beginning 1)) " "))
22066 (setq timestr 'time))
22067 (if (and donep
22068 (or org-agenda-skip-deadline-if-done
22069 (not (= diff 0))))
22070 (setq txt nil)
22071 (setq txt (org-format-agenda-item
22072 (if (= diff 0)
22073 (car org-agenda-deadline-leaders)
22074 (format (nth 1 org-agenda-deadline-leaders)
22075 diff))
22076 head category tags timestr))))
22077 (setq txt org-agenda-no-heading-message))
22078 (when txt
22079 (setq face (org-agenda-deadline-face dfrac wdays))
22080 (org-add-props txt props
22081 'org-marker (org-agenda-new-marker pos)
22082 'org-hd-marker (org-agenda-new-marker pos1)
22083 'priority (+ (- diff)
22084 (org-get-priority txt))
22085 'org-category category
22086 'type (if upcomingp "upcoming-deadline" "deadline")
22087 'date (if upcomingp date d2)
22088 'face (if donep 'org-done face)
22089 'undone-face face 'done-face 'org-done)
22090 (push txt ee))))))
22091 (nreverse ee)))
22093 (defun org-agenda-deadline-face (fraction &optional wdays)
22094 "Return the face to displaying a deadline item.
22095 FRACTION is what fraction of the head-warning time has passed."
22096 (if (equal wdays 0) (setq fraction 1.))
22097 (let ((faces org-agenda-deadline-faces) f)
22098 (catch 'exit
22099 (while (setq f (pop faces))
22100 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
22102 (defun org-agenda-get-scheduled ()
22103 "Return the scheduled information for agenda display."
22104 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
22105 'org-todo-regexp org-todo-regexp
22106 'done-face 'org-done
22107 'mouse-face 'highlight
22108 'keymap org-agenda-keymap
22109 'help-echo
22110 (format "mouse-2 or RET jump to org file %s"
22111 (abbreviate-file-name buffer-file-name))))
22112 (regexp org-scheduled-time-regexp)
22113 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22114 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22115 d2 diff pos pos1 category tags
22116 ee txt head pastschedp donep face timestr s)
22117 (goto-char (point-min))
22118 (while (re-search-forward regexp nil t)
22119 (catch :skip
22120 (org-agenda-skip)
22121 (setq s (match-string 1)
22122 pos (1- (match-beginning 1))
22123 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22124 ;;; is this right?
22125 ;;; do we need to do this for deadleine too????
22126 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22127 diff (- d2 d1))
22128 (setq pastschedp (and todayp (< diff 0)))
22129 ;; When to show a scheduled item in the calendar:
22130 ;; If it is on or past the date.
22131 (if (or (and (< diff 0)
22132 (and todayp (not org-agenda-only-exact-dates)))
22133 (= diff 0))
22134 (save-excursion
22135 (setq category (org-get-category))
22136 (if (re-search-backward "^\\*+[ \t]+" nil t)
22137 (progn
22138 (goto-char (match-end 0))
22139 (setq pos1 (match-beginning 0))
22140 (setq tags (org-get-tags-at))
22141 (setq head (buffer-substring-no-properties
22142 (point)
22143 (progn (skip-chars-forward "^\r\n") (point))))
22144 (setq donep (string-match org-looking-at-done-regexp head))
22145 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22146 (setq timestr
22147 (concat (substring s (match-beginning 1)) " "))
22148 (setq timestr 'time))
22149 (if (and donep
22150 (or org-agenda-skip-scheduled-if-done
22151 (not (= diff 0))))
22152 (setq txt nil)
22153 (setq txt (org-format-agenda-item
22154 (if (= diff 0)
22155 (car org-agenda-scheduled-leaders)
22156 (format (nth 1 org-agenda-scheduled-leaders)
22157 (- 1 diff)))
22158 head category tags timestr))))
22159 (setq txt org-agenda-no-heading-message))
22160 (when txt
22161 (setq face (if pastschedp
22162 'org-scheduled-previously
22163 'org-scheduled-today))
22164 (org-add-props txt props
22165 'undone-face face
22166 'face (if donep 'org-done face)
22167 'org-marker (org-agenda-new-marker pos)
22168 'org-hd-marker (org-agenda-new-marker pos1)
22169 'type (if pastschedp "past-scheduled" "scheduled")
22170 'date (if pastschedp d2 date)
22171 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22172 'org-category category)
22173 (push txt ee))))))
22174 (nreverse ee)))
22176 (defun org-agenda-get-blocks ()
22177 "Return the date-range information for agenda display."
22178 (let* ((props (list 'face nil
22179 'org-not-done-regexp org-not-done-regexp
22180 'org-todo-regexp org-todo-regexp
22181 'mouse-face 'highlight
22182 'keymap org-agenda-keymap
22183 'help-echo
22184 (format "mouse-2 or RET jump to org file %s"
22185 (abbreviate-file-name buffer-file-name))))
22186 (regexp org-tr-regexp)
22187 (d0 (calendar-absolute-from-gregorian date))
22188 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22189 donep head)
22190 (goto-char (point-min))
22191 (while (re-search-forward regexp nil t)
22192 (catch :skip
22193 (org-agenda-skip)
22194 (setq pos (point))
22195 (setq timestr (match-string 0)
22196 s1 (match-string 1)
22197 s2 (match-string 2)
22198 d1 (time-to-days (org-time-string-to-time s1))
22199 d2 (time-to-days (org-time-string-to-time s2)))
22200 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22201 ;; Only allow days between the limits, because the normal
22202 ;; date stamps will catch the limits.
22203 (save-excursion
22204 (setq marker (org-agenda-new-marker (point)))
22205 (setq category (org-get-category))
22206 (if (re-search-backward "^\\*+ " nil t)
22207 (progn
22208 (goto-char (match-beginning 0))
22209 (setq hdmarker (org-agenda-new-marker (point)))
22210 (setq tags (org-get-tags-at))
22211 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22212 (setq head (match-string 1))
22213 (and org-agenda-skip-timestamp-if-done
22214 (org-entry-is-done-p)
22215 (throw :skip t))
22216 (setq txt (org-format-agenda-item
22217 (format (if (= d1 d2) "" "(%d/%d): ")
22218 (1+ (- d0 d1)) (1+ (- d2 d1)))
22219 head category tags
22220 (if (= d0 d1) timestr))))
22221 (setq txt org-agenda-no-heading-message))
22222 (org-add-props txt props
22223 'org-marker marker 'org-hd-marker hdmarker
22224 'type "block" 'date date
22225 'priority (org-get-priority txt) 'org-category category)
22226 (push txt ee)))
22227 (goto-char pos)))
22228 ;; Sort the entries by expiration date.
22229 (nreverse ee)))
22231 ;;; Agenda presentation and sorting
22233 (defconst org-plain-time-of-day-regexp
22234 (concat
22235 "\\(\\<[012]?[0-9]"
22236 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22237 "\\(--?"
22238 "\\(\\<[012]?[0-9]"
22239 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22240 "\\)?")
22241 "Regular expression to match a plain time or time range.
22242 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22243 groups carry important information:
22244 0 the full match
22245 1 the first time, range or not
22246 8 the second time, if it is a range.")
22248 (defconst org-plain-time-extension-regexp
22249 (concat
22250 "\\(\\<[012]?[0-9]"
22251 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22252 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22253 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22254 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22255 groups carry important information:
22256 0 the full match
22257 7 hours of duration
22258 9 minutes of duration")
22260 (defconst org-stamp-time-of-day-regexp
22261 (concat
22262 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22263 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22264 "\\(--?"
22265 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22266 "Regular expression to match a timestamp time or time range.
22267 After a match, the following groups carry important information:
22268 0 the full match
22269 1 date plus weekday, for backreferencing to make sure both times on same day
22270 2 the first time, range or not
22271 4 the second time, if it is a range.")
22273 (defvar org-prefix-has-time nil
22274 "A flag, set by `org-compile-prefix-format'.
22275 The flag is set if the currently compiled format contains a `%t'.")
22276 (defvar org-prefix-has-tag nil
22277 "A flag, set by `org-compile-prefix-format'.
22278 The flag is set if the currently compiled format contains a `%T'.")
22280 (defun org-format-agenda-item (extra txt &optional category tags dotime
22281 noprefix remove-re)
22282 "Format TXT to be inserted into the agenda buffer.
22283 In particular, it adds the prefix and corresponding text properties. EXTRA
22284 must be a string and replaces the `%s' specifier in the prefix format.
22285 CATEGORY (string, symbol or nil) may be used to overrule the default
22286 category taken from local variable or file name. It will replace the `%c'
22287 specifier in the format. DOTIME, when non-nil, indicates that a
22288 time-of-day should be extracted from TXT for sorting of this entry, and for
22289 the `%t' specifier in the format. When DOTIME is a string, this string is
22290 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22291 only the correctly processes TXT should be returned - this is used by
22292 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22293 Any match of REMOVE-RE will be removed from TXT."
22294 (save-match-data
22295 ;; Diary entries sometimes have extra whitespace at the beginning
22296 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22297 (let* ((category (or category
22298 org-category
22299 (if buffer-file-name
22300 (file-name-sans-extension
22301 (file-name-nondirectory buffer-file-name))
22302 "")))
22303 (tag (if tags (nth (1- (length tags)) tags) ""))
22304 time ; time and tag are needed for the eval of the prefix format
22305 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22306 (time-of-day (and dotime (org-get-time-of-day ts)))
22307 stamp plain s0 s1 s2 rtn srp)
22308 (when (and dotime time-of-day org-prefix-has-time)
22309 ;; Extract starting and ending time and move them to prefix
22310 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22311 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22312 (setq s0 (match-string 0 ts)
22313 srp (and stamp (match-end 3))
22314 s1 (match-string (if plain 1 2) ts)
22315 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22317 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22318 ;; them, we might want to remove them there to avoid duplication.
22319 ;; The user can turn this off with a variable.
22320 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22321 (string-match (concat (regexp-quote s0) " *") txt)
22322 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22323 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22324 (= (match-beginning 0) 0)
22326 (setq txt (replace-match "" nil nil txt))))
22327 ;; Normalize the time(s) to 24 hour
22328 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22329 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22331 (when (and s1 (not s2) org-agenda-default-appointment-duration
22332 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22333 (let ((m (+ (string-to-number (match-string 2 s1))
22334 (* 60 (string-to-number (match-string 1 s1)))
22335 org-agenda-default-appointment-duration))
22337 (setq h (/ m 60) m (- m (* h 60)))
22338 (setq s2 (format "%02d:%02d" h m))))
22340 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22341 txt)
22342 ;; Tags are in the string
22343 (if (or (eq org-agenda-remove-tags t)
22344 (and org-agenda-remove-tags
22345 org-prefix-has-tag))
22346 (setq txt (replace-match "" t t txt))
22347 (setq txt (replace-match
22348 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22349 (match-string 2 txt))
22350 t t txt))))
22352 (when remove-re
22353 (while (string-match remove-re txt)
22354 (setq txt (replace-match "" t t txt))))
22356 ;; Create the final string
22357 (if noprefix
22358 (setq rtn txt)
22359 ;; Prepare the variables needed in the eval of the compiled format
22360 (setq time (cond (s2 (concat s1 "-" s2))
22361 (s1 (concat s1 "......"))
22362 (t ""))
22363 extra (or extra "")
22364 category (if (symbolp category) (symbol-name category) category))
22365 ;; Evaluate the compiled format
22366 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22368 ;; And finally add the text properties
22369 (org-add-props rtn nil
22370 'org-category (downcase category) 'tags tags
22371 'org-highest-priority org-highest-priority
22372 'org-lowest-priority org-lowest-priority
22373 'prefix-length (- (length rtn) (length txt))
22374 'time-of-day time-of-day
22375 'txt txt
22376 'time time
22377 'extra extra
22378 'dotime dotime))))
22380 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22381 (defvar org-agenda-sorting-strategy-selected nil)
22383 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22384 (catch 'exit
22385 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22386 ((and todayp (member 'today (car org-agenda-time-grid))))
22387 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22388 ((member 'weekly (car org-agenda-time-grid)))
22389 (t (throw 'exit list)))
22390 (let* ((have (delq nil (mapcar
22391 (lambda (x) (get-text-property 1 'time-of-day x))
22392 list)))
22393 (string (nth 1 org-agenda-time-grid))
22394 (gridtimes (nth 2 org-agenda-time-grid))
22395 (req (car org-agenda-time-grid))
22396 (remove (member 'remove-match req))
22397 new time)
22398 (if (and (member 'require-timed req) (not have))
22399 ;; don't show empty grid
22400 (throw 'exit list))
22401 (while (setq time (pop gridtimes))
22402 (unless (and remove (member time have))
22403 (setq time (int-to-string time))
22404 (push (org-format-agenda-item
22405 nil string "" nil
22406 (concat (substring time 0 -2) ":" (substring time -2)))
22407 new)
22408 (put-text-property
22409 1 (length (car new)) 'face 'org-time-grid (car new))))
22410 (if (member 'time-up org-agenda-sorting-strategy-selected)
22411 (append new list)
22412 (append list new)))))
22414 (defun org-compile-prefix-format (key)
22415 "Compile the prefix format into a Lisp form that can be evaluated.
22416 The resulting form is returned and stored in the variable
22417 `org-prefix-format-compiled'."
22418 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22419 (let ((s (cond
22420 ((stringp org-agenda-prefix-format)
22421 org-agenda-prefix-format)
22422 ((assq key org-agenda-prefix-format)
22423 (cdr (assq key org-agenda-prefix-format)))
22424 (t " %-12:c%?-12t% s")))
22425 (start 0)
22426 varform vars var e c f opt)
22427 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22428 s start)
22429 (setq var (cdr (assoc (match-string 4 s)
22430 '(("c" . category) ("t" . time) ("s" . extra)
22431 ("T" . tag))))
22432 c (or (match-string 3 s) "")
22433 opt (match-beginning 1)
22434 start (1+ (match-beginning 0)))
22435 (if (equal var 'time) (setq org-prefix-has-time t))
22436 (if (equal var 'tag) (setq org-prefix-has-tag t))
22437 (setq f (concat "%" (match-string 2 s) "s"))
22438 (if opt
22439 (setq varform
22440 `(if (equal "" ,var)
22442 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22443 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22444 (setq s (replace-match "%s" t nil s))
22445 (push varform vars))
22446 (setq vars (nreverse vars))
22447 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22449 (defun org-set-sorting-strategy (key)
22450 (if (symbolp (car org-agenda-sorting-strategy))
22451 ;; the old format
22452 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22453 (setq org-agenda-sorting-strategy-selected
22454 (or (cdr (assq key org-agenda-sorting-strategy))
22455 (cdr (assq 'agenda org-agenda-sorting-strategy))
22456 '(time-up category-keep priority-down)))))
22458 (defun org-get-time-of-day (s &optional string mod24)
22459 "Check string S for a time of day.
22460 If found, return it as a military time number between 0 and 2400.
22461 If not found, return nil.
22462 The optional STRING argument forces conversion into a 5 character wide string
22463 HH:MM."
22464 (save-match-data
22465 (when
22466 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22467 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22468 (let* ((h (string-to-number (match-string 1 s)))
22469 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22470 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22471 (am-p (equal ampm "am"))
22472 (h1 (cond ((not ampm) h)
22473 ((= h 12) (if am-p 0 12))
22474 (t (+ h (if am-p 0 12)))))
22475 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22476 (mod h1 24) h1))
22477 (t0 (+ (* 100 h2) m))
22478 (t1 (concat (if (>= h1 24) "+" " ")
22479 (if (< t0 100) "0" "")
22480 (if (< t0 10) "0" "")
22481 (int-to-string t0))))
22482 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22484 (defun org-finalize-agenda-entries (list &optional nosort)
22485 "Sort and concatenate the agenda items."
22486 (setq list (mapcar 'org-agenda-highlight-todo list))
22487 (if nosort
22488 list
22489 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22491 (defun org-agenda-highlight-todo (x)
22492 (let (re pl)
22493 (if (eq x 'line)
22494 (save-excursion
22495 (beginning-of-line 1)
22496 (setq re (get-text-property (point) 'org-todo-regexp))
22497 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22498 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22499 (add-text-properties (match-beginning 0) (match-end 0)
22500 (list 'face (org-get-todo-face 0)))
22501 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22502 (delete-region (match-beginning 1) (1- (match-end 0)))
22503 (goto-char (match-beginning 1))
22504 (insert (format org-agenda-todo-keyword-format s)))))
22505 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22506 pl (get-text-property 0 'prefix-length x))
22507 (when (and re
22508 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22509 x (or pl 0)) pl))
22510 (add-text-properties
22511 (or (match-end 1) (match-end 0)) (match-end 0)
22512 (list 'face (org-get-todo-face (match-string 2 x)))
22514 (setq x (concat (substring x 0 (match-end 1))
22515 (format org-agenda-todo-keyword-format
22516 (match-string 2 x))
22518 (substring x (match-end 3)))))
22519 x)))
22521 (defsubst org-cmp-priority (a b)
22522 "Compare the priorities of string A and B."
22523 (let ((pa (or (get-text-property 1 'priority a) 0))
22524 (pb (or (get-text-property 1 'priority b) 0)))
22525 (cond ((> pa pb) +1)
22526 ((< pa pb) -1)
22527 (t nil))))
22529 (defsubst org-cmp-category (a b)
22530 "Compare the string values of categories of strings A and B."
22531 (let ((ca (or (get-text-property 1 'org-category a) ""))
22532 (cb (or (get-text-property 1 'org-category b) "")))
22533 (cond ((string-lessp ca cb) -1)
22534 ((string-lessp cb ca) +1)
22535 (t nil))))
22537 (defsubst org-cmp-tag (a b)
22538 "Compare the string values of categories of strings A and B."
22539 (let ((ta (car (last (get-text-property 1 'tags a))))
22540 (tb (car (last (get-text-property 1 'tags b)))))
22541 (cond ((not ta) +1)
22542 ((not tb) -1)
22543 ((string-lessp ta tb) -1)
22544 ((string-lessp tb ta) +1)
22545 (t nil))))
22547 (defsubst org-cmp-time (a b)
22548 "Compare the time-of-day values of strings A and B."
22549 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22550 (ta (or (get-text-property 1 'time-of-day a) def))
22551 (tb (or (get-text-property 1 'time-of-day b) def)))
22552 (cond ((< ta tb) -1)
22553 ((< tb ta) +1)
22554 (t nil))))
22556 (defun org-entries-lessp (a b)
22557 "Predicate for sorting agenda entries."
22558 ;; The following variables will be used when the form is evaluated.
22559 ;; So even though the compiler complains, keep them.
22560 (let* ((time-up (org-cmp-time a b))
22561 (time-down (if time-up (- time-up) nil))
22562 (priority-up (org-cmp-priority a b))
22563 (priority-down (if priority-up (- priority-up) nil))
22564 (category-up (org-cmp-category a b))
22565 (category-down (if category-up (- category-up) nil))
22566 (category-keep (if category-up +1 nil))
22567 (tag-up (org-cmp-tag a b))
22568 (tag-down (if tag-up (- tag-up) nil)))
22569 (cdr (assoc
22570 (eval (cons 'or org-agenda-sorting-strategy-selected))
22571 '((-1 . t) (1 . nil) (nil . nil))))))
22573 ;;; Agenda restriction lock
22575 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22576 "Overlay to mark the headline to which arenda commands are restricted.")
22577 (org-overlay-put org-agenda-restriction-lock-overlay
22578 'face 'org-agenda-restriction-lock)
22579 (org-overlay-put org-agenda-restriction-lock-overlay
22580 'help-echo "Agendas are currently limited to this subtree.")
22581 (org-detach-overlay org-agenda-restriction-lock-overlay)
22582 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22583 "Overlay marking the agenda restriction line in speedbar.")
22584 (org-overlay-put org-speedbar-restriction-lock-overlay
22585 'face 'org-agenda-restriction-lock)
22586 (org-overlay-put org-speedbar-restriction-lock-overlay
22587 'help-echo "Agendas are currently limited to this item.")
22588 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22590 (defun org-agenda-set-restriction-lock (&optional type)
22591 "Set restriction lock for agenda, to current subtree or file.
22592 Restriction will be the file if TYPE is `file', or if type is the
22593 universal prefix '(4), or if the cursor is before the first headline
22594 in the file. Otherwise, restriction will be to the current subtree."
22595 (interactive "P")
22596 (and (equal type '(4)) (setq type 'file))
22597 (setq type (cond
22598 (type type)
22599 ((org-at-heading-p) 'subtree)
22600 ((condition-case nil (org-back-to-heading t) (error nil))
22601 'subtree)
22602 (t 'file)))
22603 (if (eq type 'subtree)
22604 (progn
22605 (setq org-agenda-restrict t)
22606 (setq org-agenda-overriding-restriction 'subtree)
22607 (put 'org-agenda-files 'org-restrict
22608 (list (buffer-file-name (buffer-base-buffer))))
22609 (org-back-to-heading t)
22610 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22611 (move-marker org-agenda-restrict-begin (point))
22612 (move-marker org-agenda-restrict-end
22613 (save-excursion (org-end-of-subtree t)))
22614 (message "Locking agenda restriction to subtree"))
22615 (put 'org-agenda-files 'org-restrict
22616 (list (buffer-file-name (buffer-base-buffer))))
22617 (setq org-agenda-restrict nil)
22618 (setq org-agenda-overriding-restriction 'file)
22619 (move-marker org-agenda-restrict-begin nil)
22620 (move-marker org-agenda-restrict-end nil)
22621 (message "Locking agenda restriction to file"))
22622 (setq current-prefix-arg nil)
22623 (org-agenda-maybe-redo))
22625 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22626 "Remove the agenda restriction lock."
22627 (interactive "P")
22628 (org-detach-overlay org-agenda-restriction-lock-overlay)
22629 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22630 (setq org-agenda-overriding-restriction nil)
22631 (setq org-agenda-restrict nil)
22632 (put 'org-agenda-files 'org-restrict nil)
22633 (move-marker org-agenda-restrict-begin nil)
22634 (move-marker org-agenda-restrict-end nil)
22635 (setq current-prefix-arg nil)
22636 (message "Agenda restriction lock removed")
22637 (or noupdate (org-agenda-maybe-redo)))
22639 (defun org-agenda-maybe-redo ()
22640 "If there is any window showing the agenda view, update it."
22641 (let ((w (get-buffer-window org-agenda-buffer-name t))
22642 (w0 (selected-window)))
22643 (when w
22644 (select-window w)
22645 (org-agenda-redo)
22646 (select-window w0)
22647 (if org-agenda-overriding-restriction
22648 (message "Agenda view shifted to new %s restriction"
22649 org-agenda-overriding-restriction)
22650 (message "Agenda restriction lock removed")))))
22652 ;;; Agenda commands
22654 (defun org-agenda-check-type (error &rest types)
22655 "Check if agenda buffer is of allowed type.
22656 If ERROR is non-nil, throw an error, otherwise just return nil."
22657 (if (memq org-agenda-type types)
22659 (if error
22660 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22661 nil)))
22663 (defun org-agenda-quit ()
22664 "Exit agenda by removing the window or the buffer."
22665 (interactive)
22666 (let ((buf (current-buffer)))
22667 (if (not (one-window-p)) (delete-window))
22668 (kill-buffer buf)
22669 (org-agenda-reset-markers)
22670 (org-columns-remove-overlays))
22671 ;; Maybe restore the pre-agenda window configuration.
22672 (and org-agenda-restore-windows-after-quit
22673 (not (eq org-agenda-window-setup 'other-frame))
22674 org-pre-agenda-window-conf
22675 (set-window-configuration org-pre-agenda-window-conf)))
22677 (defun org-agenda-exit ()
22678 "Exit agenda by removing the window or the buffer.
22679 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22680 Org-mode buffers visited directly by the user will not be touched."
22681 (interactive)
22682 (org-release-buffers org-agenda-new-buffers)
22683 (setq org-agenda-new-buffers nil)
22684 (org-agenda-quit))
22686 (defun org-agenda-execute (arg)
22687 "Execute another agenda command, keeping same window.\\<global-map>
22688 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22689 (interactive "P")
22690 (let ((org-agenda-window-setup 'current-window))
22691 (org-agenda arg)))
22693 (defun org-save-all-org-buffers ()
22694 "Save all Org-mode buffers without user confirmation."
22695 (interactive)
22696 (message "Saving all Org-mode buffers...")
22697 (save-some-buffers t 'org-mode-p)
22698 (message "Saving all Org-mode buffers... done"))
22700 (defun org-agenda-redo ()
22701 "Rebuild Agenda.
22702 When this is the global TODO list, a prefix argument will be interpreted."
22703 (interactive)
22704 (let* ((org-agenda-keep-modes t)
22705 (line (org-current-line))
22706 (window-line (- line (org-current-line (window-start))))
22707 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22708 (message "Rebuilding agenda buffer...")
22709 (org-let lprops '(eval org-agenda-redo-command))
22710 (setq org-agenda-undo-list nil
22711 org-agenda-pending-undo-list nil)
22712 (message "Rebuilding agenda buffer...done")
22713 (goto-line line)
22714 (recenter window-line)))
22716 (defun org-agenda-manipulate-query-add ()
22717 "Manipulate the query by adding a search term with positive selection.
22718 Positive selection means, the term must be matched for selection of an entry."
22719 (interactive)
22720 (org-agenda-manipulate-query ?\[))
22721 (defun org-agenda-manipulate-query-subtract ()
22722 "Manipulate the query by adding a search term with negative selection.
22723 Negative selection means, term must not be matched for selection of an entry."
22724 (interactive)
22725 (org-agenda-manipulate-query ?\]))
22726 (defun org-agenda-manipulate-query-add-re ()
22727 "Manipulate the query by adding a search regexp with positive selection.
22728 Positive selection means, the regexp must match for selection of an entry."
22729 (interactive)
22730 (org-agenda-manipulate-query ?\{))
22731 (defun org-agenda-manipulate-query-subtract-re ()
22732 "Manipulate the query by adding a search regexp with negative selection.
22733 Negative selection means, regexp must not match for selection of an entry."
22734 (interactive)
22735 (org-agenda-manipulate-query ?\}))
22736 (defun org-agenda-manipulate-query (char)
22737 (cond
22738 ((eq org-agenda-type 'search)
22739 (org-add-to-string
22740 'org-agenda-query-string
22741 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22742 (?\{ . " +{}") (?\} . " -{}")))))
22743 (setq org-agenda-redo-command
22744 (list 'org-search-view
22745 (+ (length org-agenda-query-string)
22746 (if (member char '(?\{ ?\})) 0 1))
22747 org-agenda-query-string))
22748 (set-register org-agenda-query-register org-agenda-query-string)
22749 (org-agenda-redo))
22750 (t (error "Canot manipulate query for %s-type agenda buffers"
22751 org-agenda-type))))
22753 (defun org-add-to-string (var string)
22754 (set var (concat (symbol-value var) string)))
22756 (defun org-agenda-goto-date (date)
22757 "Jump to DATE in agenda."
22758 (interactive (list (org-read-date)))
22759 (org-agenda-list nil date))
22761 (defun org-agenda-goto-today ()
22762 "Go to today."
22763 (interactive)
22764 (org-agenda-check-type t 'timeline 'agenda)
22765 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22766 (cond
22767 (tdpos (goto-char tdpos))
22768 ((eq org-agenda-type 'agenda)
22769 (let* ((sd (time-to-days
22770 (time-subtract (current-time)
22771 (list 0 (* 3600 org-extend-today-until) 0))))
22772 (comp (org-agenda-compute-time-span sd org-agenda-span))
22773 (org-agenda-overriding-arguments org-agenda-last-arguments))
22774 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22775 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22776 (org-agenda-redo)
22777 (org-agenda-find-same-or-today-or-agenda)))
22778 (t (error "Cannot find today")))))
22780 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22781 (goto-char
22782 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22783 (text-property-any (point-min) (point-max) 'org-today t)
22784 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22785 (point-min))))
22787 (defun org-agenda-later (arg)
22788 "Go forward in time by thee current span.
22789 With prefix ARG, go forward that many times the current span."
22790 (interactive "p")
22791 (org-agenda-check-type t 'agenda)
22792 (let* ((span org-agenda-span)
22793 (sd org-starting-day)
22794 (greg (calendar-gregorian-from-absolute sd))
22795 (cnt (get-text-property (point) 'org-day-cnt))
22796 greg2 nd)
22797 (cond
22798 ((eq span 'day)
22799 (setq sd (+ arg sd) nd 1))
22800 ((eq span 'week)
22801 (setq sd (+ (* 7 arg) sd) nd 7))
22802 ((eq span 'month)
22803 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22804 sd (calendar-absolute-from-gregorian greg2))
22805 (setcar greg2 (1+ (car greg2)))
22806 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22807 ((eq span 'year)
22808 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22809 sd (calendar-absolute-from-gregorian greg2))
22810 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22811 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22812 (let ((org-agenda-overriding-arguments
22813 (list (car org-agenda-last-arguments) sd nd t)))
22814 (org-agenda-redo)
22815 (org-agenda-find-same-or-today-or-agenda cnt))))
22817 (defun org-agenda-earlier (arg)
22818 "Go backward in time by the current span.
22819 With prefix ARG, go backward that many times the current span."
22820 (interactive "p")
22821 (org-agenda-later (- arg)))
22823 (defun org-agenda-day-view ()
22824 "Switch to daily view for agenda."
22825 (interactive)
22826 (setq org-agenda-ndays 1)
22827 (org-agenda-change-time-span 'day))
22828 (defun org-agenda-week-view ()
22829 "Switch to daily view for agenda."
22830 (interactive)
22831 (setq org-agenda-ndays 7)
22832 (org-agenda-change-time-span 'week))
22833 (defun org-agenda-month-view ()
22834 "Switch to daily view for agenda."
22835 (interactive)
22836 (org-agenda-change-time-span 'month))
22837 (defun org-agenda-year-view ()
22838 "Switch to daily view for agenda."
22839 (interactive)
22840 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22841 (org-agenda-change-time-span 'year)
22842 (error "Abort")))
22844 (defun org-agenda-change-time-span (span)
22845 "Change the agenda view to SPAN.
22846 SPAN may be `day', `week', `month', `year'."
22847 (org-agenda-check-type t 'agenda)
22848 (if (equal org-agenda-span span)
22849 (error "Viewing span is already \"%s\"" span))
22850 (let* ((sd (or (get-text-property (point) 'day)
22851 org-starting-day))
22852 (computed (org-agenda-compute-time-span sd span))
22853 (org-agenda-overriding-arguments
22854 (list (car org-agenda-last-arguments)
22855 (car computed) (cdr computed) t)))
22856 (org-agenda-redo)
22857 (org-agenda-find-same-or-today-or-agenda))
22858 (org-agenda-set-mode-name)
22859 (message "Switched to %s view" span))
22861 (defun org-agenda-compute-time-span (sd span)
22862 "Compute starting date and number of days for agenda.
22863 SPAN may be `day', `week', `month', `year'. The return value
22864 is a cons cell with the starting date and the number of days,
22865 so that the date SD will be in that range."
22866 (let* ((greg (calendar-gregorian-from-absolute sd))
22868 (cond
22869 ((eq span 'day)
22870 (setq nd 1))
22871 ((eq span 'week)
22872 (let* ((nt (calendar-day-of-week
22873 (calendar-gregorian-from-absolute sd)))
22874 (d (if org-agenda-start-on-weekday
22875 (- nt org-agenda-start-on-weekday)
22876 0)))
22877 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22878 (setq nd 7)))
22879 ((eq span 'month)
22880 (setq sd (calendar-absolute-from-gregorian
22881 (list (car greg) 1 (nth 2 greg)))
22882 nd (- (calendar-absolute-from-gregorian
22883 (list (1+ (car greg)) 1 (nth 2 greg)))
22884 sd)))
22885 ((eq span 'year)
22886 (setq sd (calendar-absolute-from-gregorian
22887 (list 1 1 (nth 2 greg)))
22888 nd (- (calendar-absolute-from-gregorian
22889 (list 1 1 (1+ (nth 2 greg))))
22890 sd))))
22891 (cons sd nd)))
22893 ;; FIXME: does not work if user makes date format that starts with a blank
22894 (defun org-agenda-next-date-line (&optional arg)
22895 "Jump to the next line indicating a date in agenda buffer."
22896 (interactive "p")
22897 (org-agenda-check-type t 'agenda 'timeline)
22898 (beginning-of-line 1)
22899 (if (looking-at "^\\S-") (forward-char 1))
22900 (if (not (re-search-forward "^\\S-" nil t arg))
22901 (progn
22902 (backward-char 1)
22903 (error "No next date after this line in this buffer")))
22904 (goto-char (match-beginning 0)))
22906 (defun org-agenda-previous-date-line (&optional arg)
22907 "Jump to the previous line indicating a date in agenda buffer."
22908 (interactive "p")
22909 (org-agenda-check-type t 'agenda 'timeline)
22910 (beginning-of-line 1)
22911 (if (not (re-search-backward "^\\S-" nil t arg))
22912 (error "No previous date before this line in this buffer")))
22914 ;; Initialize the highlight
22915 (defvar org-hl (org-make-overlay 1 1))
22916 (org-overlay-put org-hl 'face 'highlight)
22918 (defun org-highlight (begin end &optional buffer)
22919 "Highlight a region with overlay."
22920 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22921 org-hl begin end (or buffer (current-buffer))))
22923 (defun org-unhighlight ()
22924 "Detach overlay INDEX."
22925 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22927 ;; FIXME this is currently not used.
22928 (defun org-highlight-until-next-command (beg end &optional buffer)
22929 (org-highlight beg end buffer)
22930 (add-hook 'pre-command-hook 'org-unhighlight-once))
22931 (defun org-unhighlight-once ()
22932 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22933 (org-unhighlight))
22935 (defun org-agenda-follow-mode ()
22936 "Toggle follow mode in an agenda buffer."
22937 (interactive)
22938 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22939 (org-agenda-set-mode-name)
22940 (message "Follow mode is %s"
22941 (if org-agenda-follow-mode "on" "off")))
22943 (defun org-agenda-log-mode ()
22944 "Toggle log mode in an agenda buffer."
22945 (interactive)
22946 (org-agenda-check-type t 'agenda 'timeline)
22947 (setq org-agenda-show-log (not org-agenda-show-log))
22948 (org-agenda-set-mode-name)
22949 (org-agenda-redo)
22950 (message "Log mode is %s"
22951 (if org-agenda-show-log "on" "off")))
22953 (defun org-agenda-toggle-diary ()
22954 "Toggle diary inclusion in an agenda buffer."
22955 (interactive)
22956 (org-agenda-check-type t 'agenda)
22957 (setq org-agenda-include-diary (not org-agenda-include-diary))
22958 (org-agenda-redo)
22959 (org-agenda-set-mode-name)
22960 (message "Diary inclusion turned %s"
22961 (if org-agenda-include-diary "on" "off")))
22963 (defun org-agenda-toggle-time-grid ()
22964 "Toggle time grid in an agenda buffer."
22965 (interactive)
22966 (org-agenda-check-type t 'agenda)
22967 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
22968 (org-agenda-redo)
22969 (org-agenda-set-mode-name)
22970 (message "Time-grid turned %s"
22971 (if org-agenda-use-time-grid "on" "off")))
22973 (defun org-agenda-set-mode-name ()
22974 "Set the mode name to indicate all the small mode settings."
22975 (setq mode-name
22976 (concat "Org-Agenda"
22977 (if (equal org-agenda-ndays 1) " Day" "")
22978 (if (equal org-agenda-ndays 7) " Week" "")
22979 (if org-agenda-follow-mode " Follow" "")
22980 (if org-agenda-include-diary " Diary" "")
22981 (if org-agenda-use-time-grid " Grid" "")
22982 (if org-agenda-show-log " Log" "")))
22983 (force-mode-line-update))
22985 (defun org-agenda-post-command-hook ()
22986 (and (eolp) (not (bolp)) (backward-char 1))
22987 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
22988 (if (and org-agenda-follow-mode
22989 (get-text-property (point) 'org-marker))
22990 (org-agenda-show)))
22992 (defun org-agenda-show-priority ()
22993 "Show the priority of the current item.
22994 This priority is composed of the main priority given with the [#A] cookies,
22995 and by additional input from the age of a schedules or deadline entry."
22996 (interactive)
22997 (let* ((pri (get-text-property (point-at-bol) 'priority)))
22998 (message "Priority is %d" (if pri pri -1000))))
23000 (defun org-agenda-show-tags ()
23001 "Show the tags applicable to the current item."
23002 (interactive)
23003 (let* ((tags (get-text-property (point-at-bol) 'tags)))
23004 (if tags
23005 (message "Tags are :%s:"
23006 (org-no-properties (mapconcat 'identity tags ":")))
23007 (message "No tags associated with this line"))))
23009 (defun org-agenda-goto (&optional highlight)
23010 "Go to the Org-mode file which contains the item at point."
23011 (interactive)
23012 (let* ((marker (or (get-text-property (point) 'org-marker)
23013 (org-agenda-error)))
23014 (buffer (marker-buffer marker))
23015 (pos (marker-position marker)))
23016 (switch-to-buffer-other-window buffer)
23017 (widen)
23018 (goto-char pos)
23019 (when (org-mode-p)
23020 (org-show-context 'agenda)
23021 (save-excursion
23022 (and (outline-next-heading)
23023 (org-flag-heading nil)))) ; show the next heading
23024 (recenter (/ (window-height) 2))
23025 (run-hooks 'org-agenda-after-show-hook)
23026 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
23028 (defvar org-agenda-after-show-hook nil
23029 "Normal hook run after an item has been shown from the agenda.
23030 Point is in the buffer where the item originated.")
23032 (defun org-agenda-kill ()
23033 "Kill the entry or subtree belonging to the current agenda entry."
23034 (interactive)
23035 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23036 (let* ((marker (or (get-text-property (point) 'org-marker)
23037 (org-agenda-error)))
23038 (buffer (marker-buffer marker))
23039 (pos (marker-position marker))
23040 (type (get-text-property (point) 'type))
23041 dbeg dend (n 0) conf)
23042 (org-with-remote-undo buffer
23043 (with-current-buffer buffer
23044 (save-excursion
23045 (goto-char pos)
23046 (if (and (org-mode-p) (not (member type '("sexp"))))
23047 (setq dbeg (progn (org-back-to-heading t) (point))
23048 dend (org-end-of-subtree t t))
23049 (setq dbeg (point-at-bol)
23050 dend (min (point-max) (1+ (point-at-eol)))))
23051 (goto-char dbeg)
23052 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
23053 (setq conf (or (eq t org-agenda-confirm-kill)
23054 (and (numberp org-agenda-confirm-kill)
23055 (> n org-agenda-confirm-kill))))
23056 (and conf
23057 (not (y-or-n-p
23058 (format "Delete entry with %d lines in buffer \"%s\"? "
23059 n (buffer-name buffer))))
23060 (error "Abort"))
23061 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
23062 (with-current-buffer buffer (delete-region dbeg dend))
23063 (message "Agenda item and source killed"))))
23065 (defun org-agenda-archive ()
23066 "Kill the entry or subtree belonging to the current agenda entry."
23067 (interactive)
23068 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23069 (let* ((marker (or (get-text-property (point) 'org-marker)
23070 (org-agenda-error)))
23071 (buffer (marker-buffer marker))
23072 (pos (marker-position marker)))
23073 (org-with-remote-undo buffer
23074 (with-current-buffer buffer
23075 (if (org-mode-p)
23076 (save-excursion
23077 (goto-char pos)
23078 (org-remove-subtree-entries-from-agenda)
23079 (org-back-to-heading t)
23080 (org-archive-subtree))
23081 (error "Archiving works only in Org-mode files"))))))
23083 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
23084 "Remove all lines in the agenda that correspond to a given subtree.
23085 The subtree is the one in buffer BUF, starting at BEG and ending at END.
23086 If this information is not given, the function uses the tree at point."
23087 (let ((buf (or buf (current-buffer))) m p)
23088 (save-excursion
23089 (unless (and beg end)
23090 (org-back-to-heading t)
23091 (setq beg (point))
23092 (org-end-of-subtree t)
23093 (setq end (point)))
23094 (set-buffer (get-buffer org-agenda-buffer-name))
23095 (save-excursion
23096 (goto-char (point-max))
23097 (beginning-of-line 1)
23098 (while (not (bobp))
23099 (when (and (setq m (get-text-property (point) 'org-marker))
23100 (equal buf (marker-buffer m))
23101 (setq p (marker-position m))
23102 (>= p beg)
23103 (<= p end))
23104 (let ((inhibit-read-only t))
23105 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23106 (beginning-of-line 0))))))
23108 (defun org-agenda-open-link ()
23109 "Follow the link in the current line, if any."
23110 (interactive)
23111 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23112 (save-excursion
23113 (save-restriction
23114 (narrow-to-region (point-at-bol) (point-at-eol))
23115 (org-open-at-point))))
23117 (defun org-agenda-copy-local-variable (var)
23118 "Get a variable from a referenced buffer and install it here."
23119 (let ((m (get-text-property (point) 'org-marker)))
23120 (when (and m (buffer-live-p (marker-buffer m)))
23121 (org-set-local var (with-current-buffer (marker-buffer m)
23122 (symbol-value var))))))
23124 (defun org-agenda-switch-to (&optional delete-other-windows)
23125 "Go to the Org-mode file which contains the item at point."
23126 (interactive)
23127 (let* ((marker (or (get-text-property (point) 'org-marker)
23128 (org-agenda-error)))
23129 (buffer (marker-buffer marker))
23130 (pos (marker-position marker)))
23131 (switch-to-buffer buffer)
23132 (and delete-other-windows (delete-other-windows))
23133 (widen)
23134 (goto-char pos)
23135 (when (org-mode-p)
23136 (org-show-context 'agenda)
23137 (save-excursion
23138 (and (outline-next-heading)
23139 (org-flag-heading nil)))))) ; show the next heading
23141 (defun org-agenda-goto-mouse (ev)
23142 "Go to the Org-mode file which contains the item at the mouse click."
23143 (interactive "e")
23144 (mouse-set-point ev)
23145 (org-agenda-goto))
23147 (defun org-agenda-show ()
23148 "Display the Org-mode file which contains the item at point."
23149 (interactive)
23150 (let ((win (selected-window)))
23151 (org-agenda-goto t)
23152 (select-window win)))
23154 (defun org-agenda-recenter (arg)
23155 "Display the Org-mode file which contains the item at point and recenter."
23156 (interactive "P")
23157 (let ((win (selected-window)))
23158 (org-agenda-goto t)
23159 (recenter arg)
23160 (select-window win)))
23162 (defun org-agenda-show-mouse (ev)
23163 "Display the Org-mode file which contains the item at the mouse click."
23164 (interactive "e")
23165 (mouse-set-point ev)
23166 (org-agenda-show))
23168 (defun org-agenda-check-no-diary ()
23169 "Check if the entry is a diary link and abort if yes."
23170 (if (get-text-property (point) 'org-agenda-diary-link)
23171 (org-agenda-error)))
23173 (defun org-agenda-error ()
23174 (error "Command not allowed in this line"))
23176 (defun org-agenda-tree-to-indirect-buffer ()
23177 "Show the subtree corresponding to the current entry in an indirect buffer.
23178 This calls the command `org-tree-to-indirect-buffer' from the original
23179 Org-mode buffer.
23180 With numerical prefix arg ARG, go up to this level and then take that tree.
23181 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23182 dedicated frame)."
23183 (interactive)
23184 (org-agenda-check-no-diary)
23185 (let* ((marker (or (get-text-property (point) 'org-marker)
23186 (org-agenda-error)))
23187 (buffer (marker-buffer marker))
23188 (pos (marker-position marker)))
23189 (with-current-buffer buffer
23190 (save-excursion
23191 (goto-char pos)
23192 (call-interactively 'org-tree-to-indirect-buffer)))))
23194 (defvar org-last-heading-marker (make-marker)
23195 "Marker pointing to the headline that last changed its TODO state
23196 by a remote command from the agenda.")
23198 (defun org-agenda-todo-nextset ()
23199 "Switch TODO entry to next sequence."
23200 (interactive)
23201 (org-agenda-todo 'nextset))
23203 (defun org-agenda-todo-previousset ()
23204 "Switch TODO entry to previous sequence."
23205 (interactive)
23206 (org-agenda-todo 'previousset))
23208 (defun org-agenda-todo (&optional arg)
23209 "Cycle TODO state of line at point, also in Org-mode file.
23210 This changes the line at point, all other lines in the agenda referring to
23211 the same tree node, and the headline of the tree node in the Org-mode file."
23212 (interactive "P")
23213 (org-agenda-check-no-diary)
23214 (let* ((col (current-column))
23215 (marker (or (get-text-property (point) 'org-marker)
23216 (org-agenda-error)))
23217 (buffer (marker-buffer marker))
23218 (pos (marker-position marker))
23219 (hdmarker (get-text-property (point) 'org-hd-marker))
23220 (inhibit-read-only t)
23221 newhead)
23222 (org-with-remote-undo buffer
23223 (with-current-buffer buffer
23224 (widen)
23225 (goto-char pos)
23226 (org-show-context 'agenda)
23227 (save-excursion
23228 (and (outline-next-heading)
23229 (org-flag-heading nil))) ; show the next heading
23230 (org-todo arg)
23231 (and (bolp) (forward-char 1))
23232 (setq newhead (org-get-heading))
23233 (save-excursion
23234 (org-back-to-heading)
23235 (move-marker org-last-heading-marker (point))))
23236 (beginning-of-line 1)
23237 (save-excursion
23238 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23239 (move-to-column col))))
23241 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23242 "Change all lines in the agenda buffer which match HDMARKER.
23243 The new content of the line will be NEWHEAD (as modified by
23244 `org-format-agenda-item'). HDMARKER is checked with
23245 `equal' against all `org-hd-marker' text properties in the file.
23246 If FIXFACE is non-nil, the face of each item is modified acording to
23247 the new TODO state."
23248 (let* ((inhibit-read-only t)
23249 props m pl undone-face done-face finish new dotime cat tags)
23250 (save-excursion
23251 (goto-char (point-max))
23252 (beginning-of-line 1)
23253 (while (not finish)
23254 (setq finish (bobp))
23255 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23256 (equal m hdmarker))
23257 (setq props (text-properties-at (point))
23258 dotime (get-text-property (point) 'dotime)
23259 cat (get-text-property (point) 'org-category)
23260 tags (get-text-property (point) 'tags)
23261 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23262 pl (get-text-property (point) 'prefix-length)
23263 undone-face (get-text-property (point) 'undone-face)
23264 done-face (get-text-property (point) 'done-face))
23265 (move-to-column pl)
23266 (cond
23267 ((equal new "")
23268 (beginning-of-line 1)
23269 (and (looking-at ".*\n?") (replace-match "")))
23270 ((looking-at ".*")
23271 (replace-match new t t)
23272 (beginning-of-line 1)
23273 (add-text-properties (point-at-bol) (point-at-eol) props)
23274 (when fixface
23275 (add-text-properties
23276 (point-at-bol) (point-at-eol)
23277 (list 'face
23278 (if org-last-todo-state-is-todo
23279 undone-face done-face))))
23280 (org-agenda-highlight-todo 'line)
23281 (beginning-of-line 1))
23282 (t (error "Line update did not work"))))
23283 (beginning-of-line 0)))
23284 (org-finalize-agenda)))
23286 (defun org-agenda-align-tags (&optional line)
23287 "Align all tags in agenda items to `org-agenda-tags-column'."
23288 (let ((inhibit-read-only t) l c)
23289 (save-excursion
23290 (goto-char (if line (point-at-bol) (point-min)))
23291 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23292 (if line (point-at-eol) nil) t)
23293 (add-text-properties
23294 (match-beginning 2) (match-end 2)
23295 (list 'face (delq nil (list 'org-tag (get-text-property
23296 (match-beginning 2) 'face)))))
23297 (setq l (- (match-end 2) (match-beginning 2))
23298 c (if (< org-agenda-tags-column 0)
23299 (- (abs org-agenda-tags-column) l)
23300 org-agenda-tags-column))
23301 (delete-region (match-beginning 1) (match-end 1))
23302 (goto-char (match-beginning 1))
23303 (insert (org-add-props
23304 (make-string (max 1 (- c (current-column))) ?\ )
23305 (text-properties-at (point))))))))
23307 (defun org-agenda-priority-up ()
23308 "Increase the priority of line at point, also in Org-mode file."
23309 (interactive)
23310 (org-agenda-priority 'up))
23312 (defun org-agenda-priority-down ()
23313 "Decrease the priority of line at point, also in Org-mode file."
23314 (interactive)
23315 (org-agenda-priority 'down))
23317 (defun org-agenda-priority (&optional force-direction)
23318 "Set the priority of line at point, also in Org-mode file.
23319 This changes the line at point, all other lines in the agenda referring to
23320 the same tree node, and the headline of the tree node in the Org-mode file."
23321 (interactive)
23322 (org-agenda-check-no-diary)
23323 (let* ((marker (or (get-text-property (point) 'org-marker)
23324 (org-agenda-error)))
23325 (hdmarker (get-text-property (point) 'org-hd-marker))
23326 (buffer (marker-buffer hdmarker))
23327 (pos (marker-position hdmarker))
23328 (inhibit-read-only t)
23329 newhead)
23330 (org-with-remote-undo buffer
23331 (with-current-buffer buffer
23332 (widen)
23333 (goto-char pos)
23334 (org-show-context 'agenda)
23335 (save-excursion
23336 (and (outline-next-heading)
23337 (org-flag-heading nil))) ; show the next heading
23338 (funcall 'org-priority force-direction)
23339 (end-of-line 1)
23340 (setq newhead (org-get-heading)))
23341 (org-agenda-change-all-lines newhead hdmarker)
23342 (beginning-of-line 1))))
23344 (defun org-get-tags-at (&optional pos)
23345 "Get a list of all headline tags applicable at POS.
23346 POS defaults to point. If tags are inherited, the list contains
23347 the targets in the same sequence as the headlines appear, i.e.
23348 the tags of the current headline come last."
23349 (interactive)
23350 (let (tags lastpos)
23351 (save-excursion
23352 (save-restriction
23353 (widen)
23354 (goto-char (or pos (point)))
23355 (save-match-data
23356 (condition-case nil
23357 (progn
23358 (org-back-to-heading t)
23359 (while (not (equal lastpos (point)))
23360 (setq lastpos (point))
23361 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23362 (setq tags (append (org-split-string
23363 (org-match-string-no-properties 1) ":")
23364 tags)))
23365 (or org-use-tag-inheritance (error ""))
23366 (org-up-heading-all 1)))
23367 (error nil))))
23368 tags)))
23370 ;; FIXME: should fix the tags property of the agenda line.
23371 (defun org-agenda-set-tags ()
23372 "Set tags for the current headline."
23373 (interactive)
23374 (org-agenda-check-no-diary)
23375 (if (and (org-region-active-p) (interactive-p))
23376 (call-interactively 'org-change-tag-in-region)
23377 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23378 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23379 (org-agenda-error)))
23380 (buffer (marker-buffer hdmarker))
23381 (pos (marker-position hdmarker))
23382 (inhibit-read-only t)
23383 newhead)
23384 (org-with-remote-undo buffer
23385 (with-current-buffer buffer
23386 (widen)
23387 (goto-char pos)
23388 (save-excursion
23389 (org-show-context 'agenda))
23390 (save-excursion
23391 (and (outline-next-heading)
23392 (org-flag-heading nil))) ; show the next heading
23393 (goto-char pos)
23394 (call-interactively 'org-set-tags)
23395 (end-of-line 1)
23396 (setq newhead (org-get-heading)))
23397 (org-agenda-change-all-lines newhead hdmarker)
23398 (beginning-of-line 1)))))
23400 (defun org-agenda-toggle-archive-tag ()
23401 "Toggle the archive tag for the current entry."
23402 (interactive)
23403 (org-agenda-check-no-diary)
23404 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23405 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23406 (org-agenda-error)))
23407 (buffer (marker-buffer hdmarker))
23408 (pos (marker-position hdmarker))
23409 (inhibit-read-only t)
23410 newhead)
23411 (org-with-remote-undo buffer
23412 (with-current-buffer buffer
23413 (widen)
23414 (goto-char pos)
23415 (org-show-context 'agenda)
23416 (save-excursion
23417 (and (outline-next-heading)
23418 (org-flag-heading nil))) ; show the next heading
23419 (call-interactively 'org-toggle-archive-tag)
23420 (end-of-line 1)
23421 (setq newhead (org-get-heading)))
23422 (org-agenda-change-all-lines newhead hdmarker)
23423 (beginning-of-line 1))))
23425 (defun org-agenda-date-later (arg &optional what)
23426 "Change the date of this item to one day later."
23427 (interactive "p")
23428 (org-agenda-check-type t 'agenda 'timeline)
23429 (org-agenda-check-no-diary)
23430 (let* ((marker (or (get-text-property (point) 'org-marker)
23431 (org-agenda-error)))
23432 (buffer (marker-buffer marker))
23433 (pos (marker-position marker)))
23434 (org-with-remote-undo buffer
23435 (with-current-buffer buffer
23436 (widen)
23437 (goto-char pos)
23438 (if (not (org-at-timestamp-p))
23439 (error "Cannot find time stamp"))
23440 (org-timestamp-change arg (or what 'day)))
23441 (org-agenda-show-new-time marker org-last-changed-timestamp))
23442 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23444 (defun org-agenda-date-earlier (arg &optional what)
23445 "Change the date of this item to one day earlier."
23446 (interactive "p")
23447 (org-agenda-date-later (- arg) what))
23449 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23450 "Show new date stamp via text properties."
23451 ;; We use text properties to make this undoable
23452 (let ((inhibit-read-only t))
23453 (setq stamp (concat " " prefix " => " stamp))
23454 (save-excursion
23455 (goto-char (point-max))
23456 (while (not (bobp))
23457 (when (equal marker (get-text-property (point) 'org-marker))
23458 (move-to-column (- (window-width) (length stamp)) t)
23459 (if (featurep 'xemacs)
23460 ;; Use `duplicable' property to trigger undo recording
23461 (let ((ex (make-extent nil nil))
23462 (gl (make-glyph stamp)))
23463 (set-glyph-face gl 'secondary-selection)
23464 (set-extent-properties
23465 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23466 (insert-extent ex (1- (point)) (point-at-eol)))
23467 (add-text-properties
23468 (1- (point)) (point-at-eol)
23469 (list 'display (org-add-props stamp nil
23470 'face 'secondary-selection))))
23471 (beginning-of-line 1))
23472 (beginning-of-line 0)))))
23474 (defun org-agenda-date-prompt (arg)
23475 "Change the date of this item. Date is prompted for, with default today.
23476 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23477 be used to request time specification in the time stamp."
23478 (interactive "P")
23479 (org-agenda-check-type t 'agenda 'timeline)
23480 (org-agenda-check-no-diary)
23481 (let* ((marker (or (get-text-property (point) 'org-marker)
23482 (org-agenda-error)))
23483 (buffer (marker-buffer marker))
23484 (pos (marker-position marker)))
23485 (org-with-remote-undo buffer
23486 (with-current-buffer buffer
23487 (widen)
23488 (goto-char pos)
23489 (if (not (org-at-timestamp-p))
23490 (error "Cannot find time stamp"))
23491 (org-time-stamp arg)
23492 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23494 (defun org-agenda-schedule (arg)
23495 "Schedule the item at point."
23496 (interactive "P")
23497 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23498 (org-agenda-check-no-diary)
23499 (let* ((marker (or (get-text-property (point) 'org-marker)
23500 (org-agenda-error)))
23501 (type (marker-insertion-type marker))
23502 (buffer (marker-buffer marker))
23503 (pos (marker-position marker))
23504 (org-insert-labeled-timestamps-at-point nil)
23506 (when type (message "%s" type) (sit-for 3))
23507 (set-marker-insertion-type marker t)
23508 (org-with-remote-undo buffer
23509 (with-current-buffer buffer
23510 (widen)
23511 (goto-char pos)
23512 (setq ts (org-schedule arg)))
23513 (org-agenda-show-new-time marker ts "S"))
23514 (message "Item scheduled for %s" ts)))
23516 (defun org-agenda-deadline (arg)
23517 "Schedule the item at point."
23518 (interactive "P")
23519 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23520 (org-agenda-check-no-diary)
23521 (let* ((marker (or (get-text-property (point) 'org-marker)
23522 (org-agenda-error)))
23523 (buffer (marker-buffer marker))
23524 (pos (marker-position marker))
23525 (org-insert-labeled-timestamps-at-point nil)
23527 (org-with-remote-undo buffer
23528 (with-current-buffer buffer
23529 (widen)
23530 (goto-char pos)
23531 (setq ts (org-deadline arg)))
23532 (org-agenda-show-new-time marker ts "S"))
23533 (message "Deadline for this item set to %s" ts)))
23535 (defun org-get-heading (&optional no-tags)
23536 "Return the heading of the current entry, without the stars."
23537 (save-excursion
23538 (org-back-to-heading t)
23539 (if (looking-at
23540 (if no-tags
23541 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23542 "\\*+[ \t]+\\([^\r\n]*\\)"))
23543 (match-string 1) "")))
23545 (defun org-agenda-clock-in (&optional arg)
23546 "Start the clock on the currently selected item."
23547 (interactive "P")
23548 (org-agenda-check-no-diary)
23549 (let* ((marker (or (get-text-property (point) 'org-marker)
23550 (org-agenda-error)))
23551 (pos (marker-position marker)))
23552 (org-with-remote-undo (marker-buffer marker)
23553 (with-current-buffer (marker-buffer marker)
23554 (widen)
23555 (goto-char pos)
23556 (org-clock-in)))))
23558 (defun org-agenda-clock-out (&optional arg)
23559 "Stop the currently running clock."
23560 (interactive "P")
23561 (unless (marker-buffer org-clock-marker)
23562 (error "No running clock"))
23563 (org-with-remote-undo (marker-buffer org-clock-marker)
23564 (org-clock-out)))
23566 (defun org-agenda-clock-cancel (&optional arg)
23567 "Cancel the currently running clock."
23568 (interactive "P")
23569 (unless (marker-buffer org-clock-marker)
23570 (error "No running clock"))
23571 (org-with-remote-undo (marker-buffer org-clock-marker)
23572 (org-clock-cancel)))
23574 (defun org-agenda-diary-entry ()
23575 "Make a diary entry, like the `i' command from the calendar.
23576 All the standard commands work: block, weekly etc."
23577 (interactive)
23578 (org-agenda-check-type t 'agenda 'timeline)
23579 (require 'diary-lib)
23580 (let* ((char (progn
23581 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23582 (read-char-exclusive)))
23583 (cmd (cdr (assoc char
23584 '((?d . insert-diary-entry)
23585 (?w . insert-weekly-diary-entry)
23586 (?m . insert-monthly-diary-entry)
23587 (?y . insert-yearly-diary-entry)
23588 (?a . insert-anniversary-diary-entry)
23589 (?b . insert-block-diary-entry)
23590 (?c . insert-cyclic-diary-entry)))))
23591 (oldf (symbol-function 'calendar-cursor-to-date))
23592 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23593 (point (point))
23594 (mark (or (mark t) (point))))
23595 (unless cmd
23596 (error "No command associated with <%c>" char))
23597 (unless (and (get-text-property point 'day)
23598 (or (not (equal ?b char))
23599 (get-text-property mark 'day)))
23600 (error "Don't know which date to use for diary entry"))
23601 ;; We implement this by hacking the `calendar-cursor-to-date' function
23602 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23603 (let ((calendar-mark-ring
23604 (list (calendar-gregorian-from-absolute
23605 (or (get-text-property mark 'day)
23606 (get-text-property point 'day))))))
23607 (unwind-protect
23608 (progn
23609 (fset 'calendar-cursor-to-date
23610 (lambda (&optional error)
23611 (calendar-gregorian-from-absolute
23612 (get-text-property point 'day))))
23613 (call-interactively cmd))
23614 (fset 'calendar-cursor-to-date oldf)))))
23617 (defun org-agenda-execute-calendar-command (cmd)
23618 "Execute a calendar command from the agenda, with the date associated to
23619 the cursor position."
23620 (org-agenda-check-type t 'agenda 'timeline)
23621 (require 'diary-lib)
23622 (unless (get-text-property (point) 'day)
23623 (error "Don't know which date to use for calendar command"))
23624 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23625 (point (point))
23626 (date (calendar-gregorian-from-absolute
23627 (get-text-property point 'day)))
23628 ;; the following 3 vars are needed in the calendar
23629 (displayed-day (extract-calendar-day date))
23630 (displayed-month (extract-calendar-month date))
23631 (displayed-year (extract-calendar-year date)))
23632 (unwind-protect
23633 (progn
23634 (fset 'calendar-cursor-to-date
23635 (lambda (&optional error)
23636 (calendar-gregorian-from-absolute
23637 (get-text-property point 'day))))
23638 (call-interactively cmd))
23639 (fset 'calendar-cursor-to-date oldf))))
23641 (defun org-agenda-phases-of-moon ()
23642 "Display the phases of the moon for the 3 months around the cursor date."
23643 (interactive)
23644 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23646 (defun org-agenda-holidays ()
23647 "Display the holidays for the 3 months around the cursor date."
23648 (interactive)
23649 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23651 (defvar calendar-longitude)
23652 (defvar calendar-latitude)
23653 (defvar calendar-location-name)
23655 (defun org-agenda-sunrise-sunset (arg)
23656 "Display sunrise and sunset for the cursor date.
23657 Latitude and longitude can be specified with the variables
23658 `calendar-latitude' and `calendar-longitude'. When called with prefix
23659 argument, latitude and longitude will be prompted for."
23660 (interactive "P")
23661 (require 'solar)
23662 (let ((calendar-longitude (if arg nil calendar-longitude))
23663 (calendar-latitude (if arg nil calendar-latitude))
23664 (calendar-location-name
23665 (if arg "the given coordinates" calendar-location-name)))
23666 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23668 (defun org-agenda-goto-calendar ()
23669 "Open the Emacs calendar with the date at the cursor."
23670 (interactive)
23671 (org-agenda-check-type t 'agenda 'timeline)
23672 (let* ((day (or (get-text-property (point) 'day)
23673 (error "Don't know which date to open in calendar")))
23674 (date (calendar-gregorian-from-absolute day))
23675 (calendar-move-hook nil)
23676 (view-calendar-holidays-initially nil)
23677 (view-diary-entries-initially nil))
23678 (calendar)
23679 (calendar-goto-date date)))
23681 (defun org-calendar-goto-agenda ()
23682 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23683 This is a command that has to be installed in `calendar-mode-map'."
23684 (interactive)
23685 (org-agenda-list nil (calendar-absolute-from-gregorian
23686 (calendar-cursor-to-date))
23687 nil))
23689 (defun org-agenda-convert-date ()
23690 (interactive)
23691 (org-agenda-check-type t 'agenda 'timeline)
23692 (let ((day (get-text-property (point) 'day))
23693 date s)
23694 (unless day
23695 (error "Don't know which date to convert"))
23696 (setq date (calendar-gregorian-from-absolute day))
23697 (setq s (concat
23698 "Gregorian: " (calendar-date-string date) "\n"
23699 "ISO: " (calendar-iso-date-string date) "\n"
23700 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23701 "Julian: " (calendar-julian-date-string date) "\n"
23702 "Astron. JD: " (calendar-astro-date-string date)
23703 " (Julian date number at noon UTC)\n"
23704 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23705 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23706 "French: " (calendar-french-date-string date) "\n"
23707 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23708 "Mayan: " (calendar-mayan-date-string date) "\n"
23709 "Coptic: " (calendar-coptic-date-string date) "\n"
23710 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23711 "Persian: " (calendar-persian-date-string date) "\n"
23712 "Chinese: " (calendar-chinese-date-string date) "\n"))
23713 (with-output-to-temp-buffer "*Dates*"
23714 (princ s))
23715 (if (fboundp 'fit-window-to-buffer)
23716 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23719 ;;;; Embedded LaTeX
23721 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23722 "Keymap for the minor `org-cdlatex-mode'.")
23724 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23725 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23726 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23727 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23728 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23730 (defvar org-cdlatex-texmathp-advice-is-done nil
23731 "Flag remembering if we have applied the advice to texmathp already.")
23733 (define-minor-mode org-cdlatex-mode
23734 "Toggle the minor `org-cdlatex-mode'.
23735 This mode supports entering LaTeX environment and math in LaTeX fragments
23736 in Org-mode.
23737 \\{org-cdlatex-mode-map}"
23738 nil " OCDL" nil
23739 (when org-cdlatex-mode (require 'cdlatex))
23740 (unless org-cdlatex-texmathp-advice-is-done
23741 (setq org-cdlatex-texmathp-advice-is-done t)
23742 (defadvice texmathp (around org-math-always-on activate)
23743 "Always return t in org-mode buffers.
23744 This is because we want to insert math symbols without dollars even outside
23745 the LaTeX math segments. If Orgmode thinks that point is actually inside
23746 en embedded LaTeX fragement, let texmathp do its job.
23747 \\[org-cdlatex-mode-map]"
23748 (interactive)
23749 (let (p)
23750 (cond
23751 ((not (org-mode-p)) ad-do-it)
23752 ((eq this-command 'cdlatex-math-symbol)
23753 (setq ad-return-value t
23754 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23756 (let ((p (org-inside-LaTeX-fragment-p)))
23757 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23758 (setq ad-return-value t
23759 texmathp-why '("Org-mode embedded math" . 0))
23760 (if p ad-do-it)))))))))
23762 (defun turn-on-org-cdlatex ()
23763 "Unconditionally turn on `org-cdlatex-mode'."
23764 (org-cdlatex-mode 1))
23766 (defun org-inside-LaTeX-fragment-p ()
23767 "Test if point is inside a LaTeX fragment.
23768 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23769 sequence appearing also before point.
23770 Even though the matchers for math are configurable, this function assumes
23771 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23772 delimiters are skipped when they have been removed by customization.
23773 The return value is nil, or a cons cell with the delimiter and
23774 and the position of this delimiter.
23776 This function does a reasonably good job, but can locally be fooled by
23777 for example currency specifications. For example it will assume being in
23778 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23779 fragments that are properly closed, but during editing, we have to live
23780 with the uncertainty caused by missing closing delimiters. This function
23781 looks only before point, not after."
23782 (catch 'exit
23783 (let ((pos (point))
23784 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23785 (lim (progn
23786 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23787 (point)))
23788 dd-on str (start 0) m re)
23789 (goto-char pos)
23790 (when dodollar
23791 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23792 re (nth 1 (assoc "$" org-latex-regexps)))
23793 (while (string-match re str start)
23794 (cond
23795 ((= (match-end 0) (length str))
23796 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23797 ((= (match-end 0) (- (length str) 5))
23798 (throw 'exit nil))
23799 (t (setq start (match-end 0))))))
23800 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23801 (goto-char pos)
23802 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23803 (and (match-beginning 2) (throw 'exit nil))
23804 ;; count $$
23805 (while (re-search-backward "\\$\\$" lim t)
23806 (setq dd-on (not dd-on)))
23807 (goto-char pos)
23808 (if dd-on (cons "$$" m))))))
23811 (defun org-try-cdlatex-tab ()
23812 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23813 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23814 - inside a LaTeX fragment, or
23815 - after the first word in a line, where an abbreviation expansion could
23816 insert a LaTeX environment."
23817 (when org-cdlatex-mode
23818 (cond
23819 ((save-excursion
23820 (skip-chars-backward "a-zA-Z0-9*")
23821 (skip-chars-backward " \t")
23822 (bolp))
23823 (cdlatex-tab) t)
23824 ((org-inside-LaTeX-fragment-p)
23825 (cdlatex-tab) t)
23826 (t nil))))
23828 (defun org-cdlatex-underscore-caret (&optional arg)
23829 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23830 Revert to the normal definition outside of these fragments."
23831 (interactive "P")
23832 (if (org-inside-LaTeX-fragment-p)
23833 (call-interactively 'cdlatex-sub-superscript)
23834 (let (org-cdlatex-mode)
23835 (call-interactively (key-binding (vector last-input-event))))))
23837 (defun org-cdlatex-math-modify (&optional arg)
23838 "Execute `cdlatex-math-modify' in LaTeX fragments.
23839 Revert to the normal definition outside of these fragments."
23840 (interactive "P")
23841 (if (org-inside-LaTeX-fragment-p)
23842 (call-interactively 'cdlatex-math-modify)
23843 (let (org-cdlatex-mode)
23844 (call-interactively (key-binding (vector last-input-event))))))
23846 (defvar org-latex-fragment-image-overlays nil
23847 "List of overlays carrying the images of latex fragments.")
23848 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23850 (defun org-remove-latex-fragment-image-overlays ()
23851 "Remove all overlays with LaTeX fragment images in current buffer."
23852 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23853 (setq org-latex-fragment-image-overlays nil))
23855 (defun org-preview-latex-fragment (&optional subtree)
23856 "Preview the LaTeX fragment at point, or all locally or globally.
23857 If the cursor is in a LaTeX fragment, create the image and overlay
23858 it over the source code. If there is no fragment at point, display
23859 all fragments in the current text, from one headline to the next. With
23860 prefix SUBTREE, display all fragments in the current subtree. With a
23861 double prefix `C-u C-u', or when the cursor is before the first headline,
23862 display all fragments in the buffer.
23863 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23864 (interactive "P")
23865 (org-remove-latex-fragment-image-overlays)
23866 (save-excursion
23867 (save-restriction
23868 (let (beg end at msg)
23869 (cond
23870 ((or (equal subtree '(16))
23871 (not (save-excursion
23872 (re-search-backward (concat "^" outline-regexp) nil t))))
23873 (setq beg (point-min) end (point-max)
23874 msg "Creating images for buffer...%s"))
23875 ((equal subtree '(4))
23876 (org-back-to-heading)
23877 (setq beg (point) end (org-end-of-subtree t)
23878 msg "Creating images for subtree...%s"))
23880 (if (setq at (org-inside-LaTeX-fragment-p))
23881 (goto-char (max (point-min) (- (cdr at) 2)))
23882 (org-back-to-heading))
23883 (setq beg (point) end (progn (outline-next-heading) (point))
23884 msg (if at "Creating image...%s"
23885 "Creating images for entry...%s"))))
23886 (message msg "")
23887 (narrow-to-region beg end)
23888 (goto-char beg)
23889 (org-format-latex
23890 (concat "ltxpng/" (file-name-sans-extension
23891 (file-name-nondirectory
23892 buffer-file-name)))
23893 default-directory 'overlays msg at 'forbuffer)
23894 (message msg "done. Use `C-c C-c' to remove images.")))))
23896 (defvar org-latex-regexps
23897 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23898 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23899 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23900 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23901 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23902 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23903 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23904 "Regular expressions for matching embedded LaTeX.")
23906 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23907 "Replace LaTeX fragments with links to an image, and produce images."
23908 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23909 (let* ((prefixnodir (file-name-nondirectory prefix))
23910 (absprefix (expand-file-name prefix dir))
23911 (todir (file-name-directory absprefix))
23912 (opt org-format-latex-options)
23913 (matchers (plist-get opt :matchers))
23914 (re-list org-latex-regexps)
23915 (cnt 0) txt link beg end re e checkdir
23916 m n block linkfile movefile ov)
23917 ;; Check if there are old images files with this prefix, and remove them
23918 (when (file-directory-p todir)
23919 (mapc 'delete-file
23920 (directory-files
23921 todir 'full
23922 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23923 ;; Check the different regular expressions
23924 (while (setq e (pop re-list))
23925 (setq m (car e) re (nth 1 e) n (nth 2 e)
23926 block (if (nth 3 e) "\n\n" ""))
23927 (when (member m matchers)
23928 (goto-char (point-min))
23929 (while (re-search-forward re nil t)
23930 (when (or (not at) (equal (cdr at) (match-beginning n)))
23931 (setq txt (match-string n)
23932 beg (match-beginning n) end (match-end n)
23933 cnt (1+ cnt)
23934 linkfile (format "%s_%04d.png" prefix cnt)
23935 movefile (format "%s_%04d.png" absprefix cnt)
23936 link (concat block "[[file:" linkfile "]]" block))
23937 (if msg (message msg cnt))
23938 (goto-char beg)
23939 (unless checkdir ; make sure the directory exists
23940 (setq checkdir t)
23941 (or (file-directory-p todir) (make-directory todir)))
23942 (org-create-formula-image
23943 txt movefile opt forbuffer)
23944 (if overlays
23945 (progn
23946 (setq ov (org-make-overlay beg end))
23947 (if (featurep 'xemacs)
23948 (progn
23949 (org-overlay-put ov 'invisible t)
23950 (org-overlay-put
23951 ov 'end-glyph
23952 (make-glyph (vector 'png :file movefile))))
23953 (org-overlay-put
23954 ov 'display
23955 (list 'image :type 'png :file movefile :ascent 'center)))
23956 (push ov org-latex-fragment-image-overlays)
23957 (goto-char end))
23958 (delete-region beg end)
23959 (insert link))))))))
23961 ;; This function borrows from Ganesh Swami's latex2png.el
23962 (defun org-create-formula-image (string tofile options buffer)
23963 (let* ((tmpdir (if (featurep 'xemacs)
23964 (temp-directory)
23965 temporary-file-directory))
23966 (texfilebase (make-temp-name
23967 (expand-file-name "orgtex" tmpdir)))
23968 (texfile (concat texfilebase ".tex"))
23969 (dvifile (concat texfilebase ".dvi"))
23970 (pngfile (concat texfilebase ".png"))
23971 (fnh (face-attribute 'default :height nil))
23972 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
23973 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
23974 (fg (or (plist-get options (if buffer :foreground :html-foreground))
23975 "Black"))
23976 (bg (or (plist-get options (if buffer :background :html-background))
23977 "Transparent")))
23978 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
23979 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
23980 (with-temp-file texfile
23981 (insert org-format-latex-header
23982 "\n\\begin{document}\n" string "\n\\end{document}\n"))
23983 (let ((dir default-directory))
23984 (condition-case nil
23985 (progn
23986 (cd tmpdir)
23987 (call-process "latex" nil nil nil texfile))
23988 (error nil))
23989 (cd dir))
23990 (if (not (file-exists-p dvifile))
23991 (progn (message "Failed to create dvi file from %s" texfile) nil)
23992 (call-process "dvipng" nil nil nil
23993 "-E" "-fg" fg "-bg" bg
23994 "-D" dpi
23995 ;;"-x" scale "-y" scale
23996 "-T" "tight"
23997 "-o" pngfile
23998 dvifile)
23999 (if (not (file-exists-p pngfile))
24000 (progn (message "Failed to create png file from %s" texfile) nil)
24001 ;; Use the requested file name and clean up
24002 (copy-file pngfile tofile 'replace)
24003 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
24004 (delete-file (concat texfilebase e)))
24005 pngfile))))
24007 (defun org-dvipng-color (attr)
24008 "Return an rgb color specification for dvipng."
24009 (apply 'format "rgb %s %s %s"
24010 (mapcar 'org-normalize-color
24011 (color-values (face-attribute 'default attr nil)))))
24013 (defun org-normalize-color (value)
24014 "Return string to be used as color value for an RGB component."
24015 (format "%g" (/ value 65535.0)))
24017 ;;;; Exporting
24019 ;;; Variables, constants, and parameter plists
24021 (defconst org-level-max 20)
24023 (defvar org-export-html-preamble nil
24024 "Preamble, to be inserted just after <body>. Set by publishing functions.")
24025 (defvar org-export-html-postamble nil
24026 "Preamble, to be inserted just before </body>. Set by publishing functions.")
24027 (defvar org-export-html-auto-preamble t
24028 "Should default preamble be inserted? Set by publishing functions.")
24029 (defvar org-export-html-auto-postamble t
24030 "Should default postamble be inserted? Set by publishing functions.")
24031 (defvar org-current-export-file nil) ; dynamically scoped parameter
24032 (defvar org-current-export-dir nil) ; dynamically scoped parameter
24035 (defconst org-export-plist-vars
24036 '((:language . org-export-default-language)
24037 (:customtime . org-display-custom-times)
24038 (:headline-levels . org-export-headline-levels)
24039 (:section-numbers . org-export-with-section-numbers)
24040 (:table-of-contents . org-export-with-toc)
24041 (:preserve-breaks . org-export-preserve-breaks)
24042 (:archived-trees . org-export-with-archived-trees)
24043 (:emphasize . org-export-with-emphasize)
24044 (:sub-superscript . org-export-with-sub-superscripts)
24045 (:special-strings . org-export-with-special-strings)
24046 (:footnotes . org-export-with-footnotes)
24047 (:drawers . org-export-with-drawers)
24048 (:tags . org-export-with-tags)
24049 (:TeX-macros . org-export-with-TeX-macros)
24050 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
24051 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
24052 (:fixed-width . org-export-with-fixed-width)
24053 (:timestamps . org-export-with-timestamps)
24054 (:author-info . org-export-author-info)
24055 (:time-stamp-file . org-export-time-stamp-file)
24056 (:tables . org-export-with-tables)
24057 (:table-auto-headline . org-export-highlight-first-table-line)
24058 (:style . org-export-html-style)
24059 (:agenda-style . org-agenda-export-html-style)
24060 (:convert-org-links . org-export-html-link-org-files-as-html)
24061 (:inline-images . org-export-html-inline-images)
24062 (:html-extension . org-export-html-extension)
24063 (:html-table-tag . org-export-html-table-tag)
24064 (:expand-quoted-html . org-export-html-expand)
24065 (:timestamp . org-export-html-with-timestamp)
24066 (:publishing-directory . org-export-publishing-directory)
24067 (:preamble . org-export-html-preamble)
24068 (:postamble . org-export-html-postamble)
24069 (:auto-preamble . org-export-html-auto-preamble)
24070 (:auto-postamble . org-export-html-auto-postamble)
24071 (:author . user-full-name)
24072 (:email . user-mail-address)))
24074 (defun org-default-export-plist ()
24075 "Return the property list with default settings for the export variables."
24076 (let ((l org-export-plist-vars) rtn e)
24077 (while (setq e (pop l))
24078 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
24079 rtn))
24081 (defun org-infile-export-plist ()
24082 "Return the property list with file-local settings for export."
24083 (save-excursion
24084 (save-restriction
24085 (widen)
24086 (goto-char 0)
24087 (let ((re (org-make-options-regexp
24088 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
24089 p key val text options)
24090 (while (re-search-forward re nil t)
24091 (setq key (org-match-string-no-properties 1)
24092 val (org-match-string-no-properties 2))
24093 (cond
24094 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
24095 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
24096 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
24097 ((string-equal key "DATE") (setq p (plist-put p :date val)))
24098 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
24099 ((string-equal key "TEXT")
24100 (setq text (if text (concat text "\n" val) val)))
24101 ((string-equal key "OPTIONS") (setq options val))))
24102 (setq p (plist-put p :text text))
24103 (when options
24104 (let ((op '(("H" . :headline-levels)
24105 ("num" . :section-numbers)
24106 ("toc" . :table-of-contents)
24107 ("\\n" . :preserve-breaks)
24108 ("@" . :expand-quoted-html)
24109 (":" . :fixed-width)
24110 ("|" . :tables)
24111 ("^" . :sub-superscript)
24112 ("-" . :special-strings)
24113 ("f" . :footnotes)
24114 ("d" . :drawers)
24115 ("tags" . :tags)
24116 ("*" . :emphasize)
24117 ("TeX" . :TeX-macros)
24118 ("LaTeX" . :LaTeX-fragments)
24119 ("skip" . :skip-before-1st-heading)
24120 ("author" . :author-info)
24121 ("timestamp" . :time-stamp-file)))
24123 (while (setq o (pop op))
24124 (if (string-match (concat (regexp-quote (car o))
24125 ":\\([^ \t\n\r;,.]*\\)")
24126 options)
24127 (setq p (plist-put p (cdr o)
24128 (car (read-from-string
24129 (match-string 1 options)))))))))
24130 p))))
24132 (defun org-export-directory (type plist)
24133 (let* ((val (plist-get plist :publishing-directory))
24134 (dir (if (listp val)
24135 (or (cdr (assoc type val)) ".")
24136 val)))
24137 dir))
24139 (defun org-skip-comments (lines)
24140 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24141 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24142 (re2 "^\\(\\*+\\)[ \t\n\r]")
24143 (case-fold-search nil)
24144 rtn line level)
24145 (while (setq line (pop lines))
24146 (cond
24147 ((and (string-match re1 line)
24148 (setq level (- (match-end 1) (match-beginning 1))))
24149 ;; Beginning of a COMMENT subtree. Skip it.
24150 (while (and (setq line (pop lines))
24151 (or (not (string-match re2 line))
24152 (> (- (match-end 1) (match-beginning 1)) level))))
24153 (setq lines (cons line lines)))
24154 ((string-match "^#" line)
24155 ;; an ordinary comment line
24157 ((and org-export-table-remove-special-lines
24158 (string-match "^[ \t]*|" line)
24159 (or (string-match "^[ \t]*| *[!_^] *|" line)
24160 (and (string-match "| *<[0-9]+> *|" line)
24161 (not (string-match "| *[^ <|]" line)))))
24162 ;; a special table line that should be removed
24164 (t (setq rtn (cons line rtn)))))
24165 (nreverse rtn)))
24167 (defun org-export (&optional arg)
24168 (interactive)
24169 (let ((help "[t] insert the export option template
24170 \[v] limit export to visible part of outline tree
24172 \[a] export as ASCII
24174 \[h] export as HTML
24175 \[H] export as HTML to temporary buffer
24176 \[R] export region as HTML
24177 \[b] export as HTML and browse immediately
24178 \[x] export as XOXO
24180 \[l] export as LaTeX
24181 \[L] export as LaTeX to temporary buffer
24183 \[i] export current file as iCalendar file
24184 \[I] export all agenda files as iCalendar files
24185 \[c] export agenda files into combined iCalendar file
24187 \[F] publish current file
24188 \[P] publish current project
24189 \[X] publish... (project will be prompted for)
24190 \[A] publish all projects")
24191 (cmds
24192 '((?t . org-insert-export-options-template)
24193 (?v . org-export-visible)
24194 (?a . org-export-as-ascii)
24195 (?h . org-export-as-html)
24196 (?b . org-export-as-html-and-open)
24197 (?H . org-export-as-html-to-buffer)
24198 (?R . org-export-region-as-html)
24199 (?x . org-export-as-xoxo)
24200 (?l . org-export-as-latex)
24201 (?L . org-export-as-latex-to-buffer)
24202 (?i . org-export-icalendar-this-file)
24203 (?I . org-export-icalendar-all-agenda-files)
24204 (?c . org-export-icalendar-combine-agenda-files)
24205 (?F . org-publish-current-file)
24206 (?P . org-publish-current-project)
24207 (?X . org-publish)
24208 (?A . org-publish-all)))
24209 r1 r2 ass)
24210 (save-window-excursion
24211 (delete-other-windows)
24212 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24213 (princ help))
24214 (message "Select command: ")
24215 (setq r1 (read-char-exclusive)))
24216 (setq r2 (if (< r1 27) (+ r1 96) r1))
24217 (if (setq ass (assq r2 cmds))
24218 (call-interactively (cdr ass))
24219 (error "No command associated with key %c" r1))))
24221 (defconst org-html-entities
24222 '(("nbsp")
24223 ("iexcl")
24224 ("cent")
24225 ("pound")
24226 ("curren")
24227 ("yen")
24228 ("brvbar")
24229 ("vert" . "&#124;")
24230 ("sect")
24231 ("uml")
24232 ("copy")
24233 ("ordf")
24234 ("laquo")
24235 ("not")
24236 ("shy")
24237 ("reg")
24238 ("macr")
24239 ("deg")
24240 ("plusmn")
24241 ("sup2")
24242 ("sup3")
24243 ("acute")
24244 ("micro")
24245 ("para")
24246 ("middot")
24247 ("odot"."o")
24248 ("star"."*")
24249 ("cedil")
24250 ("sup1")
24251 ("ordm")
24252 ("raquo")
24253 ("frac14")
24254 ("frac12")
24255 ("frac34")
24256 ("iquest")
24257 ("Agrave")
24258 ("Aacute")
24259 ("Acirc")
24260 ("Atilde")
24261 ("Auml")
24262 ("Aring") ("AA"."&Aring;")
24263 ("AElig")
24264 ("Ccedil")
24265 ("Egrave")
24266 ("Eacute")
24267 ("Ecirc")
24268 ("Euml")
24269 ("Igrave")
24270 ("Iacute")
24271 ("Icirc")
24272 ("Iuml")
24273 ("ETH")
24274 ("Ntilde")
24275 ("Ograve")
24276 ("Oacute")
24277 ("Ocirc")
24278 ("Otilde")
24279 ("Ouml")
24280 ("times")
24281 ("Oslash")
24282 ("Ugrave")
24283 ("Uacute")
24284 ("Ucirc")
24285 ("Uuml")
24286 ("Yacute")
24287 ("THORN")
24288 ("szlig")
24289 ("agrave")
24290 ("aacute")
24291 ("acirc")
24292 ("atilde")
24293 ("auml")
24294 ("aring")
24295 ("aelig")
24296 ("ccedil")
24297 ("egrave")
24298 ("eacute")
24299 ("ecirc")
24300 ("euml")
24301 ("igrave")
24302 ("iacute")
24303 ("icirc")
24304 ("iuml")
24305 ("eth")
24306 ("ntilde")
24307 ("ograve")
24308 ("oacute")
24309 ("ocirc")
24310 ("otilde")
24311 ("ouml")
24312 ("divide")
24313 ("oslash")
24314 ("ugrave")
24315 ("uacute")
24316 ("ucirc")
24317 ("uuml")
24318 ("yacute")
24319 ("thorn")
24320 ("yuml")
24321 ("fnof")
24322 ("Alpha")
24323 ("Beta")
24324 ("Gamma")
24325 ("Delta")
24326 ("Epsilon")
24327 ("Zeta")
24328 ("Eta")
24329 ("Theta")
24330 ("Iota")
24331 ("Kappa")
24332 ("Lambda")
24333 ("Mu")
24334 ("Nu")
24335 ("Xi")
24336 ("Omicron")
24337 ("Pi")
24338 ("Rho")
24339 ("Sigma")
24340 ("Tau")
24341 ("Upsilon")
24342 ("Phi")
24343 ("Chi")
24344 ("Psi")
24345 ("Omega")
24346 ("alpha")
24347 ("beta")
24348 ("gamma")
24349 ("delta")
24350 ("epsilon")
24351 ("varepsilon"."&epsilon;")
24352 ("zeta")
24353 ("eta")
24354 ("theta")
24355 ("iota")
24356 ("kappa")
24357 ("lambda")
24358 ("mu")
24359 ("nu")
24360 ("xi")
24361 ("omicron")
24362 ("pi")
24363 ("rho")
24364 ("sigmaf") ("varsigma"."&sigmaf;")
24365 ("sigma")
24366 ("tau")
24367 ("upsilon")
24368 ("phi")
24369 ("chi")
24370 ("psi")
24371 ("omega")
24372 ("thetasym") ("vartheta"."&thetasym;")
24373 ("upsih")
24374 ("piv")
24375 ("bull") ("bullet"."&bull;")
24376 ("hellip") ("dots"."&hellip;")
24377 ("prime")
24378 ("Prime")
24379 ("oline")
24380 ("frasl")
24381 ("weierp")
24382 ("image")
24383 ("real")
24384 ("trade")
24385 ("alefsym")
24386 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24387 ("uarr") ("uparrow"."&uarr;")
24388 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24389 ("darr")("downarrow"."&darr;")
24390 ("harr") ("leftrightarrow"."&harr;")
24391 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24392 ("lArr") ("Leftarrow"."&lArr;")
24393 ("uArr") ("Uparrow"."&uArr;")
24394 ("rArr") ("Rightarrow"."&rArr;")
24395 ("dArr") ("Downarrow"."&dArr;")
24396 ("hArr") ("Leftrightarrow"."&hArr;")
24397 ("forall")
24398 ("part") ("partial"."&part;")
24399 ("exist") ("exists"."&exist;")
24400 ("empty") ("emptyset"."&empty;")
24401 ("nabla")
24402 ("isin") ("in"."&isin;")
24403 ("notin")
24404 ("ni")
24405 ("prod")
24406 ("sum")
24407 ("minus")
24408 ("lowast") ("ast"."&lowast;")
24409 ("radic")
24410 ("prop") ("proptp"."&prop;")
24411 ("infin") ("infty"."&infin;")
24412 ("ang") ("angle"."&ang;")
24413 ("and") ("wedge"."&and;")
24414 ("or") ("vee"."&or;")
24415 ("cap")
24416 ("cup")
24417 ("int")
24418 ("there4")
24419 ("sim")
24420 ("cong") ("simeq"."&cong;")
24421 ("asymp")("approx"."&asymp;")
24422 ("ne") ("neq"."&ne;")
24423 ("equiv")
24424 ("le")
24425 ("ge")
24426 ("sub") ("subset"."&sub;")
24427 ("sup") ("supset"."&sup;")
24428 ("nsub")
24429 ("sube")
24430 ("supe")
24431 ("oplus")
24432 ("otimes")
24433 ("perp")
24434 ("sdot") ("cdot"."&sdot;")
24435 ("lceil")
24436 ("rceil")
24437 ("lfloor")
24438 ("rfloor")
24439 ("lang")
24440 ("rang")
24441 ("loz") ("Diamond"."&loz;")
24442 ("spades") ("spadesuit"."&spades;")
24443 ("clubs") ("clubsuit"."&clubs;")
24444 ("hearts") ("diamondsuit"."&hearts;")
24445 ("diams") ("diamondsuit"."&diams;")
24446 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24447 ("quot")
24448 ("amp")
24449 ("lt")
24450 ("gt")
24451 ("OElig")
24452 ("oelig")
24453 ("Scaron")
24454 ("scaron")
24455 ("Yuml")
24456 ("circ")
24457 ("tilde")
24458 ("ensp")
24459 ("emsp")
24460 ("thinsp")
24461 ("zwnj")
24462 ("zwj")
24463 ("lrm")
24464 ("rlm")
24465 ("ndash")
24466 ("mdash")
24467 ("lsquo")
24468 ("rsquo")
24469 ("sbquo")
24470 ("ldquo")
24471 ("rdquo")
24472 ("bdquo")
24473 ("dagger")
24474 ("Dagger")
24475 ("permil")
24476 ("lsaquo")
24477 ("rsaquo")
24478 ("euro")
24480 ("arccos"."arccos")
24481 ("arcsin"."arcsin")
24482 ("arctan"."arctan")
24483 ("arg"."arg")
24484 ("cos"."cos")
24485 ("cosh"."cosh")
24486 ("cot"."cot")
24487 ("coth"."coth")
24488 ("csc"."csc")
24489 ("deg"."deg")
24490 ("det"."det")
24491 ("dim"."dim")
24492 ("exp"."exp")
24493 ("gcd"."gcd")
24494 ("hom"."hom")
24495 ("inf"."inf")
24496 ("ker"."ker")
24497 ("lg"."lg")
24498 ("lim"."lim")
24499 ("liminf"."liminf")
24500 ("limsup"."limsup")
24501 ("ln"."ln")
24502 ("log"."log")
24503 ("max"."max")
24504 ("min"."min")
24505 ("Pr"."Pr")
24506 ("sec"."sec")
24507 ("sin"."sin")
24508 ("sinh"."sinh")
24509 ("sup"."sup")
24510 ("tan"."tan")
24511 ("tanh"."tanh")
24513 "Entities for TeX->HTML translation.
24514 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24515 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24516 In that case, \"\\ent\" will be translated to \"&other;\".
24517 The list contains HTML entities for Latin-1, Greek and other symbols.
24518 It is supplemented by a number of commonly used TeX macros with appropriate
24519 translations. There is currently no way for users to extend this.")
24521 ;;; General functions for all backends
24523 (defun org-cleaned-string-for-export (string &rest parameters)
24524 "Cleanup a buffer STRING so that links can be created safely."
24525 (interactive)
24526 (let* ((re-radio (and org-target-link-regexp
24527 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24528 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24529 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24530 (re-archive (concat ":" org-archive-tag ":"))
24531 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24532 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24533 (htmlp (plist-get parameters :for-html))
24534 (asciip (plist-get parameters :for-ascii))
24535 (latexp (plist-get parameters :for-LaTeX))
24536 (commentsp (plist-get parameters :comments))
24537 (archived-trees (plist-get parameters :archived-trees))
24538 (inhibit-read-only t)
24539 (drawers org-drawers)
24540 (exp-drawers (plist-get parameters :drawers))
24541 (outline-regexp "\\*+ ")
24542 a b xx
24543 rtn p)
24544 (with-current-buffer (get-buffer-create " org-mode-tmp")
24545 (erase-buffer)
24546 (insert string)
24547 ;; Remove license-to-kill stuff
24548 (while (setq p (text-property-any (point-min) (point-max)
24549 :org-license-to-kill t))
24550 (delete-region p (next-single-property-change p :org-license-to-kill)))
24552 (let ((org-inhibit-startup t)) (org-mode))
24553 (untabify (point-min) (point-max))
24555 ;; Get rid of drawers
24556 (unless (eq t exp-drawers)
24557 (goto-char (point-min))
24558 (let ((re (concat "^[ \t]*:\\("
24559 (mapconcat
24560 'identity
24561 (org-delete-all exp-drawers
24562 (copy-sequence drawers))
24563 "\\|")
24564 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24565 (while (re-search-forward re nil t)
24566 (replace-match ""))))
24568 ;; Get the correct stuff before the first headline
24569 (when (plist-get parameters :skip-before-1st-heading)
24570 (goto-char (point-min))
24571 (when (re-search-forward "^\\*+[ \t]" nil t)
24572 (delete-region (point-min) (match-beginning 0))
24573 (goto-char (point-min))
24574 (insert "\n")))
24575 (when (plist-get parameters :add-text)
24576 (goto-char (point-min))
24577 (insert (plist-get parameters :add-text) "\n"))
24579 ;; Get rid of archived trees
24580 (when (not (eq archived-trees t))
24581 (goto-char (point-min))
24582 (while (re-search-forward re-archive nil t)
24583 (if (not (org-on-heading-p t))
24584 (org-end-of-subtree t)
24585 (beginning-of-line 1)
24586 (setq a (if archived-trees
24587 (1+ (point-at-eol)) (point))
24588 b (org-end-of-subtree t))
24589 (if (> b a) (delete-region a b)))))
24591 ;; Find targets in comments and move them out of comments,
24592 ;; but mark them as targets that should be invisible
24593 (goto-char (point-min))
24594 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24595 (replace-match "\\1(INVISIBLE)"))
24597 ;; Protect backend specific stuff, throw away the others.
24598 (let ((formatters
24599 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24600 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24601 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24602 fmt)
24603 (goto-char (point-min))
24604 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24605 (goto-char (match-end 0))
24606 (while (not (looking-at "#\\+END_EXAMPLE"))
24607 (insert ": ")
24608 (beginning-of-line 2)))
24609 (goto-char (point-min))
24610 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24611 (add-text-properties (match-beginning 0) (match-end 0)
24612 '(org-protected t)))
24613 (while formatters
24614 (setq fmt (pop formatters))
24615 (when (car fmt)
24616 (goto-char (point-min))
24617 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24618 ":[ \t]*\\(.*\\)") nil t)
24619 (replace-match "\\1" t)
24620 (add-text-properties
24621 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24622 '(org-protected t))))
24623 (goto-char (point-min))
24624 (while (re-search-forward
24625 (concat "^#\\+"
24626 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24627 (cadddr fmt) "\\>.*\n?") nil t)
24628 (if (car fmt)
24629 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24630 '(org-protected t))
24631 (delete-region (match-beginning 0) (match-end 0))))))
24633 ;; Protect quoted subtrees
24634 (goto-char (point-min))
24635 (while (re-search-forward re-quote nil t)
24636 (goto-char (match-beginning 0))
24637 (end-of-line 1)
24638 (add-text-properties (point) (org-end-of-subtree t)
24639 '(org-protected t)))
24641 ;; Protect verbatim elements
24642 (goto-char (point-min))
24643 (while (re-search-forward org-verbatim-re nil t)
24644 (add-text-properties (match-beginning 4) (match-end 4)
24645 '(org-protected t))
24646 (goto-char (1+ (match-end 4))))
24648 ;; Remove subtrees that are commented
24649 (goto-char (point-min))
24650 (while (re-search-forward re-commented nil t)
24651 (goto-char (match-beginning 0))
24652 (delete-region (point) (org-end-of-subtree t)))
24654 ;; Remove special table lines
24655 (when org-export-table-remove-special-lines
24656 (goto-char (point-min))
24657 (while (re-search-forward "^[ \t]*|" nil t)
24658 (beginning-of-line 1)
24659 (if (or (looking-at "[ \t]*| *[!_^] *|")
24660 (and (looking-at ".*?| *<[0-9]+> *|")
24661 (not (looking-at ".*?| *[^ <|]"))))
24662 (delete-region (max (point-min) (1- (point-at-bol)))
24663 (point-at-eol))
24664 (end-of-line 1))))
24666 ;; Specific LaTeX stuff
24667 (when latexp
24668 (require 'org-export-latex nil)
24669 (org-export-latex-cleaned-string))
24671 (when asciip
24672 (org-export-ascii-clean-string))
24674 ;; Specific HTML stuff
24675 (when htmlp
24676 ;; Convert LaTeX fragments to images
24677 (when (plist-get parameters :LaTeX-fragments)
24678 (org-format-latex
24679 (concat "ltxpng/" (file-name-sans-extension
24680 (file-name-nondirectory
24681 org-current-export-file)))
24682 org-current-export-dir nil "Creating LaTeX image %s"))
24683 (message "Exporting..."))
24685 ;; Remove or replace comments
24686 (goto-char (point-min))
24687 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24688 (if commentsp
24689 (progn (add-text-properties
24690 (match-beginning 0) (match-end 0) '(org-protected t))
24691 (replace-match (format commentsp (match-string 1)) t t))
24692 (replace-match "")))
24694 ;; Find matches for radio targets and turn them into internal links
24695 (goto-char (point-min))
24696 (when re-radio
24697 (while (re-search-forward re-radio nil t)
24698 (org-if-unprotected
24699 (replace-match "\\1[[\\2]]"))))
24701 ;; Find all links that contain a newline and put them into a single line
24702 (goto-char (point-min))
24703 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24704 (org-if-unprotected
24705 (replace-match "\\1 \\3")
24706 (goto-char (match-beginning 0))))
24709 ;; Normalize links: Convert angle and plain links into bracket links
24710 ;; Expand link abbreviations
24711 (goto-char (point-min))
24712 (while (re-search-forward re-plain-link nil t)
24713 (goto-char (1- (match-end 0)))
24714 (org-if-unprotected
24715 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24716 ":" (match-string 3) "]]")))
24717 ;; added 'org-link face to links
24718 (put-text-property 0 (length s) 'face 'org-link s)
24719 (replace-match s t t))))
24720 (goto-char (point-min))
24721 (while (re-search-forward re-angle-link nil t)
24722 (goto-char (1- (match-end 0)))
24723 (org-if-unprotected
24724 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24725 ":" (match-string 3) "]]")))
24726 (put-text-property 0 (length s) 'face 'org-link s)
24727 (replace-match s t t))))
24728 (goto-char (point-min))
24729 (while (re-search-forward org-bracket-link-regexp nil t)
24730 (org-if-unprotected
24731 (let* ((s (concat "[[" (setq xx (save-match-data
24732 (org-link-expand-abbrev (match-string 1))))
24734 (if (match-end 3)
24735 (match-string 2)
24736 (concat "[" xx "]"))
24737 "]")))
24738 (put-text-property 0 (length s) 'face 'org-link s)
24739 (replace-match s t t))))
24741 ;; Find multiline emphasis and put them into single line
24742 (when (plist-get parameters :emph-multiline)
24743 (goto-char (point-min))
24744 (while (re-search-forward org-emph-re nil t)
24745 (if (not (= (char-after (match-beginning 3))
24746 (char-after (match-beginning 4))))
24747 (org-if-unprotected
24748 (subst-char-in-region (match-beginning 0) (match-end 0)
24749 ?\n ?\ t)
24750 (goto-char (1- (match-end 0))))
24751 (goto-char (1+ (match-beginning 0))))))
24753 (setq rtn (buffer-string)))
24754 (kill-buffer " org-mode-tmp")
24755 rtn))
24757 (defun org-export-grab-title-from-buffer ()
24758 "Get a title for the current document, from looking at the buffer."
24759 (let ((inhibit-read-only t))
24760 (save-excursion
24761 (goto-char (point-min))
24762 (let ((end (save-excursion (outline-next-heading) (point))))
24763 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24764 ;; Mark the line so that it will not be exported as normal text.
24765 (org-unmodified
24766 (add-text-properties (match-beginning 0) (match-end 0)
24767 (list :org-license-to-kill t)))
24768 ;; Return the title string
24769 (org-trim (match-string 0)))))))
24771 (defun org-export-get-title-from-subtree ()
24772 "Return subtree title and exclude it from export."
24773 (let (title (m (mark)))
24774 (save-excursion
24775 (goto-char (region-beginning))
24776 (when (and (org-at-heading-p)
24777 (>= (org-end-of-subtree t t) (region-end)))
24778 ;; This is a subtree, we take the title from the first heading
24779 (goto-char (region-beginning))
24780 (looking-at org-todo-line-regexp)
24781 (setq title (match-string 3))
24782 (org-unmodified
24783 (add-text-properties (point) (1+ (point-at-eol))
24784 (list :org-license-to-kill t)))))
24785 title))
24787 (defun org-solidify-link-text (s &optional alist)
24788 "Take link text and make a safe target out of it."
24789 (save-match-data
24790 (let* ((rtn
24791 (mapconcat
24792 'identity
24793 (org-split-string s "[ \t\r\n]+") "--"))
24794 (a (assoc rtn alist)))
24795 (or (cdr a) rtn))))
24797 (defun org-get-min-level (lines)
24798 "Get the minimum level in LINES."
24799 (let ((re "^\\(\\*+\\) ") l min)
24800 (catch 'exit
24801 (while (setq l (pop lines))
24802 (if (string-match re l)
24803 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24804 1)))
24806 ;; Variable holding the vector with section numbers
24807 (defvar org-section-numbers (make-vector org-level-max 0))
24809 (defun org-init-section-numbers ()
24810 "Initialize the vector for the section numbers."
24811 (let* ((level -1)
24812 (numbers (nreverse (org-split-string "" "\\.")))
24813 (depth (1- (length org-section-numbers)))
24814 (i depth) number-string)
24815 (while (>= i 0)
24816 (if (> i level)
24817 (aset org-section-numbers i 0)
24818 (setq number-string (or (car numbers) "0"))
24819 (if (string-match "\\`[A-Z]\\'" number-string)
24820 (aset org-section-numbers i
24821 (- (string-to-char number-string) ?A -1))
24822 (aset org-section-numbers i (string-to-number number-string)))
24823 (pop numbers))
24824 (setq i (1- i)))))
24826 (defun org-section-number (&optional level)
24827 "Return a string with the current section number.
24828 When LEVEL is non-nil, increase section numbers on that level."
24829 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24830 (when level
24831 (when (> level -1)
24832 (aset org-section-numbers
24833 level (1+ (aref org-section-numbers level))))
24834 (setq idx (1+ level))
24835 (while (<= idx depth)
24836 (if (not (= idx 1))
24837 (aset org-section-numbers idx 0))
24838 (setq idx (1+ idx))))
24839 (setq idx 0)
24840 (while (<= idx depth)
24841 (setq n (aref org-section-numbers idx))
24842 (setq string (concat string (if (not (string= string "")) "." "")
24843 (int-to-string n)))
24844 (setq idx (1+ idx)))
24845 (save-match-data
24846 (if (string-match "\\`\\([@0]\\.\\)+" string)
24847 (setq string (replace-match "" t nil string)))
24848 (if (string-match "\\(\\.0\\)+\\'" string)
24849 (setq string (replace-match "" t nil string))))
24850 string))
24852 ;;; ASCII export
24854 (defvar org-last-level nil) ; dynamically scoped variable
24855 (defvar org-min-level nil) ; dynamically scoped variable
24856 (defvar org-levels-open nil) ; dynamically scoped parameter
24857 (defvar org-ascii-current-indentation nil) ; For communication
24859 (defun org-export-as-ascii (arg)
24860 "Export the outline as a pretty ASCII file.
24861 If there is an active region, export only the region.
24862 The prefix ARG specifies how many levels of the outline should become
24863 underlined headlines. The default is 3."
24864 (interactive "P")
24865 (setq-default org-todo-line-regexp org-todo-line-regexp)
24866 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24867 (org-infile-export-plist)))
24868 (region-p (org-region-active-p))
24869 (subtree-p
24870 (when region-p
24871 (save-excursion
24872 (goto-char (region-beginning))
24873 (and (org-at-heading-p)
24874 (>= (org-end-of-subtree t t) (region-end))))))
24875 (custom-times org-display-custom-times)
24876 (org-ascii-current-indentation '(0 . 0))
24877 (level 0) line txt
24878 (umax nil)
24879 (umax-toc nil)
24880 (case-fold-search nil)
24881 (filename (concat (file-name-as-directory
24882 (org-export-directory :ascii opt-plist))
24883 (file-name-sans-extension
24884 (or (and subtree-p
24885 (org-entry-get (region-beginning)
24886 "EXPORT_FILE_NAME" t))
24887 (file-name-nondirectory buffer-file-name)))
24888 ".txt"))
24889 (filename (if (equal (file-truename filename)
24890 (file-truename buffer-file-name))
24891 (concat filename ".txt")
24892 filename))
24893 (buffer (find-file-noselect filename))
24894 (org-levels-open (make-vector org-level-max nil))
24895 (odd org-odd-levels-only)
24896 (date (plist-get opt-plist :date))
24897 (author (plist-get opt-plist :author))
24898 (title (or (and subtree-p (org-export-get-title-from-subtree))
24899 (plist-get opt-plist :title)
24900 (and (not
24901 (plist-get opt-plist :skip-before-1st-heading))
24902 (org-export-grab-title-from-buffer))
24903 (file-name-sans-extension
24904 (file-name-nondirectory buffer-file-name))))
24905 (email (plist-get opt-plist :email))
24906 (language (plist-get opt-plist :language))
24907 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24908 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24909 (todo nil)
24910 (lang-words nil)
24911 (region
24912 (buffer-substring
24913 (if (org-region-active-p) (region-beginning) (point-min))
24914 (if (org-region-active-p) (region-end) (point-max))))
24915 (lines (org-split-string
24916 (org-cleaned-string-for-export
24917 region
24918 :for-ascii t
24919 :skip-before-1st-heading
24920 (plist-get opt-plist :skip-before-1st-heading)
24921 :drawers (plist-get opt-plist :drawers)
24922 :verbatim-multiline t
24923 :archived-trees
24924 (plist-get opt-plist :archived-trees)
24925 :add-text (plist-get opt-plist :text))
24926 "\n"))
24927 thetoc have-headings first-heading-pos
24928 table-open table-buffer)
24930 (let ((inhibit-read-only t))
24931 (org-unmodified
24932 (remove-text-properties (point-min) (point-max)
24933 '(:org-license-to-kill t))))
24935 (setq org-min-level (org-get-min-level lines))
24936 (setq org-last-level org-min-level)
24937 (org-init-section-numbers)
24939 (find-file-noselect filename)
24941 (setq lang-words (or (assoc language org-export-language-setup)
24942 (assoc "en" org-export-language-setup)))
24943 (switch-to-buffer-other-window buffer)
24944 (erase-buffer)
24945 (fundamental-mode)
24946 ;; create local variables for all options, to make sure all called
24947 ;; functions get the correct information
24948 (mapc (lambda (x)
24949 (set (make-local-variable (cdr x))
24950 (plist-get opt-plist (car x))))
24951 org-export-plist-vars)
24952 (org-set-local 'org-odd-levels-only odd)
24953 (setq umax (if arg (prefix-numeric-value arg)
24954 org-export-headline-levels))
24955 (setq umax-toc (if (integerp org-export-with-toc)
24956 (min org-export-with-toc umax)
24957 umax))
24959 ;; File header
24960 (if title (org-insert-centered title ?=))
24961 (insert "\n")
24962 (if (and (or author email)
24963 org-export-author-info)
24964 (insert (concat (nth 1 lang-words) ": " (or author "")
24965 (if email (concat " <" email ">") "")
24966 "\n")))
24968 (cond
24969 ((and date (string-match "%" date))
24970 (setq date (format-time-string date (current-time))))
24971 (date)
24972 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
24974 (if (and date org-export-time-stamp-file)
24975 (insert (concat (nth 2 lang-words) ": " date"\n")))
24977 (insert "\n\n")
24979 (if org-export-with-toc
24980 (progn
24981 (push (concat (nth 3 lang-words) "\n") thetoc)
24982 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
24983 (mapc '(lambda (line)
24984 (if (string-match org-todo-line-regexp
24985 line)
24986 ;; This is a headline
24987 (progn
24988 (setq have-headings t)
24989 (setq level (- (match-end 1) (match-beginning 1))
24990 level (org-tr-level level)
24991 txt (match-string 3 line)
24992 todo
24993 (or (and org-export-mark-todo-in-toc
24994 (match-beginning 2)
24995 (not (member (match-string 2 line)
24996 org-done-keywords)))
24997 ; TODO, not DONE
24998 (and org-export-mark-todo-in-toc
24999 (= level umax-toc)
25000 (org-search-todo-below
25001 line lines level))))
25002 (setq txt (org-html-expand-for-ascii txt))
25004 (while (string-match org-bracket-link-regexp txt)
25005 (setq txt
25006 (replace-match
25007 (match-string (if (match-end 2) 3 1) txt)
25008 t t txt)))
25010 (if (and (memq org-export-with-tags '(not-in-toc nil))
25011 (string-match
25012 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
25013 txt))
25014 (setq txt (replace-match "" t t txt)))
25015 (if (string-match quote-re0 txt)
25016 (setq txt (replace-match "" t t txt)))
25018 (if org-export-with-section-numbers
25019 (setq txt (concat (org-section-number level)
25020 " " txt)))
25021 (if (<= level umax-toc)
25022 (progn
25023 (push
25024 (concat
25025 (make-string
25026 (* (max 0 (- level org-min-level)) 4) ?\ )
25027 (format (if todo "%s (*)\n" "%s\n") txt))
25028 thetoc)
25029 (setq org-last-level level))
25030 ))))
25031 lines)
25032 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25034 (org-init-section-numbers)
25035 (while (setq line (pop lines))
25036 ;; Remove the quoted HTML tags.
25037 (setq line (org-html-expand-for-ascii line))
25038 ;; Remove targets
25039 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
25040 (setq line (replace-match "" t t line)))
25041 ;; Replace internal links
25042 (while (string-match org-bracket-link-regexp line)
25043 (setq line (replace-match
25044 (if (match-end 3) "[\\3]" "[\\1]")
25045 t nil line)))
25046 (when custom-times
25047 (setq line (org-translate-time line)))
25048 (cond
25049 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25050 ;; a Headline
25051 (setq first-heading-pos (or first-heading-pos (point)))
25052 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25053 txt (match-string 2 line))
25054 (org-ascii-level-start level txt umax lines))
25056 ((and org-export-with-tables
25057 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25058 (if (not table-open)
25059 ;; New table starts
25060 (setq table-open t table-buffer nil))
25061 ;; Accumulate lines
25062 (setq table-buffer (cons line table-buffer))
25063 (when (or (not lines)
25064 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25065 (car lines))))
25066 (setq table-open nil
25067 table-buffer (nreverse table-buffer))
25068 (insert (mapconcat
25069 (lambda (x)
25070 (org-fix-indentation x org-ascii-current-indentation))
25071 (org-format-table-ascii table-buffer)
25072 "\n") "\n")))
25074 (setq line (org-fix-indentation line org-ascii-current-indentation))
25075 (if (and org-export-with-fixed-width
25076 (string-match "^\\([ \t]*\\)\\(:\\)" line))
25077 (setq line (replace-match "\\1" nil nil line)))
25078 (insert line "\n"))))
25080 (normal-mode)
25082 ;; insert the table of contents
25083 (when thetoc
25084 (goto-char (point-min))
25085 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
25086 (progn
25087 (goto-char (match-beginning 0))
25088 (replace-match ""))
25089 (goto-char first-heading-pos))
25090 (mapc 'insert thetoc)
25091 (or (looking-at "[ \t]*\n[ \t]*\n")
25092 (insert "\n\n")))
25094 ;; Convert whitespace place holders
25095 (goto-char (point-min))
25096 (let (beg end)
25097 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25098 (setq end (next-single-property-change beg 'org-whitespace))
25099 (goto-char beg)
25100 (delete-region beg end)
25101 (insert (make-string (- end beg) ?\ ))))
25103 (save-buffer)
25104 ;; remove display and invisible chars
25105 (let (beg end)
25106 (goto-char (point-min))
25107 (while (setq beg (next-single-property-change (point) 'display))
25108 (setq end (next-single-property-change beg 'display))
25109 (delete-region beg end)
25110 (goto-char beg)
25111 (insert "=>"))
25112 (goto-char (point-min))
25113 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25114 (setq end (next-single-property-change beg 'org-cwidth))
25115 (delete-region beg end)
25116 (goto-char beg)))
25117 (goto-char (point-min))))
25119 (defun org-export-ascii-clean-string ()
25120 "Do extra work for ASCII export"
25121 (goto-char (point-min))
25122 (while (re-search-forward org-verbatim-re nil t)
25123 (goto-char (match-end 2))
25124 (backward-delete-char 1) (insert "'")
25125 (goto-char (match-beginning 2))
25126 (delete-char 1) (insert "`")
25127 (goto-char (match-end 2))))
25129 (defun org-search-todo-below (line lines level)
25130 "Search the subtree below LINE for any TODO entries."
25131 (let ((rest (cdr (memq line lines)))
25132 (re org-todo-line-regexp)
25133 line lv todo)
25134 (catch 'exit
25135 (while (setq line (pop rest))
25136 (if (string-match re line)
25137 (progn
25138 (setq lv (- (match-end 1) (match-beginning 1))
25139 todo (and (match-beginning 2)
25140 (not (member (match-string 2 line)
25141 org-done-keywords))))
25142 ; TODO, not DONE
25143 (if (<= lv level) (throw 'exit nil))
25144 (if todo (throw 'exit t))))))))
25146 (defun org-html-expand-for-ascii (line)
25147 "Handle quoted HTML for ASCII export."
25148 (if org-export-html-expand
25149 (while (string-match "@<[^<>\n]*>" line)
25150 ;; We just remove the tags for now.
25151 (setq line (replace-match "" nil nil line))))
25152 line)
25154 (defun org-insert-centered (s &optional underline)
25155 "Insert the string S centered and underline it with character UNDERLINE."
25156 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25157 (insert (make-string ind ?\ ) s "\n")
25158 (if underline
25159 (insert (make-string ind ?\ )
25160 (make-string (string-width s) underline)
25161 "\n"))))
25163 (defun org-ascii-level-start (level title umax &optional lines)
25164 "Insert a new level in ASCII export."
25165 (let (char (n (- level umax 1)) (ind 0))
25166 (if (> level umax)
25167 (progn
25168 (insert (make-string (* 2 n) ?\ )
25169 (char-to-string (nth (% n (length org-export-ascii-bullets))
25170 org-export-ascii-bullets))
25171 " " title "\n")
25172 ;; find the indentation of the next non-empty line
25173 (catch 'stop
25174 (while lines
25175 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25176 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25177 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25178 (pop lines)))
25179 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25180 (if (or (not (equal (char-before) ?\n))
25181 (not (equal (char-before (1- (point))) ?\n)))
25182 (insert "\n"))
25183 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25184 (unless org-export-with-tags
25185 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25186 (setq title (replace-match "" t t title))))
25187 (if org-export-with-section-numbers
25188 (setq title (concat (org-section-number level) " " title)))
25189 (insert title "\n" (make-string (string-width title) char) "\n")
25190 (setq org-ascii-current-indentation '(0 . 0)))))
25192 (defun org-export-visible (type arg)
25193 "Create a copy of the visible part of the current buffer, and export it.
25194 The copy is created in a temporary buffer and removed after use.
25195 TYPE is the final key (as a string) that also select the export command in
25196 the `C-c C-e' export dispatcher.
25197 As a special case, if the you type SPC at the prompt, the temporary
25198 org-mode file will not be removed but presented to you so that you can
25199 continue to use it. The prefix arg ARG is passed through to the exporting
25200 command."
25201 (interactive
25202 (list (progn
25203 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25204 (read-char-exclusive))
25205 current-prefix-arg))
25206 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25207 (error "Invalid export key"))
25208 (let* ((binding (cdr (assoc type
25209 '((?a . org-export-as-ascii)
25210 (?\C-a . org-export-as-ascii)
25211 (?b . org-export-as-html-and-open)
25212 (?\C-b . org-export-as-html-and-open)
25213 (?h . org-export-as-html)
25214 (?H . org-export-as-html-to-buffer)
25215 (?R . org-export-region-as-html)
25216 (?x . org-export-as-xoxo)))))
25217 (keepp (equal type ?\ ))
25218 (file buffer-file-name)
25219 (buffer (get-buffer-create "*Org Export Visible*"))
25220 s e)
25221 ;; Need to hack the drawers here.
25222 (save-excursion
25223 (goto-char (point-min))
25224 (while (re-search-forward org-drawer-regexp nil t)
25225 (goto-char (match-beginning 1))
25226 (or (org-invisible-p) (org-flag-drawer nil))))
25227 (with-current-buffer buffer (erase-buffer))
25228 (save-excursion
25229 (setq s (goto-char (point-min)))
25230 (while (not (= (point) (point-max)))
25231 (goto-char (org-find-invisible))
25232 (append-to-buffer buffer s (point))
25233 (setq s (goto-char (org-find-visible))))
25234 (org-cycle-hide-drawers 'all)
25235 (goto-char (point-min))
25236 (unless keepp
25237 ;; Copy all comment lines to the end, to make sure #+ settings are
25238 ;; still available for the second export step. Kind of a hack, but
25239 ;; does do the trick.
25240 (if (looking-at "#[^\r\n]*")
25241 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25242 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25243 (append-to-buffer buffer (1+ (match-beginning 0))
25244 (min (point-max) (1+ (match-end 0))))))
25245 (set-buffer buffer)
25246 (let ((buffer-file-name file)
25247 (org-inhibit-startup t))
25248 (org-mode)
25249 (show-all)
25250 (unless keepp (funcall binding arg))))
25251 (if (not keepp)
25252 (kill-buffer buffer)
25253 (switch-to-buffer-other-window buffer)
25254 (goto-char (point-min)))))
25256 (defun org-find-visible ()
25257 (let ((s (point)))
25258 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25259 (get-char-property s 'invisible)))
25261 (defun org-find-invisible ()
25262 (let ((s (point)))
25263 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25264 (not (get-char-property s 'invisible))))
25267 ;;; HTML export
25269 (defun org-get-current-options ()
25270 "Return a string with current options as keyword options.
25271 Does include HTML export options as well as TODO and CATEGORY stuff."
25272 (format
25273 "#+TITLE: %s
25274 #+AUTHOR: %s
25275 #+EMAIL: %s
25276 #+LANGUAGE: %s
25277 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25278 #+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
25279 #+CATEGORY: %s
25280 #+SEQ_TODO: %s
25281 #+TYP_TODO: %s
25282 #+PRIORITIES: %c %c %c
25283 #+DRAWERS: %s
25284 #+STARTUP: %s %s %s %s %s
25285 #+TAGS: %s
25286 #+ARCHIVE: %s
25287 #+LINK: %s
25289 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25290 org-export-headline-levels
25291 org-export-with-section-numbers
25292 org-export-with-toc
25293 org-export-preserve-breaks
25294 org-export-html-expand
25295 org-export-with-fixed-width
25296 org-export-with-tables
25297 org-export-with-sub-superscripts
25298 org-export-with-special-strings
25299 org-export-with-footnotes
25300 org-export-with-emphasize
25301 org-export-with-TeX-macros
25302 org-export-with-LaTeX-fragments
25303 org-export-skip-text-before-1st-heading
25304 org-export-with-drawers
25305 org-export-with-tags
25306 (file-name-nondirectory buffer-file-name)
25307 "TODO FEEDBACK VERIFY DONE"
25308 "Me Jason Marie DONE"
25309 org-highest-priority org-lowest-priority org-default-priority
25310 (mapconcat 'identity org-drawers " ")
25311 (cdr (assoc org-startup-folded
25312 '((nil . "showall") (t . "overview") (content . "content"))))
25313 (if org-odd-levels-only "odd" "oddeven")
25314 (if org-hide-leading-stars "hidestars" "showstars")
25315 (if org-startup-align-all-tables "align" "noalign")
25316 (cond ((eq org-log-done t) "logdone")
25317 ((equal org-log-done 'note) "lognotedone")
25318 ((not org-log-done) "nologdone"))
25319 (or (mapconcat (lambda (x)
25320 (cond
25321 ((equal '(:startgroup) x) "{")
25322 ((equal '(:endgroup) x) "}")
25323 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25324 (t (car x))))
25325 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25326 org-archive-location
25327 "org file:~/org/%s.org"
25330 (defun org-insert-export-options-template ()
25331 "Insert into the buffer a template with information for exporting."
25332 (interactive)
25333 (if (not (bolp)) (newline))
25334 (let ((s (org-get-current-options)))
25335 (and (string-match "#\\+CATEGORY" s)
25336 (setq s (substring s 0 (match-beginning 0))))
25337 (insert s)))
25339 (defun org-toggle-fixed-width-section (arg)
25340 "Toggle the fixed-width export.
25341 If there is no active region, the QUOTE keyword at the current headline is
25342 inserted or removed. When present, it causes the text between this headline
25343 and the next to be exported as fixed-width text, and unmodified.
25344 If there is an active region, this command adds or removes a colon as the
25345 first character of this line. If the first character of a line is a colon,
25346 this line is also exported in fixed-width font."
25347 (interactive "P")
25348 (let* ((cc 0)
25349 (regionp (org-region-active-p))
25350 (beg (if regionp (region-beginning) (point)))
25351 (end (if regionp (region-end)))
25352 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25353 (case-fold-search nil)
25354 (re "[ \t]*\\(:\\)")
25355 off)
25356 (if regionp
25357 (save-excursion
25358 (goto-char beg)
25359 (setq cc (current-column))
25360 (beginning-of-line 1)
25361 (setq off (looking-at re))
25362 (while (> nlines 0)
25363 (setq nlines (1- nlines))
25364 (beginning-of-line 1)
25365 (cond
25366 (arg
25367 (move-to-column cc t)
25368 (insert ":\n")
25369 (forward-line -1))
25370 ((and off (looking-at re))
25371 (replace-match "" t t nil 1))
25372 ((not off) (move-to-column cc t) (insert ":")))
25373 (forward-line 1)))
25374 (save-excursion
25375 (org-back-to-heading)
25376 (if (looking-at (concat outline-regexp
25377 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25378 (replace-match "" t t nil 1)
25379 (if (looking-at outline-regexp)
25380 (progn
25381 (goto-char (match-end 0))
25382 (insert org-quote-string " "))))))))
25384 (defun org-export-as-html-and-open (arg)
25385 "Export the outline as HTML and immediately open it with a browser.
25386 If there is an active region, export only the region.
25387 The prefix ARG specifies how many levels of the outline should become
25388 headlines. The default is 3. Lower levels will become bulleted lists."
25389 (interactive "P")
25390 (org-export-as-html arg 'hidden)
25391 (org-open-file buffer-file-name))
25393 (defun org-export-as-html-batch ()
25394 "Call `org-export-as-html', may be used in batch processing as
25395 emacs --batch
25396 --load=$HOME/lib/emacs/org.el
25397 --eval \"(setq org-export-headline-levels 2)\"
25398 --visit=MyFile --funcall org-export-as-html-batch"
25399 (org-export-as-html org-export-headline-levels 'hidden))
25401 (defun org-export-as-html-to-buffer (arg)
25402 "Call `org-exort-as-html` with output to a temporary buffer.
25403 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25404 (interactive "P")
25405 (org-export-as-html arg nil nil "*Org HTML Export*")
25406 (switch-to-buffer-other-window "*Org HTML Export*"))
25408 (defun org-replace-region-by-html (beg end)
25409 "Assume the current region has org-mode syntax, and convert it to HTML.
25410 This can be used in any buffer. For example, you could write an
25411 itemized list in org-mode syntax in an HTML buffer and then use this
25412 command to convert it."
25413 (interactive "r")
25414 (let (reg html buf pop-up-frames)
25415 (save-window-excursion
25416 (if (org-mode-p)
25417 (setq html (org-export-region-as-html
25418 beg end t 'string))
25419 (setq reg (buffer-substring beg end)
25420 buf (get-buffer-create "*Org tmp*"))
25421 (with-current-buffer buf
25422 (erase-buffer)
25423 (insert reg)
25424 (org-mode)
25425 (setq html (org-export-region-as-html
25426 (point-min) (point-max) t 'string)))
25427 (kill-buffer buf)))
25428 (delete-region beg end)
25429 (insert html)))
25431 (defun org-export-region-as-html (beg end &optional body-only buffer)
25432 "Convert region from BEG to END in org-mode buffer to HTML.
25433 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25434 contents, and only produce the region of converted text, useful for
25435 cut-and-paste operations.
25436 If BUFFER is a buffer or a string, use/create that buffer as a target
25437 of the converted HTML. If BUFFER is the symbol `string', return the
25438 produced HTML as a string and leave not buffer behind. For example,
25439 a Lisp program could call this function in the following way:
25441 (setq html (org-export-region-as-html beg end t 'string))
25443 When called interactively, the output buffer is selected, and shown
25444 in a window. A non-interactive call will only retunr the buffer."
25445 (interactive "r\nP")
25446 (when (interactive-p)
25447 (setq buffer "*Org HTML Export*"))
25448 (let ((transient-mark-mode t) (zmacs-regions t)
25449 rtn)
25450 (goto-char end)
25451 (set-mark (point)) ;; to activate the region
25452 (goto-char beg)
25453 (setq rtn (org-export-as-html
25454 nil nil nil
25455 buffer body-only))
25456 (if (fboundp 'deactivate-mark) (deactivate-mark))
25457 (if (and (interactive-p) (bufferp rtn))
25458 (switch-to-buffer-other-window rtn)
25459 rtn)))
25461 (defvar html-table-tag nil) ; dynamically scoped into this.
25462 (defun org-export-as-html (arg &optional hidden ext-plist
25463 to-buffer body-only pub-dir)
25464 "Export the outline as a pretty HTML file.
25465 If there is an active region, export only the region. The prefix
25466 ARG specifies how many levels of the outline should become
25467 headlines. The default is 3. Lower levels will become bulleted
25468 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25469 EXT-PLIST is a property list with external parameters overriding
25470 org-mode's default settings, but still inferior to file-local
25471 settings. When TO-BUFFER is non-nil, create a buffer with that
25472 name and export to that buffer. If TO-BUFFER is the symbol
25473 `string', don't leave any buffer behind but just return the
25474 resulting HTML as a string. When BODY-ONLY is set, don't produce
25475 the file header and footer, simply return the content of
25476 <body>...</body>, without even the body tags themselves. When
25477 PUB-DIR is set, use this as the publishing directory."
25478 (interactive "P")
25480 ;; Make sure we have a file name when we need it.
25481 (when (and (not (or to-buffer body-only))
25482 (not buffer-file-name))
25483 (if (buffer-base-buffer)
25484 (org-set-local 'buffer-file-name
25485 (with-current-buffer (buffer-base-buffer)
25486 buffer-file-name))
25487 (error "Need a file name to be able to export.")))
25489 (message "Exporting...")
25490 (setq-default org-todo-line-regexp org-todo-line-regexp)
25491 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25492 (setq-default org-done-keywords org-done-keywords)
25493 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25494 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25495 ext-plist
25496 (org-infile-export-plist)))
25498 (style (plist-get opt-plist :style))
25499 (html-extension (plist-get opt-plist :html-extension))
25500 (link-validate (plist-get opt-plist :link-validation-function))
25501 valid thetoc have-headings first-heading-pos
25502 (odd org-odd-levels-only)
25503 (region-p (org-region-active-p))
25504 (subtree-p
25505 (when region-p
25506 (save-excursion
25507 (goto-char (region-beginning))
25508 (and (org-at-heading-p)
25509 (>= (org-end-of-subtree t t) (region-end))))))
25510 ;; The following two are dynamically scoped into other
25511 ;; routines below.
25512 (org-current-export-dir
25513 (or pub-dir (org-export-directory :html opt-plist)))
25514 (org-current-export-file buffer-file-name)
25515 (level 0) (line "") (origline "") txt todo
25516 (umax nil)
25517 (umax-toc nil)
25518 (filename (if to-buffer nil
25519 (expand-file-name
25520 (concat
25521 (file-name-sans-extension
25522 (or (and subtree-p
25523 (org-entry-get (region-beginning)
25524 "EXPORT_FILE_NAME" t))
25525 (file-name-nondirectory buffer-file-name)))
25526 "." html-extension)
25527 (file-name-as-directory
25528 (or pub-dir (org-export-directory :html opt-plist))))))
25529 (current-dir (if buffer-file-name
25530 (file-name-directory buffer-file-name)
25531 default-directory))
25532 (buffer (if to-buffer
25533 (cond
25534 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25535 (t (get-buffer-create to-buffer)))
25536 (find-file-noselect filename)))
25537 (org-levels-open (make-vector org-level-max nil))
25538 (date (plist-get opt-plist :date))
25539 (author (plist-get opt-plist :author))
25540 (title (or (and subtree-p (org-export-get-title-from-subtree))
25541 (plist-get opt-plist :title)
25542 (and (not
25543 (plist-get opt-plist :skip-before-1st-heading))
25544 (org-export-grab-title-from-buffer))
25545 (and buffer-file-name
25546 (file-name-sans-extension
25547 (file-name-nondirectory buffer-file-name)))
25548 "UNTITLED"))
25549 (html-table-tag (plist-get opt-plist :html-table-tag))
25550 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25551 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25552 (inquote nil)
25553 (infixed nil)
25554 (in-local-list nil)
25555 (local-list-num nil)
25556 (local-list-indent nil)
25557 (llt org-plain-list-ordered-item-terminator)
25558 (email (plist-get opt-plist :email))
25559 (language (plist-get opt-plist :language))
25560 (lang-words nil)
25561 (target-alist nil) tg
25562 (head-count 0) cnt
25563 (start 0)
25564 (coding-system (and (boundp 'buffer-file-coding-system)
25565 buffer-file-coding-system))
25566 (coding-system-for-write (or org-export-html-coding-system
25567 coding-system))
25568 (save-buffer-coding-system (or org-export-html-coding-system
25569 coding-system))
25570 (charset (and coding-system-for-write
25571 (fboundp 'coding-system-get)
25572 (coding-system-get coding-system-for-write
25573 'mime-charset)))
25574 (region
25575 (buffer-substring
25576 (if region-p (region-beginning) (point-min))
25577 (if region-p (region-end) (point-max))))
25578 (lines
25579 (org-split-string
25580 (org-cleaned-string-for-export
25581 region
25582 :emph-multiline t
25583 :for-html t
25584 :skip-before-1st-heading
25585 (plist-get opt-plist :skip-before-1st-heading)
25586 :drawers (plist-get opt-plist :drawers)
25587 :archived-trees
25588 (plist-get opt-plist :archived-trees)
25589 :add-text
25590 (plist-get opt-plist :text)
25591 :LaTeX-fragments
25592 (plist-get opt-plist :LaTeX-fragments))
25593 "[\r\n]"))
25594 table-open type
25595 table-buffer table-orig-buffer
25596 ind start-is-num starter didclose
25597 rpl path desc descp desc1 desc2 link
25600 (let ((inhibit-read-only t))
25601 (org-unmodified
25602 (remove-text-properties (point-min) (point-max)
25603 '(:org-license-to-kill t))))
25605 (message "Exporting...")
25607 (setq org-min-level (org-get-min-level lines))
25608 (setq org-last-level org-min-level)
25609 (org-init-section-numbers)
25611 (cond
25612 ((and date (string-match "%" date))
25613 (setq date (format-time-string date (current-time))))
25614 (date)
25615 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25617 ;; Get the language-dependent settings
25618 (setq lang-words (or (assoc language org-export-language-setup)
25619 (assoc "en" org-export-language-setup)))
25621 ;; Switch to the output buffer
25622 (set-buffer buffer)
25623 (let ((inhibit-read-only t)) (erase-buffer))
25624 (fundamental-mode)
25626 (and (fboundp 'set-buffer-file-coding-system)
25627 (set-buffer-file-coding-system coding-system-for-write))
25629 (let ((case-fold-search nil)
25630 (org-odd-levels-only odd))
25631 ;; create local variables for all options, to make sure all called
25632 ;; functions get the correct information
25633 (mapc (lambda (x)
25634 (set (make-local-variable (cdr x))
25635 (plist-get opt-plist (car x))))
25636 org-export-plist-vars)
25637 (setq umax (if arg (prefix-numeric-value arg)
25638 org-export-headline-levels))
25639 (setq umax-toc (if (integerp org-export-with-toc)
25640 (min org-export-with-toc umax)
25641 umax))
25642 (unless body-only
25643 ;; File header
25644 (insert (format
25645 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25646 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25647 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25648 lang=\"%s\" xml:lang=\"%s\">
25649 <head>
25650 <title>%s</title>
25651 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25652 <meta name=\"generator\" content=\"Org-mode\"/>
25653 <meta name=\"generated\" content=\"%s\"/>
25654 <meta name=\"author\" content=\"%s\"/>
25656 </head><body>
25658 language language (org-html-expand title)
25659 (or charset "iso-8859-1") date author style))
25661 (insert (or (plist-get opt-plist :preamble) ""))
25663 (when (plist-get opt-plist :auto-preamble)
25664 (if title (insert (format org-export-html-title-format
25665 (org-html-expand title))))))
25667 (if (and org-export-with-toc (not body-only))
25668 (progn
25669 (push (format "<h%d>%s</h%d>\n"
25670 org-export-html-toplevel-hlevel
25671 (nth 3 lang-words)
25672 org-export-html-toplevel-hlevel)
25673 thetoc)
25674 (push "<ul>\n<li>" thetoc)
25675 (setq lines
25676 (mapcar '(lambda (line)
25677 (if (string-match org-todo-line-regexp line)
25678 ;; This is a headline
25679 (progn
25680 (setq have-headings t)
25681 (setq level (- (match-end 1) (match-beginning 1))
25682 level (org-tr-level level)
25683 txt (save-match-data
25684 (org-html-expand
25685 (org-export-cleanup-toc-line
25686 (match-string 3 line))))
25687 todo
25688 (or (and org-export-mark-todo-in-toc
25689 (match-beginning 2)
25690 (not (member (match-string 2 line)
25691 org-done-keywords)))
25692 ; TODO, not DONE
25693 (and org-export-mark-todo-in-toc
25694 (= level umax-toc)
25695 (org-search-todo-below
25696 line lines level))))
25697 (if (string-match
25698 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25699 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25700 (if (string-match quote-re0 txt)
25701 (setq txt (replace-match "" t t txt)))
25702 (if org-export-with-section-numbers
25703 (setq txt (concat (org-section-number level)
25704 " " txt)))
25705 (if (<= level (max umax umax-toc))
25706 (setq head-count (+ head-count 1)))
25707 (if (<= level umax-toc)
25708 (progn
25709 (if (> level org-last-level)
25710 (progn
25711 (setq cnt (- level org-last-level))
25712 (while (>= (setq cnt (1- cnt)) 0)
25713 (push "\n<ul>\n<li>" thetoc))
25714 (push "\n" thetoc)))
25715 (if (< level org-last-level)
25716 (progn
25717 (setq cnt (- org-last-level level))
25718 (while (>= (setq cnt (1- cnt)) 0)
25719 (push "</li>\n</ul>" thetoc))
25720 (push "\n" thetoc)))
25721 ;; Check for targets
25722 (while (string-match org-target-regexp line)
25723 (setq tg (match-string 1 line)
25724 line (replace-match
25725 (concat "@<span class=\"target\">" tg "@</span> ")
25726 t t line))
25727 (push (cons (org-solidify-link-text tg)
25728 (format "sec-%d" head-count))
25729 target-alist))
25730 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25731 (setq txt (replace-match "" t t txt)))
25732 (push
25733 (format
25734 (if todo
25735 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25736 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25737 head-count txt) thetoc)
25739 (setq org-last-level level))
25741 line)
25742 lines))
25743 (while (> org-last-level (1- org-min-level))
25744 (setq org-last-level (1- org-last-level))
25745 (push "</li>\n</ul>\n" thetoc))
25746 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25748 (setq head-count 0)
25749 (org-init-section-numbers)
25751 (while (setq line (pop lines) origline line)
25752 (catch 'nextline
25754 ;; end of quote section?
25755 (when (and inquote (string-match "^\\*+ " line))
25756 (insert "</pre>\n")
25757 (setq inquote nil))
25758 ;; inside a quote section?
25759 (when inquote
25760 (insert (org-html-protect line) "\n")
25761 (throw 'nextline nil))
25763 ;; verbatim lines
25764 (when (and org-export-with-fixed-width
25765 (string-match "^[ \t]*:\\(.*\\)" line))
25766 (when (not infixed)
25767 (setq infixed t)
25768 (insert "<pre>\n"))
25769 (insert (org-html-protect (match-string 1 line)) "\n")
25770 (when (and lines
25771 (not (string-match "^[ \t]*\\(:.*\\)"
25772 (car lines))))
25773 (setq infixed nil)
25774 (insert "</pre>\n"))
25775 (throw 'nextline nil))
25777 ;; Protected HTML
25778 (when (get-text-property 0 'org-protected line)
25779 (let (par)
25780 (when (re-search-backward
25781 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25782 (setq par (match-string 1))
25783 (replace-match "\\2\n"))
25784 (insert line "\n")
25785 (while (and lines
25786 (or (= (length (car lines)) 0)
25787 (get-text-property 0 'org-protected (car lines))))
25788 (insert (pop lines) "\n"))
25789 (and par (insert "<p>\n")))
25790 (throw 'nextline nil))
25792 ;; Horizontal line
25793 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25794 (insert "\n<hr/>\n")
25795 (throw 'nextline nil))
25797 ;; make targets to anchors
25798 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25799 (cond
25800 ((match-end 2)
25801 (setq line (replace-match
25802 (concat "@<a name=\""
25803 (org-solidify-link-text (match-string 1 line))
25804 "\">\\nbsp@</a>")
25805 t t line)))
25806 ((and org-export-with-toc (equal (string-to-char line) ?*))
25807 (setq line (replace-match
25808 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25809 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25810 t t line)))
25812 (setq line (replace-match
25813 (concat "@<a name=\""
25814 (org-solidify-link-text (match-string 1 line))
25815 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25816 t t line)))))
25818 (setq line (org-html-handle-time-stamps line))
25820 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25821 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25822 ;; Also handle sub_superscripts and checkboxes
25823 (or (string-match org-table-hline-regexp line)
25824 (setq line (org-html-expand line)))
25826 ;; Format the links
25827 (setq start 0)
25828 (while (string-match org-bracket-link-analytic-regexp line start)
25829 (setq start (match-beginning 0))
25830 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25831 (setq path (match-string 3 line))
25832 (setq desc1 (if (match-end 5) (match-string 5 line))
25833 desc2 (if (match-end 2) (concat type ":" path) path)
25834 descp (and desc1 (not (equal desc1 desc2)))
25835 desc (or desc1 desc2))
25836 ;; Make an image out of the description if that is so wanted
25837 (when (and descp (org-file-image-p desc))
25838 (save-match-data
25839 (if (string-match "^file:" desc)
25840 (setq desc (substring desc (match-end 0)))))
25841 (setq desc (concat "<img src=\"" desc "\"/>")))
25842 ;; FIXME: do we need to unescape here somewhere?
25843 (cond
25844 ((equal type "internal")
25845 (setq rpl
25846 (concat
25847 "<a href=\"#"
25848 (org-solidify-link-text
25849 (save-match-data (org-link-unescape path)) target-alist)
25850 "\">" desc "</a>")))
25851 ((member type '("http" "https"))
25852 ;; standard URL, just check if we need to inline an image
25853 (if (and (or (eq t org-export-html-inline-images)
25854 (and org-export-html-inline-images (not descp)))
25855 (org-file-image-p path))
25856 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25857 (setq link (concat type ":" path))
25858 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25859 ((member type '("ftp" "mailto" "news"))
25860 ;; standard URL
25861 (setq link (concat type ":" path))
25862 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25863 ((string= type "file")
25864 ;; FILE link
25865 (let* ((filename path)
25866 (abs-p (file-name-absolute-p filename))
25867 thefile file-is-image-p search)
25868 (save-match-data
25869 (if (string-match "::\\(.*\\)" filename)
25870 (setq search (match-string 1 filename)
25871 filename (replace-match "" t nil filename)))
25872 (setq valid
25873 (if (functionp link-validate)
25874 (funcall link-validate filename current-dir)
25876 (setq file-is-image-p (org-file-image-p filename))
25877 (setq thefile (if abs-p (expand-file-name filename) filename))
25878 (when (and org-export-html-link-org-files-as-html
25879 (string-match "\\.org$" thefile))
25880 (setq thefile (concat (substring thefile 0
25881 (match-beginning 0))
25882 "." html-extension))
25883 (if (and search
25884 ;; make sure this is can be used as target search
25885 (not (string-match "^[0-9]*$" search))
25886 (not (string-match "^\\*" search))
25887 (not (string-match "^/.*/$" search)))
25888 (setq thefile (concat thefile "#"
25889 (org-solidify-link-text
25890 (org-link-unescape search)))))
25891 (when (string-match "^file:" desc)
25892 (setq desc (replace-match "" t t desc))
25893 (if (string-match "\\.org$" desc)
25894 (setq desc (replace-match "" t t desc))))))
25895 (setq rpl (if (and file-is-image-p
25896 (or (eq t org-export-html-inline-images)
25897 (and org-export-html-inline-images
25898 (not descp))))
25899 (concat "<img src=\"" thefile "\"/>")
25900 (concat "<a href=\"" thefile "\">" desc "</a>")))
25901 (if (not valid) (setq rpl desc))))
25902 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25903 (setq rpl (concat "<i>&lt;" type ":"
25904 (save-match-data (org-link-unescape path))
25905 "&gt;</i>"))))
25906 (setq line (replace-match rpl t t line)
25907 start (+ start (length rpl))))
25909 ;; TODO items
25910 (if (and (string-match org-todo-line-regexp line)
25911 (match-beginning 2))
25913 (setq line
25914 (concat (substring line 0 (match-beginning 2))
25915 "<span class=\""
25916 (if (member (match-string 2 line)
25917 org-done-keywords)
25918 "done" "todo")
25919 "\">" (match-string 2 line)
25920 "</span>" (substring line (match-end 2)))))
25922 ;; Does this contain a reference to a footnote?
25923 (when org-export-with-footnotes
25924 (setq start 0)
25925 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25926 (if (get-text-property (match-beginning 2) 'org-protected line)
25927 (setq start (match-end 2))
25928 (let ((n (match-string 2 line)))
25929 (setq line
25930 (replace-match
25931 (format
25932 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25933 (match-string 1 line) n n n)
25934 t t line))))))
25936 (cond
25937 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25938 ;; This is a headline
25939 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25940 txt (match-string 2 line))
25941 (if (string-match quote-re0 txt)
25942 (setq txt (replace-match "" t t txt)))
25943 (if (<= level (max umax umax-toc))
25944 (setq head-count (+ head-count 1)))
25945 (when in-local-list
25946 ;; Close any local lists before inserting a new header line
25947 (while local-list-num
25948 (org-close-li)
25949 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
25950 (pop local-list-num))
25951 (setq local-list-indent nil
25952 in-local-list nil))
25953 (setq first-heading-pos (or first-heading-pos (point)))
25954 (org-html-level-start level txt umax
25955 (and org-export-with-toc (<= level umax))
25956 head-count)
25957 ;; QUOTES
25958 (when (string-match quote-re line)
25959 (insert "<pre>")
25960 (setq inquote t)))
25962 ((and org-export-with-tables
25963 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25964 (if (not table-open)
25965 ;; New table starts
25966 (setq table-open t table-buffer nil table-orig-buffer nil))
25967 ;; Accumulate lines
25968 (setq table-buffer (cons line table-buffer)
25969 table-orig-buffer (cons origline table-orig-buffer))
25970 (when (or (not lines)
25971 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25972 (car lines))))
25973 (setq table-open nil
25974 table-buffer (nreverse table-buffer)
25975 table-orig-buffer (nreverse table-orig-buffer))
25976 (org-close-par-maybe)
25977 (insert (org-format-table-html table-buffer table-orig-buffer))))
25979 ;; Normal lines
25980 (when (string-match
25981 (cond
25982 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25983 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25984 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
25985 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
25986 line)
25987 (setq ind (org-get-string-indentation line)
25988 start-is-num (match-beginning 4)
25989 starter (if (match-beginning 2)
25990 (substring (match-string 2 line) 0 -1))
25991 line (substring line (match-beginning 5)))
25992 (unless (string-match "[^ \t]" line)
25993 ;; empty line. Pretend indentation is large.
25994 (setq ind (if org-empty-line-terminates-plain-lists
25996 (1+ (or (car local-list-indent) 1)))))
25997 (setq didclose nil)
25998 (while (and in-local-list
25999 (or (and (= ind (car local-list-indent))
26000 (not starter))
26001 (< ind (car local-list-indent))))
26002 (setq didclose t)
26003 (org-close-li)
26004 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
26005 (pop local-list-num) (pop local-list-indent)
26006 (setq in-local-list local-list-indent))
26007 (cond
26008 ((and starter
26009 (or (not in-local-list)
26010 (> ind (car local-list-indent))))
26011 ;; Start new (level of) list
26012 (org-close-par-maybe)
26013 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
26014 (push start-is-num local-list-num)
26015 (push ind local-list-indent)
26016 (setq in-local-list t))
26017 (starter
26018 ;; continue current list
26019 (org-close-li)
26020 (insert "<li>\n"))
26021 (didclose
26022 ;; we did close a list, normal text follows: need <p>
26023 (org-open-par)))
26024 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
26025 (setq line
26026 (replace-match
26027 (if (equal (match-string 1 line) "X")
26028 "<b>[X]</b>"
26029 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
26030 t t line))))
26032 ;; Empty lines start a new paragraph. If hand-formatted lists
26033 ;; are not fully interpreted, lines starting with "-", "+", "*"
26034 ;; also start a new paragraph.
26035 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
26037 ;; Is this the start of a footnote?
26038 (when org-export-with-footnotes
26039 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
26040 (org-close-par-maybe)
26041 (let ((n (match-string 1 line)))
26042 (setq line (replace-match
26043 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
26045 ;; Check if the line break needs to be conserved
26046 (cond
26047 ((string-match "\\\\\\\\[ \t]*$" line)
26048 (setq line (replace-match "<br/>" t t line)))
26049 (org-export-preserve-breaks
26050 (setq line (concat line "<br/>"))))
26052 (insert line "\n")))))
26054 ;; Properly close all local lists and other lists
26055 (when inquote (insert "</pre>\n"))
26056 (when in-local-list
26057 ;; Close any local lists before inserting a new header line
26058 (while local-list-num
26059 (org-close-li)
26060 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
26061 (pop local-list-num))
26062 (setq local-list-indent nil
26063 in-local-list nil))
26064 (org-html-level-start 1 nil umax
26065 (and org-export-with-toc (<= level umax))
26066 head-count)
26068 (unless body-only
26069 (when (plist-get opt-plist :auto-postamble)
26070 (insert "<div id=\"postamble\">")
26071 (when (and org-export-author-info author)
26072 (insert "<p class=\"author\"> "
26073 (nth 1 lang-words) ": " author "\n")
26074 (when email
26075 (if (listp (split-string email ",+ *"))
26076 (mapc (lambda(e)
26077 (insert "<a href=\"mailto:" e "\">&lt;"
26078 e "&gt;</a>\n"))
26079 (split-string email ",+ *"))
26080 (insert "<a href=\"mailto:" email "\">&lt;"
26081 email "&gt;</a>\n")))
26082 (insert "</p>\n"))
26083 (when (and date org-export-time-stamp-file)
26084 (insert "<p class=\"date\"> "
26085 (nth 2 lang-words) ": "
26086 date "</p>\n"))
26087 (insert "</div>"))
26089 (if org-export-html-with-timestamp
26090 (insert org-export-html-html-helper-timestamp))
26091 (insert (or (plist-get opt-plist :postamble) ""))
26092 (insert "</body>\n</html>\n"))
26094 (normal-mode)
26095 (if (eq major-mode default-major-mode) (html-mode))
26097 ;; insert the table of contents
26098 (goto-char (point-min))
26099 (when thetoc
26100 (if (or (re-search-forward
26101 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26102 (re-search-forward
26103 "\\[TABLE-OF-CONTENTS\\]" nil t))
26104 (progn
26105 (goto-char (match-beginning 0))
26106 (replace-match ""))
26107 (goto-char first-heading-pos)
26108 (when (looking-at "\\s-*</p>")
26109 (goto-char (match-end 0))
26110 (insert "\n")))
26111 (insert "<div id=\"table-of-contents\">\n")
26112 (mapc 'insert thetoc)
26113 (insert "</div>\n"))
26114 ;; remove empty paragraphs and lists
26115 (goto-char (point-min))
26116 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26117 (replace-match ""))
26118 (goto-char (point-min))
26119 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26120 (replace-match ""))
26121 (goto-char (point-min))
26122 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26123 (replace-match ""))
26124 ;; Convert whitespace place holders
26125 (goto-char (point-min))
26126 (let (beg end n)
26127 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26128 (setq n (get-text-property beg 'org-whitespace)
26129 end (next-single-property-change beg 'org-whitespace))
26130 (goto-char beg)
26131 (delete-region beg end)
26132 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26133 (make-string n ?x)))))
26134 (or to-buffer (save-buffer))
26135 (goto-char (point-min))
26136 (message "Exporting... done")
26137 (if (eq to-buffer 'string)
26138 (prog1 (buffer-substring (point-min) (point-max))
26139 (kill-buffer (current-buffer)))
26140 (current-buffer)))))
26142 (defvar org-table-colgroup-info nil)
26143 (defun org-format-table-ascii (lines)
26144 "Format a table for ascii export."
26145 (if (stringp lines)
26146 (setq lines (org-split-string lines "\n")))
26147 (if (not (string-match "^[ \t]*|" (car lines)))
26148 ;; Table made by table.el - test for spanning
26149 lines
26151 ;; A normal org table
26152 ;; Get rid of hlines at beginning and end
26153 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26154 (setq lines (nreverse lines))
26155 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26156 (setq lines (nreverse lines))
26157 (when org-export-table-remove-special-lines
26158 ;; Check if the table has a marking column. If yes remove the
26159 ;; column and the special lines
26160 (setq lines (org-table-clean-before-export lines)))
26161 ;; Get rid of the vertical lines except for grouping
26162 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26163 rtn line vl1 start)
26164 (while (setq line (pop lines))
26165 (if (string-match org-table-hline-regexp line)
26166 (and (string-match "|\\(.*\\)|" line)
26167 (setq line (replace-match " \\1" t nil line)))
26168 (setq start 0 vl1 vl)
26169 (while (string-match "|" line start)
26170 (setq start (match-end 0))
26171 (or (pop vl1) (setq line (replace-match " " t t line)))))
26172 (push line rtn))
26173 (nreverse rtn))))
26175 (defun org-colgroup-info-to-vline-list (info)
26176 (let (vl new last)
26177 (while info
26178 (setq last new new (pop info))
26179 (if (or (memq last '(:end :startend))
26180 (memq new '(:start :startend)))
26181 (push t vl)
26182 (push nil vl)))
26183 (setq vl (nreverse vl))
26184 (and vl (setcar vl nil))
26185 vl))
26187 (defun org-format-table-html (lines olines)
26188 "Find out which HTML converter to use and return the HTML code."
26189 (if (stringp lines)
26190 (setq lines (org-split-string lines "\n")))
26191 (if (string-match "^[ \t]*|" (car lines))
26192 ;; A normal org table
26193 (org-format-org-table-html lines)
26194 ;; Table made by table.el - test for spanning
26195 (let* ((hlines (delq nil (mapcar
26196 (lambda (x)
26197 (if (string-match "^[ \t]*\\+-" x) x
26198 nil))
26199 lines)))
26200 (first (car hlines))
26201 (ll (and (string-match "\\S-+" first)
26202 (match-string 0 first)))
26203 (re (concat "^[ \t]*" (regexp-quote ll)))
26204 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26205 hlines))))
26206 (if (and (not spanning)
26207 (not org-export-prefer-native-exporter-for-tables))
26208 ;; We can use my own converter with HTML conversions
26209 (org-format-table-table-html lines)
26210 ;; Need to use the code generator in table.el, with the original text.
26211 (org-format-table-table-html-using-table-generate-source olines)))))
26213 (defun org-format-org-table-html (lines &optional splice)
26214 "Format a table into HTML."
26215 ;; Get rid of hlines at beginning and end
26216 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26217 (setq lines (nreverse lines))
26218 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26219 (setq lines (nreverse lines))
26220 (when org-export-table-remove-special-lines
26221 ;; Check if the table has a marking column. If yes remove the
26222 ;; column and the special lines
26223 (setq lines (org-table-clean-before-export lines)))
26225 (let ((head (and org-export-highlight-first-table-line
26226 (delq nil (mapcar
26227 (lambda (x) (string-match "^[ \t]*|-" x))
26228 (cdr lines)))))
26229 (nlines 0) fnum i
26230 tbopen line fields html gr colgropen)
26231 (if splice (setq head nil))
26232 (unless splice (push (if head "<thead>" "<tbody>") html))
26233 (setq tbopen t)
26234 (while (setq line (pop lines))
26235 (catch 'next-line
26236 (if (string-match "^[ \t]*|-" line)
26237 (progn
26238 (unless splice
26239 (push (if head "</thead>" "</tbody>") html)
26240 (if lines (push "<tbody>" html) (setq tbopen nil)))
26241 (setq head nil) ;; head ends here, first time around
26242 ;; ignore this line
26243 (throw 'next-line t)))
26244 ;; Break the line into fields
26245 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26246 (unless fnum (setq fnum (make-vector (length fields) 0)))
26247 (setq nlines (1+ nlines) i -1)
26248 (push (concat "<tr>"
26249 (mapconcat
26250 (lambda (x)
26251 (setq i (1+ i))
26252 (if (and (< i nlines)
26253 (string-match org-table-number-regexp x))
26254 (incf (aref fnum i)))
26255 (if head
26256 (concat (car org-export-table-header-tags) x
26257 (cdr org-export-table-header-tags))
26258 (concat (car org-export-table-data-tags) x
26259 (cdr org-export-table-data-tags))))
26260 fields "")
26261 "</tr>")
26262 html)))
26263 (unless splice (if tbopen (push "</tbody>" html)))
26264 (unless splice (push "</table>\n" html))
26265 (setq html (nreverse html))
26266 (unless splice
26267 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26268 (push (mapconcat
26269 (lambda (x)
26270 (setq gr (pop org-table-colgroup-info))
26271 (format "%s<col align=\"%s\"></col>%s"
26272 (if (memq gr '(:start :startend))
26273 (prog1
26274 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26275 (setq colgropen t))
26277 (if (> (/ (float x) nlines) org-table-number-fraction)
26278 "right" "left")
26279 (if (memq gr '(:end :startend))
26280 (progn (setq colgropen nil) "</colgroup>")
26281 "")))
26282 fnum "")
26283 html)
26284 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26285 (push html-table-tag html))
26286 (concat (mapconcat 'identity html "\n") "\n")))
26288 (defun org-table-clean-before-export (lines)
26289 "Check if the table has a marking column.
26290 If yes remove the column and the special lines."
26291 (setq org-table-colgroup-info nil)
26292 (if (memq nil
26293 (mapcar
26294 (lambda (x) (or (string-match "^[ \t]*|-" x)
26295 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26296 lines))
26297 (progn
26298 (setq org-table-clean-did-remove-column nil)
26299 (delq nil
26300 (mapcar
26301 (lambda (x)
26302 (cond
26303 ((string-match "^[ \t]*| */ *|" x)
26304 (setq org-table-colgroup-info
26305 (mapcar (lambda (x)
26306 (cond ((member x '("<" "&lt;")) :start)
26307 ((member x '(">" "&gt;")) :end)
26308 ((member x '("<>" "&lt;&gt;")) :startend)
26309 (t nil)))
26310 (org-split-string x "[ \t]*|[ \t]*")))
26311 nil)
26312 (t x)))
26313 lines)))
26314 (setq org-table-clean-did-remove-column t)
26315 (delq nil
26316 (mapcar
26317 (lambda (x)
26318 (cond
26319 ((string-match "^[ \t]*| */ *|" x)
26320 (setq org-table-colgroup-info
26321 (mapcar (lambda (x)
26322 (cond ((member x '("<" "&lt;")) :start)
26323 ((member x '(">" "&gt;")) :end)
26324 ((member x '("<>" "&lt;&gt;")) :startend)
26325 (t nil)))
26326 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26327 nil)
26328 ((string-match "^[ \t]*| *[!_^/] *|" x)
26329 nil) ; ignore this line
26330 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26331 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26332 ;; remove the first column
26333 (replace-match "\\1|" t nil x))))
26334 lines))))
26336 (defun org-format-table-table-html (lines)
26337 "Format a table generated by table.el into HTML.
26338 This conversion does *not* use `table-generate-source' from table.el.
26339 This has the advantage that Org-mode's HTML conversions can be used.
26340 But it has the disadvantage, that no cell- or row-spanning is allowed."
26341 (let (line field-buffer
26342 (head org-export-highlight-first-table-line)
26343 fields html empty)
26344 (setq html (concat html-table-tag "\n"))
26345 (while (setq line (pop lines))
26346 (setq empty "&nbsp;")
26347 (catch 'next-line
26348 (if (string-match "^[ \t]*\\+-" line)
26349 (progn
26350 (if field-buffer
26351 (progn
26352 (setq
26353 html
26354 (concat
26355 html
26356 "<tr>"
26357 (mapconcat
26358 (lambda (x)
26359 (if (equal x "") (setq x empty))
26360 (if head
26361 (concat (car org-export-table-header-tags) x
26362 (cdr org-export-table-header-tags))
26363 (concat (car org-export-table-data-tags) x
26364 (cdr org-export-table-data-tags))))
26365 field-buffer "\n")
26366 "</tr>\n"))
26367 (setq head nil)
26368 (setq field-buffer nil)))
26369 ;; Ignore this line
26370 (throw 'next-line t)))
26371 ;; Break the line into fields and store the fields
26372 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26373 (if field-buffer
26374 (setq field-buffer (mapcar
26375 (lambda (x)
26376 (concat x "<br/>" (pop fields)))
26377 field-buffer))
26378 (setq field-buffer fields))))
26379 (setq html (concat html "</table>\n"))
26380 html))
26382 (defun org-format-table-table-html-using-table-generate-source (lines)
26383 "Format a table into html, using `table-generate-source' from table.el.
26384 This has the advantage that cell- or row-spanning is allowed.
26385 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26386 (require 'table)
26387 (with-current-buffer (get-buffer-create " org-tmp1 ")
26388 (erase-buffer)
26389 (insert (mapconcat 'identity lines "\n"))
26390 (goto-char (point-min))
26391 (if (not (re-search-forward "|[^+]" nil t))
26392 (error "Error processing table"))
26393 (table-recognize-table)
26394 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26395 (table-generate-source 'html " org-tmp2 ")
26396 (set-buffer " org-tmp2 ")
26397 (buffer-substring (point-min) (point-max))))
26399 (defun org-html-handle-time-stamps (s)
26400 "Format time stamps in string S, or remove them."
26401 (catch 'exit
26402 (let (r b)
26403 (while (string-match org-maybe-keyword-time-regexp s)
26404 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26405 ;; never export CLOCK
26406 (throw 'exit ""))
26407 (or b (setq b (substring s 0 (match-beginning 0))))
26408 (if (not org-export-with-timestamps)
26409 (setq r (concat r (substring s 0 (match-beginning 0)))
26410 s (substring s (match-end 0)))
26411 (setq r (concat
26412 r (substring s 0 (match-beginning 0))
26413 (if (match-end 1)
26414 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26415 (match-string 1 s)))
26416 (format " @<span class=\"timestamp\">%s@</span>"
26417 (substring
26418 (org-translate-time (match-string 3 s)) 1 -1)))
26419 s (substring s (match-end 0)))))
26420 ;; Line break if line started and ended with time stamp stuff
26421 (if (not r)
26423 (setq r (concat r s))
26424 (unless (string-match "\\S-" (concat b s))
26425 (setq r (concat r "@<br/>")))
26426 r))))
26428 (defun org-html-protect (s)
26429 ;; convert & to &amp;, < to &lt; and > to &gt;
26430 (let ((start 0))
26431 (while (string-match "&" s start)
26432 (setq s (replace-match "&amp;" t t s)
26433 start (1+ (match-beginning 0))))
26434 (while (string-match "<" s)
26435 (setq s (replace-match "&lt;" t t s)))
26436 (while (string-match ">" s)
26437 (setq s (replace-match "&gt;" t t s))))
26440 (defun org-export-cleanup-toc-line (s)
26441 "Remove tags and time staps from lines going into the toc."
26442 (when (memq org-export-with-tags '(not-in-toc nil))
26443 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26444 (setq s (replace-match "" t t s))))
26445 (when org-export-remove-timestamps-from-toc
26446 (while (string-match org-maybe-keyword-time-regexp s)
26447 (setq s (replace-match "" t t s))))
26448 (while (string-match org-bracket-link-regexp s)
26449 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26450 t t s)))
26453 (defun org-html-expand (string)
26454 "Prepare STRING for HTML export. Applies all active conversions.
26455 If there are links in the string, don't modify these."
26456 (let* ((re (concat org-bracket-link-regexp "\\|"
26457 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26458 m s l res)
26459 (while (setq m (string-match re string))
26460 (setq s (substring string 0 m)
26461 l (match-string 0 string)
26462 string (substring string (match-end 0)))
26463 (push (org-html-do-expand s) res)
26464 (push l res))
26465 (push (org-html-do-expand string) res)
26466 (apply 'concat (nreverse res))))
26468 (defun org-html-do-expand (s)
26469 "Apply all active conversions to translate special ASCII to HTML."
26470 (setq s (org-html-protect s))
26471 (if org-export-html-expand
26472 (let ((start 0))
26473 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26474 (setq s (replace-match "<\\1>" t nil s)))))
26475 (if org-export-with-emphasize
26476 (setq s (org-export-html-convert-emphasize s)))
26477 (if org-export-with-special-strings
26478 (setq s (org-export-html-convert-special-strings s)))
26479 (if org-export-with-sub-superscripts
26480 (setq s (org-export-html-convert-sub-super s)))
26481 (if org-export-with-TeX-macros
26482 (let ((start 0) wd ass)
26483 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26484 (if (get-text-property (match-beginning 0) 'org-protected s)
26485 (setq start (match-end 0))
26486 (setq wd (match-string 1 s))
26487 (if (setq ass (assoc wd org-html-entities))
26488 (setq s (replace-match (or (cdr ass)
26489 (concat "&" (car ass) ";"))
26490 t t s))
26491 (setq start (+ start (length wd))))))))
26494 (defun org-create-multibrace-regexp (left right n)
26495 "Create a regular expression which will match a balanced sexp.
26496 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26497 as single character strings.
26498 The regexp returned will match the entire expression including the
26499 delimiters. It will also define a single group which contains the
26500 match except for the outermost delimiters. The maximum depth of
26501 stacked delimiters is N. Escaping delimiters is not possible."
26502 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26503 (or "\\|")
26504 (re nothing)
26505 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26506 (while (> n 1)
26507 (setq n (1- n)
26508 re (concat re or next)
26509 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26510 (concat left "\\(" re "\\)" right)))
26512 (defvar org-match-substring-regexp
26513 (concat
26514 "\\([^\\]\\)\\([_^]\\)\\("
26515 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26516 "\\|"
26517 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26518 "\\|"
26519 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26520 "The regular expression matching a sub- or superscript.")
26522 (defvar org-match-substring-with-braces-regexp
26523 (concat
26524 "\\([^\\]\\)\\([_^]\\)\\("
26525 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26526 "\\)")
26527 "The regular expression matching a sub- or superscript, forcing braces.")
26529 (defconst org-export-html-special-string-regexps
26530 '(("\\\\-" . "&shy;")
26531 ("---\\([^-]\\)" . "&mdash;\\1")
26532 ("--\\([^-]\\)" . "&ndash;\\1")
26533 ("\\.\\.\\." . "&hellip;"))
26534 "Regular expressions for special string conversion.")
26536 (defun org-export-html-convert-special-strings (string)
26537 "Convert special characters in STRING to HTML."
26538 (let ((all org-export-html-special-string-regexps)
26539 e a re rpl start)
26540 (while (setq a (pop all))
26541 (setq re (car a) rpl (cdr a) start 0)
26542 (while (string-match re string start)
26543 (if (get-text-property (match-beginning 0) 'org-protected string)
26544 (setq start (match-end 0))
26545 (setq string (replace-match rpl t nil string)))))
26546 string))
26548 (defun org-export-html-convert-sub-super (string)
26549 "Convert sub- and superscripts in STRING to HTML."
26550 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26551 (while (string-match org-match-substring-regexp string s)
26552 (cond
26553 ((and requireb (match-end 8)) (setq s (match-end 2)))
26554 ((get-text-property (match-beginning 2) 'org-protected string)
26555 (setq s (match-end 2)))
26557 (setq s (match-end 1)
26558 key (if (string= (match-string 2 string) "_") "sub" "sup")
26559 c (or (match-string 8 string)
26560 (match-string 6 string)
26561 (match-string 5 string))
26562 string (replace-match
26563 (concat (match-string 1 string)
26564 "<" key ">" c "</" key ">")
26565 t t string)))))
26566 (while (string-match "\\\\\\([_^]\\)" string)
26567 (setq string (replace-match (match-string 1 string) t t string)))
26568 string))
26570 (defun org-export-html-convert-emphasize (string)
26571 "Apply emphasis."
26572 (let ((s 0) rpl)
26573 (while (string-match org-emph-re string s)
26574 (if (not (equal
26575 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26576 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26577 (setq s (match-beginning 0)
26579 (concat
26580 (match-string 1 string)
26581 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26582 (match-string 4 string)
26583 (nth 3 (assoc (match-string 3 string)
26584 org-emphasis-alist))
26585 (match-string 5 string))
26586 string (replace-match rpl t t string)
26587 s (+ s (- (length rpl) 2)))
26588 (setq s (1+ s))))
26589 string))
26591 (defvar org-par-open nil)
26592 (defun org-open-par ()
26593 "Insert <p>, but first close previous paragraph if any."
26594 (org-close-par-maybe)
26595 (insert "\n<p>")
26596 (setq org-par-open t))
26597 (defun org-close-par-maybe ()
26598 "Close paragraph if there is one open."
26599 (when org-par-open
26600 (insert "</p>")
26601 (setq org-par-open nil)))
26602 (defun org-close-li ()
26603 "Close <li> if necessary."
26604 (org-close-par-maybe)
26605 (insert "</li>\n"))
26607 (defvar body-only) ; dynamically scoped into this.
26608 (defun org-html-level-start (level title umax with-toc head-count)
26609 "Insert a new level in HTML export.
26610 When TITLE is nil, just close all open levels."
26611 (org-close-par-maybe)
26612 (let ((l org-level-max))
26613 (while (>= l level)
26614 (if (aref org-levels-open (1- l))
26615 (progn
26616 (org-html-level-close l umax)
26617 (aset org-levels-open (1- l) nil)))
26618 (setq l (1- l)))
26619 (when title
26620 ;; If title is nil, this means this function is called to close
26621 ;; all levels, so the rest is done only if title is given
26622 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26623 (setq title (replace-match
26624 (if org-export-with-tags
26625 (save-match-data
26626 (concat
26627 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26628 (mapconcat 'identity (org-split-string
26629 (match-string 1 title) ":")
26630 "&nbsp;")
26631 "</span>"))
26633 t t title)))
26634 (if (> level umax)
26635 (progn
26636 (if (aref org-levels-open (1- level))
26637 (progn
26638 (org-close-li)
26639 (insert "<li>" title "<br/>\n"))
26640 (aset org-levels-open (1- level) t)
26641 (org-close-par-maybe)
26642 (insert "<ul>\n<li>" title "<br/>\n")))
26643 (aset org-levels-open (1- level) t)
26644 (if (and org-export-with-section-numbers (not body-only))
26645 (setq title (concat (org-section-number level) " " title)))
26646 (setq level (+ level org-export-html-toplevel-hlevel -1))
26647 (if with-toc
26648 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26649 level level head-count title level))
26650 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26651 (org-open-par)))))
26653 (defun org-html-level-close (level max-outline-level)
26654 "Terminate one level in HTML export."
26655 (if (<= level max-outline-level)
26656 (insert "</div>\n")
26657 (org-close-li)
26658 (insert "</ul>\n")))
26660 ;;; iCalendar export
26662 ;;;###autoload
26663 (defun org-export-icalendar-this-file ()
26664 "Export current file as an iCalendar file.
26665 The iCalendar file will be located in the same directory as the Org-mode
26666 file, but with extension `.ics'."
26667 (interactive)
26668 (org-export-icalendar nil buffer-file-name))
26670 ;;;###autoload
26671 (defun org-export-icalendar-all-agenda-files ()
26672 "Export all files in `org-agenda-files' to iCalendar .ics files.
26673 Each iCalendar file will be located in the same directory as the Org-mode
26674 file, but with extension `.ics'."
26675 (interactive)
26676 (apply 'org-export-icalendar nil (org-agenda-files t)))
26678 ;;;###autoload
26679 (defun org-export-icalendar-combine-agenda-files ()
26680 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26681 The file is stored under the name `org-combined-agenda-icalendar-file'."
26682 (interactive)
26683 (apply 'org-export-icalendar t (org-agenda-files t)))
26685 (defun org-export-icalendar (combine &rest files)
26686 "Create iCalendar files for all elements of FILES.
26687 If COMBINE is non-nil, combine all calendar entries into a single large
26688 file and store it under the name `org-combined-agenda-icalendar-file'."
26689 (save-excursion
26690 (org-prepare-agenda-buffers files)
26691 (let* ((dir (org-export-directory
26692 :ical (list :publishing-directory
26693 org-export-publishing-directory)))
26694 file ical-file ical-buffer category started org-agenda-new-buffers)
26696 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26697 (when combine
26698 (setq ical-file
26699 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26700 org-combined-agenda-icalendar-file
26701 (expand-file-name org-combined-agenda-icalendar-file dir))
26702 ical-buffer (org-get-agenda-file-buffer ical-file))
26703 (set-buffer ical-buffer) (erase-buffer))
26704 (while (setq file (pop files))
26705 (catch 'nextfile
26706 (org-check-agenda-file file)
26707 (set-buffer (org-get-agenda-file-buffer file))
26708 (unless combine
26709 (setq ical-file (concat (file-name-as-directory dir)
26710 (file-name-sans-extension
26711 (file-name-nondirectory buffer-file-name))
26712 ".ics"))
26713 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26714 (with-current-buffer ical-buffer (erase-buffer)))
26715 (setq category (or org-category
26716 (file-name-sans-extension
26717 (file-name-nondirectory buffer-file-name))))
26718 (if (symbolp category) (setq category (symbol-name category)))
26719 (let ((standard-output ical-buffer))
26720 (if combine
26721 (and (not started) (setq started t)
26722 (org-start-icalendar-file org-icalendar-combined-name))
26723 (org-start-icalendar-file category))
26724 (org-print-icalendar-entries combine)
26725 (when (or (and combine (not files)) (not combine))
26726 (org-finish-icalendar-file)
26727 (set-buffer ical-buffer)
26728 (save-buffer)
26729 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26730 (org-release-buffers org-agenda-new-buffers))))
26732 (defvar org-after-save-iCalendar-file-hook nil
26733 "Hook run after an iCalendar file has been saved.
26734 The iCalendar buffer is still current when this hook is run.
26735 A good way to use this is to tell a desktop calenndar application to re-read
26736 the iCalendar file.")
26738 (defun org-print-icalendar-entries (&optional combine)
26739 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26740 When COMBINE is non nil, add the category to each line."
26741 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26742 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26743 (dts (org-ical-ts-to-string
26744 (format-time-string (cdr org-time-stamp-formats) (current-time))
26745 "DTSTART"))
26746 hd ts ts2 state status (inc t) pos b sexp rrule
26747 scheduledp deadlinep tmp pri category entry location summary desc
26748 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26749 (org-refresh-category-properties)
26750 (save-excursion
26751 (goto-char (point-min))
26752 (while (re-search-forward re1 nil t)
26753 (catch :skip
26754 (org-agenda-skip)
26755 (setq pos (match-beginning 0)
26756 ts (match-string 0)
26757 inc t
26758 hd (org-get-heading)
26759 summary (org-icalendar-cleanup-string
26760 (org-entry-get nil "SUMMARY"))
26761 desc (org-icalendar-cleanup-string
26762 (or (org-entry-get nil "DESCRIPTION")
26763 (and org-icalendar-include-body (org-get-entry)))
26764 t org-icalendar-include-body)
26765 location (org-icalendar-cleanup-string
26766 (org-entry-get nil "LOCATION"))
26767 category (org-get-category))
26768 (if (looking-at re2)
26769 (progn
26770 (goto-char (match-end 0))
26771 (setq ts2 (match-string 1) inc nil))
26772 (setq tmp (buffer-substring (max (point-min)
26773 (- pos org-ds-keyword-length))
26774 pos)
26775 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26776 (progn
26777 (setq inc nil)
26778 (replace-match "\\1" t nil ts))
26780 deadlinep (string-match org-deadline-regexp tmp)
26781 scheduledp (string-match org-scheduled-regexp tmp)
26782 ;; donep (org-entry-is-done-p)
26784 (if (or (string-match org-tr-regexp hd)
26785 (string-match org-ts-regexp hd))
26786 (setq hd (replace-match "" t t hd)))
26787 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26788 (setq rrule
26789 (concat "\nRRULE:FREQ="
26790 (cdr (assoc
26791 (match-string 2 ts)
26792 '(("d" . "DAILY")("w" . "WEEKLY")
26793 ("m" . "MONTHLY")("y" . "YEARLY"))))
26794 ";INTERVAL=" (match-string 1 ts)))
26795 (setq rrule ""))
26796 (setq summary (or summary hd))
26797 (if (string-match org-bracket-link-regexp summary)
26798 (setq summary
26799 (replace-match (if (match-end 3)
26800 (match-string 3 summary)
26801 (match-string 1 summary))
26802 t t summary)))
26803 (if deadlinep (setq summary (concat "DL: " summary)))
26804 (if scheduledp (setq summary (concat "S: " summary)))
26805 (if (string-match "\\`<%%" ts)
26806 (with-current-buffer sexp-buffer
26807 (insert (substring ts 1 -1) " " summary "\n"))
26808 (princ (format "BEGIN:VEVENT
26810 %s%s
26811 SUMMARY:%s%s%s
26812 CATEGORIES:%s
26813 END:VEVENT\n"
26814 (org-ical-ts-to-string ts "DTSTART")
26815 (org-ical-ts-to-string ts2 "DTEND" inc)
26816 rrule summary
26817 (if (and desc (string-match "\\S-" desc))
26818 (concat "\nDESCRIPTION: " desc) "")
26819 (if (and location (string-match "\\S-" location))
26820 (concat "\nLOCATION: " location) "")
26821 category)))))
26823 (when (and org-icalendar-include-sexps
26824 (condition-case nil (require 'icalendar) (error nil))
26825 (fboundp 'icalendar-export-region))
26826 ;; Get all the literal sexps
26827 (goto-char (point-min))
26828 (while (re-search-forward "^&?%%(" nil t)
26829 (catch :skip
26830 (org-agenda-skip)
26831 (setq b (match-beginning 0))
26832 (goto-char (1- (match-end 0)))
26833 (forward-sexp 1)
26834 (end-of-line 1)
26835 (setq sexp (buffer-substring b (point)))
26836 (with-current-buffer sexp-buffer
26837 (insert sexp "\n"))
26838 (princ (org-diary-to-ical-string sexp-buffer)))))
26840 (when org-icalendar-include-todo
26841 (goto-char (point-min))
26842 (while (re-search-forward org-todo-line-regexp nil t)
26843 (catch :skip
26844 (org-agenda-skip)
26845 (setq state (match-string 2))
26846 (setq status (if (member state org-done-keywords)
26847 "COMPLETED" "NEEDS-ACTION"))
26848 (when (and state
26849 (or (not (member state org-done-keywords))
26850 (eq org-icalendar-include-todo 'all))
26851 (not (member org-archive-tag (org-get-tags-at)))
26853 (setq hd (match-string 3)
26854 summary (org-icalendar-cleanup-string
26855 (org-entry-get nil "SUMMARY"))
26856 desc (org-icalendar-cleanup-string
26857 (or (org-entry-get nil "DESCRIPTION")
26858 (and org-icalendar-include-body (org-get-entry)))
26859 t org-icalendar-include-body)
26860 location (org-icalendar-cleanup-string
26861 (org-entry-get nil "LOCATION")))
26862 (if (string-match org-bracket-link-regexp hd)
26863 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26864 (match-string 1 hd))
26865 t t hd)))
26866 (if (string-match org-priority-regexp hd)
26867 (setq pri (string-to-char (match-string 2 hd))
26868 hd (concat (substring hd 0 (match-beginning 1))
26869 (substring hd (match-end 1))))
26870 (setq pri org-default-priority))
26871 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26872 (- org-lowest-priority org-highest-priority))))))
26874 (princ (format "BEGIN:VTODO
26876 SUMMARY:%s%s%s
26877 CATEGORIES:%s
26878 SEQUENCE:1
26879 PRIORITY:%d
26880 STATUS:%s
26881 END:VTODO\n"
26883 (or summary hd)
26884 (if (and location (string-match "\\S-" location))
26885 (concat "\nLOCATION: " location) "")
26886 (if (and desc (string-match "\\S-" desc))
26887 (concat "\nDESCRIPTION: " desc) "")
26888 category pri status)))))))))
26890 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26891 "Take out stuff and quote what needs to be quoted.
26892 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26893 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26894 characters."
26895 (if (not s)
26897 (when is-body
26898 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26899 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26900 (while (string-match re s) (setq s (replace-match "" t t s)))
26901 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26902 (let ((start 0))
26903 (while (string-match "\\([,;\\]\\)" s start)
26904 (setq start (+ (match-beginning 0) 2)
26905 s (replace-match "\\\\\\1" nil nil s))))
26906 (when is-body
26907 (while (string-match "[ \t]*\n[ \t]*" s)
26908 (setq s (replace-match "\\n" t t s))))
26909 (setq s (org-trim s))
26910 (if is-body
26911 (if maxlength
26912 (if (and (numberp maxlength)
26913 (> (length s) maxlength))
26914 (setq s (substring s 0 maxlength)))))
26917 (defun org-get-entry ()
26918 "Clean-up description string."
26919 (save-excursion
26920 (org-back-to-heading t)
26921 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26923 (defun org-start-icalendar-file (name)
26924 "Start an iCalendar file by inserting the header."
26925 (let ((user user-full-name)
26926 (name (or name "unknown"))
26927 (timezone (cadr (current-time-zone))))
26928 (princ
26929 (format "BEGIN:VCALENDAR
26930 VERSION:2.0
26931 X-WR-CALNAME:%s
26932 PRODID:-//%s//Emacs with Org-mode//EN
26933 X-WR-TIMEZONE:%s
26934 CALSCALE:GREGORIAN\n" name user timezone))))
26936 (defun org-finish-icalendar-file ()
26937 "Finish an iCalendar file by inserting the END statement."
26938 (princ "END:VCALENDAR\n"))
26940 (defun org-ical-ts-to-string (s keyword &optional inc)
26941 "Take a time string S and convert it to iCalendar format.
26942 KEYWORD is added in front, to make a complete line like DTSTART....
26943 When INC is non-nil, increase the hour by two (if time string contains
26944 a time), or the day by one (if it does not contain a time)."
26945 (let ((t1 (org-parse-time-string s 'nodefault))
26946 t2 fmt have-time time)
26947 (if (and (car t1) (nth 1 t1) (nth 2 t1))
26948 (setq t2 t1 have-time t)
26949 (setq t2 (org-parse-time-string s)))
26950 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
26951 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
26952 (when inc
26953 (if have-time
26954 (if org-agenda-default-appointment-duration
26955 (setq mi (+ org-agenda-default-appointment-duration mi))
26956 (setq h (+ 2 h)))
26957 (setq d (1+ d))))
26958 (setq time (encode-time s mi h d m y)))
26959 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
26960 (concat keyword (format-time-string fmt time))))
26962 ;;; XOXO export
26964 (defun org-export-as-xoxo-insert-into (buffer &rest output)
26965 (with-current-buffer buffer
26966 (apply 'insert output)))
26967 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
26969 (defun org-export-as-xoxo (&optional buffer)
26970 "Export the org buffer as XOXO.
26971 The XOXO buffer is named *xoxo-<source buffer name>*"
26972 (interactive (list (current-buffer)))
26973 ;; A quickie abstraction
26975 ;; Output everything as XOXO
26976 (with-current-buffer (get-buffer buffer)
26977 (let* ((pos (point))
26978 (opt-plist (org-combine-plists (org-default-export-plist)
26979 (org-infile-export-plist)))
26980 (filename (concat (file-name-as-directory
26981 (org-export-directory :xoxo opt-plist))
26982 (file-name-sans-extension
26983 (file-name-nondirectory buffer-file-name))
26984 ".html"))
26985 (out (find-file-noselect filename))
26986 (last-level 1)
26987 (hanging-li nil))
26988 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
26989 ;; Check the output buffer is empty.
26990 (with-current-buffer out (erase-buffer))
26991 ;; Kick off the output
26992 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
26993 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
26994 (let* ((hd (match-string-no-properties 1))
26995 (level (length hd))
26996 (text (concat
26997 (match-string-no-properties 2)
26998 (save-excursion
26999 (goto-char (match-end 0))
27000 (let ((str ""))
27001 (catch 'loop
27002 (while 't
27003 (forward-line)
27004 (if (looking-at "^[ \t]\\(.*\\)")
27005 (setq str (concat str (match-string-no-properties 1)))
27006 (throw 'loop str)))))))))
27008 ;; Handle level rendering
27009 (cond
27010 ((> level last-level)
27011 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
27013 ((< level last-level)
27014 (dotimes (- (- last-level level) 1)
27015 (if hanging-li
27016 (org-export-as-xoxo-insert-into out "</li>\n"))
27017 (org-export-as-xoxo-insert-into out "</ol>\n"))
27018 (when hanging-li
27019 (org-export-as-xoxo-insert-into out "</li>\n")
27020 (setq hanging-li nil)))
27022 ((equal level last-level)
27023 (if hanging-li
27024 (org-export-as-xoxo-insert-into out "</li>\n")))
27027 (setq last-level level)
27029 ;; And output the new li
27030 (setq hanging-li 't)
27031 (if (equal ?+ (elt text 0))
27032 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
27033 (org-export-as-xoxo-insert-into out "<li>" text))))
27035 ;; Finally finish off the ol
27036 (dotimes (- last-level 1)
27037 (if hanging-li
27038 (org-export-as-xoxo-insert-into out "</li>\n"))
27039 (org-export-as-xoxo-insert-into out "</ol>\n"))
27041 (goto-char pos)
27042 ;; Finish the buffer off and clean it up.
27043 (switch-to-buffer-other-window out)
27044 (indent-region (point-min) (point-max) nil)
27045 (save-buffer)
27046 (goto-char (point-min))
27050 ;;;; Key bindings
27052 ;; Make `C-c C-x' a prefix key
27053 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
27055 ;; TAB key with modifiers
27056 (org-defkey org-mode-map "\C-i" 'org-cycle)
27057 (org-defkey org-mode-map [(tab)] 'org-cycle)
27058 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
27059 (org-defkey org-mode-map [(meta tab)] 'org-complete)
27060 (org-defkey org-mode-map "\M-\t" 'org-complete)
27061 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
27062 ;; The following line is necessary under Suse GNU/Linux
27063 (unless (featurep 'xemacs)
27064 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
27065 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
27066 (define-key org-mode-map [backtab] 'org-shifttab)
27068 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
27069 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
27070 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
27072 ;; Cursor keys with modifiers
27073 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
27074 (org-defkey org-mode-map [(meta right)] 'org-metaright)
27075 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27076 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27078 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27079 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27080 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27081 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27083 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27084 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27085 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27086 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27088 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27089 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27091 ;;; Extra keys for tty access.
27092 ;; We only set them when really needed because otherwise the
27093 ;; menus don't show the simple keys
27095 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27096 (not window-system))
27097 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27098 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27099 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27100 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27101 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27102 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27103 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27104 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27105 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27106 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27107 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27108 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27109 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27110 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27111 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27112 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27113 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27114 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27115 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27116 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27117 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27118 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27120 ;; All the other keys
27122 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27123 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27124 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27125 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27126 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27127 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27128 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27129 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27130 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27131 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27132 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27133 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27134 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27135 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27136 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27137 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27138 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27139 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27140 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27141 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27142 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27143 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27144 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27145 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27146 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27147 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27148 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27149 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27150 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27151 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27152 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27153 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27154 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27155 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27156 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27157 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27158 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27159 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27160 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27161 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27162 (org-defkey org-mode-map "\C-c^" 'org-sort)
27163 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27164 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27165 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27166 (org-defkey org-mode-map "\C-m" 'org-return)
27167 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27168 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27169 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27170 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27171 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27172 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27173 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27174 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27175 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27176 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27177 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27178 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27179 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27180 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27181 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27182 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27184 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27185 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27186 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27187 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27189 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27190 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27191 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27192 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27193 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27194 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27195 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27196 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27197 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27198 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27199 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27200 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27202 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27204 (when (featurep 'xemacs)
27205 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27207 (defsubst org-table-p () (org-at-table-p))
27209 (defun org-self-insert-command (N)
27210 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27211 If the cursor is in a table looking at whitespace, the whitespace is
27212 overwritten, and the table is not marked as requiring realignment."
27213 (interactive "p")
27214 (if (and (org-table-p)
27215 (progn
27216 ;; check if we blank the field, and if that triggers align
27217 (and org-table-auto-blank-field
27218 (member last-command
27219 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27220 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27221 ;; got extra space, this field does not determine column width
27222 (let (org-table-may-need-update) (org-table-blank-field))
27223 ;; no extra space, this field may determine column width
27224 (org-table-blank-field)))
27226 (eq N 1)
27227 (looking-at "[^|\n]* |"))
27228 (let (org-table-may-need-update)
27229 (goto-char (1- (match-end 0)))
27230 (delete-backward-char 1)
27231 (goto-char (match-beginning 0))
27232 (self-insert-command N))
27233 (setq org-table-may-need-update t)
27234 (self-insert-command N)
27235 (org-fix-tags-on-the-fly)))
27237 (defun org-fix-tags-on-the-fly ()
27238 (when (and (equal (char-after (point-at-bol)) ?*)
27239 (org-on-heading-p))
27240 (org-align-tags-here org-tags-column)))
27242 (defun org-delete-backward-char (N)
27243 "Like `delete-backward-char', insert whitespace at field end in tables.
27244 When deleting backwards, in tables this function will insert whitespace in
27245 front of the next \"|\" separator, to keep the table aligned. The table will
27246 still be marked for re-alignment if the field did fill the entire column,
27247 because, in this case the deletion might narrow the column."
27248 (interactive "p")
27249 (if (and (org-table-p)
27250 (eq N 1)
27251 (string-match "|" (buffer-substring (point-at-bol) (point)))
27252 (looking-at ".*?|"))
27253 (let ((pos (point))
27254 (noalign (looking-at "[^|\n\r]* |"))
27255 (c org-table-may-need-update))
27256 (backward-delete-char N)
27257 (skip-chars-forward "^|")
27258 (insert " ")
27259 (goto-char (1- pos))
27260 ;; noalign: if there were two spaces at the end, this field
27261 ;; does not determine the width of the column.
27262 (if noalign (setq org-table-may-need-update c)))
27263 (backward-delete-char N)
27264 (org-fix-tags-on-the-fly)))
27266 (defun org-delete-char (N)
27267 "Like `delete-char', but insert whitespace at field end in tables.
27268 When deleting characters, in tables this function will insert whitespace in
27269 front of the next \"|\" separator, to keep the table aligned. The table will
27270 still be marked for re-alignment if the field did fill the entire column,
27271 because, in this case the deletion might narrow the column."
27272 (interactive "p")
27273 (if (and (org-table-p)
27274 (not (bolp))
27275 (not (= (char-after) ?|))
27276 (eq N 1))
27277 (if (looking-at ".*?|")
27278 (let ((pos (point))
27279 (noalign (looking-at "[^|\n\r]* |"))
27280 (c org-table-may-need-update))
27281 (replace-match (concat
27282 (substring (match-string 0) 1 -1)
27283 " |"))
27284 (goto-char pos)
27285 ;; noalign: if there were two spaces at the end, this field
27286 ;; does not determine the width of the column.
27287 (if noalign (setq org-table-may-need-update c)))
27288 (delete-char N))
27289 (delete-char N)
27290 (org-fix-tags-on-the-fly)))
27292 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27293 (put 'org-self-insert-command 'delete-selection t)
27294 (put 'orgtbl-self-insert-command 'delete-selection t)
27295 (put 'org-delete-char 'delete-selection 'supersede)
27296 (put 'org-delete-backward-char 'delete-selection 'supersede)
27298 ;; Make `flyspell-mode' delay after some commands
27299 (put 'org-self-insert-command 'flyspell-delayed t)
27300 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27301 (put 'org-delete-char 'flyspell-delayed t)
27302 (put 'org-delete-backward-char 'flyspell-delayed t)
27304 ;; Make pabbrev-mode expand after org-mode commands
27305 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27306 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27308 ;; How to do this: Measure non-white length of current string
27309 ;; If equal to column width, we should realign.
27311 (defun org-remap (map &rest commands)
27312 "In MAP, remap the functions given in COMMANDS.
27313 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27314 (let (new old)
27315 (while commands
27316 (setq old (pop commands) new (pop commands))
27317 (if (fboundp 'command-remapping)
27318 (org-defkey map (vector 'remap old) new)
27319 (substitute-key-definition old new map global-map)))))
27321 (when (eq org-enable-table-editor 'optimized)
27322 ;; If the user wants maximum table support, we need to hijack
27323 ;; some standard editing functions
27324 (org-remap org-mode-map
27325 'self-insert-command 'org-self-insert-command
27326 'delete-char 'org-delete-char
27327 'delete-backward-char 'org-delete-backward-char)
27328 (org-defkey org-mode-map "|" 'org-force-self-insert))
27330 (defun org-shiftcursor-error ()
27331 "Throw an error because Shift-Cursor command was applied in wrong context."
27332 (error "This command is active in special context like tables, headlines or timestamps"))
27334 (defun org-shifttab (&optional arg)
27335 "Global visibility cycling or move to previous table field.
27336 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27337 on context.
27338 See the individual commands for more information."
27339 (interactive "P")
27340 (cond
27341 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27342 (arg (message "Content view to level: ")
27343 (org-content (prefix-numeric-value arg))
27344 (setq org-cycle-global-status 'overview))
27345 (t (call-interactively 'org-global-cycle))))
27347 (defun org-shiftmetaleft ()
27348 "Promote subtree or delete table column.
27349 Calls `org-promote-subtree', `org-outdent-item',
27350 or `org-table-delete-column', depending on context.
27351 See the individual commands for more information."
27352 (interactive)
27353 (cond
27354 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27355 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27356 ((org-at-item-p) (call-interactively 'org-outdent-item))
27357 (t (org-shiftcursor-error))))
27359 (defun org-shiftmetaright ()
27360 "Demote subtree or insert table column.
27361 Calls `org-demote-subtree', `org-indent-item',
27362 or `org-table-insert-column', depending on context.
27363 See the individual commands for more information."
27364 (interactive)
27365 (cond
27366 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27367 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27368 ((org-at-item-p) (call-interactively 'org-indent-item))
27369 (t (org-shiftcursor-error))))
27371 (defun org-shiftmetaup (&optional arg)
27372 "Move subtree up or kill table row.
27373 Calls `org-move-subtree-up' or `org-table-kill-row' or
27374 `org-move-item-up' depending on context. See the individual commands
27375 for more information."
27376 (interactive "P")
27377 (cond
27378 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27379 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27380 ((org-at-item-p) (call-interactively 'org-move-item-up))
27381 (t (org-shiftcursor-error))))
27382 (defun org-shiftmetadown (&optional arg)
27383 "Move subtree down or insert table row.
27384 Calls `org-move-subtree-down' or `org-table-insert-row' or
27385 `org-move-item-down', depending on context. See the individual
27386 commands for more information."
27387 (interactive "P")
27388 (cond
27389 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27390 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27391 ((org-at-item-p) (call-interactively 'org-move-item-down))
27392 (t (org-shiftcursor-error))))
27394 (defun org-metaleft (&optional arg)
27395 "Promote heading or move table column to left.
27396 Calls `org-do-promote' or `org-table-move-column', depending on context.
27397 With no specific context, calls the Emacs default `backward-word'.
27398 See the individual commands for more information."
27399 (interactive "P")
27400 (cond
27401 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27402 ((or (org-on-heading-p) (org-region-active-p))
27403 (call-interactively 'org-do-promote))
27404 ((org-at-item-p) (call-interactively 'org-outdent-item))
27405 (t (call-interactively 'backward-word))))
27407 (defun org-metaright (&optional arg)
27408 "Demote subtree or move table column to right.
27409 Calls `org-do-demote' or `org-table-move-column', depending on context.
27410 With no specific context, calls the Emacs default `forward-word'.
27411 See the individual commands for more information."
27412 (interactive "P")
27413 (cond
27414 ((org-at-table-p) (call-interactively 'org-table-move-column))
27415 ((or (org-on-heading-p) (org-region-active-p))
27416 (call-interactively 'org-do-demote))
27417 ((org-at-item-p) (call-interactively 'org-indent-item))
27418 (t (call-interactively 'forward-word))))
27420 (defun org-metaup (&optional arg)
27421 "Move subtree up or move table row up.
27422 Calls `org-move-subtree-up' or `org-table-move-row' or
27423 `org-move-item-up', depending on context. See the individual commands
27424 for more information."
27425 (interactive "P")
27426 (cond
27427 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27428 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27429 ((org-at-item-p) (call-interactively 'org-move-item-up))
27430 (t (transpose-lines 1) (beginning-of-line -1))))
27432 (defun org-metadown (&optional arg)
27433 "Move subtree down or move table row down.
27434 Calls `org-move-subtree-down' or `org-table-move-row' or
27435 `org-move-item-down', depending on context. See the individual
27436 commands for more information."
27437 (interactive "P")
27438 (cond
27439 ((org-at-table-p) (call-interactively 'org-table-move-row))
27440 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27441 ((org-at-item-p) (call-interactively 'org-move-item-down))
27442 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27444 (defun org-shiftup (&optional arg)
27445 "Increase item in timestamp or increase priority of current headline.
27446 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27447 depending on context. See the individual commands for more information."
27448 (interactive "P")
27449 (cond
27450 ((org-at-timestamp-p t)
27451 (call-interactively (if org-edit-timestamp-down-means-later
27452 'org-timestamp-down 'org-timestamp-up)))
27453 ((org-on-heading-p) (call-interactively 'org-priority-up))
27454 ((org-at-item-p) (call-interactively 'org-previous-item))
27455 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27457 (defun org-shiftdown (&optional arg)
27458 "Decrease item in timestamp or decrease priority of current headline.
27459 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27460 depending on context. See the individual commands for more information."
27461 (interactive "P")
27462 (cond
27463 ((org-at-timestamp-p t)
27464 (call-interactively (if org-edit-timestamp-down-means-later
27465 'org-timestamp-up 'org-timestamp-down)))
27466 ((org-on-heading-p) (call-interactively 'org-priority-down))
27467 (t (call-interactively 'org-next-item))))
27469 (defun org-shiftright ()
27470 "Next TODO keyword or timestamp one day later, depending on context."
27471 (interactive)
27472 (cond
27473 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27474 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27475 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27476 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27477 (t (org-shiftcursor-error))))
27479 (defun org-shiftleft ()
27480 "Previous TODO keyword or timestamp one day earlier, depending on context."
27481 (interactive)
27482 (cond
27483 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27484 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27485 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27486 ((org-at-property-p)
27487 (call-interactively 'org-property-previous-allowed-value))
27488 (t (org-shiftcursor-error))))
27490 (defun org-shiftcontrolright ()
27491 "Switch to next TODO set."
27492 (interactive)
27493 (cond
27494 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27495 (t (org-shiftcursor-error))))
27497 (defun org-shiftcontrolleft ()
27498 "Switch to previous TODO set."
27499 (interactive)
27500 (cond
27501 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27502 (t (org-shiftcursor-error))))
27504 (defun org-ctrl-c-ret ()
27505 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27506 (interactive)
27507 (cond
27508 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27509 (t (call-interactively 'org-insert-heading))))
27511 (defun org-copy-special ()
27512 "Copy region in table or copy current subtree.
27513 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27514 See the individual commands for more information."
27515 (interactive)
27516 (call-interactively
27517 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27519 (defun org-cut-special ()
27520 "Cut region in table or cut current subtree.
27521 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27522 See the individual commands for more information."
27523 (interactive)
27524 (call-interactively
27525 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27527 (defun org-paste-special (arg)
27528 "Paste rectangular region into table, or past subtree relative to level.
27529 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27530 See the individual commands for more information."
27531 (interactive "P")
27532 (if (org-at-table-p)
27533 (org-table-paste-rectangle)
27534 (org-paste-subtree arg)))
27536 (defun org-ctrl-c-ctrl-c (&optional arg)
27537 "Set tags in headline, or update according to changed information at point.
27539 This command does many different things, depending on context:
27541 - If the cursor is in a headline, prompt for tags and insert them
27542 into the current line, aligned to `org-tags-column'. When called
27543 with prefix arg, realign all tags in the current buffer.
27545 - If the cursor is in one of the special #+KEYWORD lines, this
27546 triggers scanning the buffer for these lines and updating the
27547 information.
27549 - If the cursor is inside a table, realign the table. This command
27550 works even if the automatic table editor has been turned off.
27552 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27553 the entire table.
27555 - If the cursor is a the beginning of a dynamic block, update it.
27557 - If the cursor is inside a table created by the table.el package,
27558 activate that table.
27560 - If the current buffer is a remember buffer, close note and file it.
27561 with a prefix argument, file it without further interaction to the default
27562 location.
27564 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27565 links in this buffer.
27567 - If the cursor is on a numbered item in a plain list, renumber the
27568 ordered list.
27570 - If the cursor is on a checkbox, toggle it."
27571 (interactive "P")
27572 (let ((org-enable-table-editor t))
27573 (cond
27574 ((or org-clock-overlays
27575 org-occur-highlights
27576 org-latex-fragment-image-overlays)
27577 (org-remove-clock-overlays)
27578 (org-remove-occur-highlights)
27579 (org-remove-latex-fragment-image-overlays)
27580 (message "Temporary highlights/overlays removed from current buffer"))
27581 ((and (local-variable-p 'org-finish-function (current-buffer))
27582 (fboundp org-finish-function))
27583 (funcall org-finish-function))
27584 ((org-at-property-p)
27585 (call-interactively 'org-property-action))
27586 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27587 ((org-on-heading-p) (call-interactively 'org-set-tags))
27588 ((org-at-table.el-p)
27589 (require 'table)
27590 (beginning-of-line 1)
27591 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27592 (call-interactively 'table-recognize-table))
27593 ((org-at-table-p)
27594 (org-table-maybe-eval-formula)
27595 (if arg
27596 (call-interactively 'org-table-recalculate)
27597 (org-table-maybe-recalculate-line))
27598 (call-interactively 'org-table-align))
27599 ((org-at-item-checkbox-p)
27600 (call-interactively 'org-toggle-checkbox))
27601 ((org-at-item-p)
27602 (call-interactively 'org-maybe-renumber-ordered-list))
27603 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27604 ;; Dynamic block
27605 (beginning-of-line 1)
27606 (org-update-dblock))
27607 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27608 (cond
27609 ((equal (match-string 1) "TBLFM")
27610 ;; Recalculate the table before this line
27611 (save-excursion
27612 (beginning-of-line 1)
27613 (skip-chars-backward " \r\n\t")
27614 (if (org-at-table-p)
27615 (org-call-with-arg 'org-table-recalculate t))))
27617 (call-interactively 'org-mode-restart))))
27618 (t (error "C-c C-c can do nothing useful at this location.")))))
27620 (defun org-mode-restart ()
27621 "Restart Org-mode, to scan again for special lines.
27622 Also updates the keyword regular expressions."
27623 (interactive)
27624 (let ((org-inhibit-startup t)) (org-mode))
27625 (message "Org-mode restarted to refresh keyword and special line setup"))
27627 (defun org-kill-note-or-show-branches ()
27628 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27629 (interactive)
27630 (if (not org-finish-function)
27631 (call-interactively 'show-branches)
27632 (let ((org-note-abort t))
27633 (funcall org-finish-function))))
27635 (defun org-return (&optional indent)
27636 "Goto next table row or insert a newline.
27637 Calls `org-table-next-row' or `newline', depending on context.
27638 See the individual commands for more information."
27639 (interactive)
27640 (cond
27641 ((bobp) (if indent (newline-and-indent) (newline)))
27642 ((and (org-at-heading-p)
27643 (looking-at
27644 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27645 (org-show-entry)
27646 (end-of-line 1)
27647 (newline))
27648 ((org-at-table-p)
27649 (org-table-justify-field-maybe)
27650 (call-interactively 'org-table-next-row))
27651 (t (if indent (newline-and-indent) (newline)))))
27653 (defun org-return-indent ()
27654 "Goto next table row or insert a newline and indent.
27655 Calls `org-table-next-row' or `newline-and-indent', depending on
27656 context. See the individual commands for more information."
27657 (interactive)
27658 (org-return t))
27660 (defun org-ctrl-c-star ()
27661 "Compute table, or change heading status of lines.
27662 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27663 depending on context. This will also turn a plain list item or a normal
27664 line into a subheading."
27665 (interactive)
27666 (cond
27667 ((org-at-table-p)
27668 (call-interactively 'org-table-recalculate))
27669 ((org-region-active-p)
27670 ;; Convert all lines in region to list items
27671 (call-interactively 'org-toggle-region-headings))
27672 ((org-on-heading-p)
27673 (org-toggle-region-headings (point-at-bol)
27674 (min (1+ (point-at-eol)) (point-max))))
27675 ((org-at-item-p)
27676 ;; Convert to heading
27677 ;; FIXME: not yet implemented
27679 (t (org-toggle-region-headings (point-at-bol)
27680 (min (1+ (point-at-eol)) (point-max))))))
27682 (defun org-ctrl-c-minus ()
27683 "Insert separator line in table or modify bullet status of line.
27684 Also turns a plain line or a region of lines into list items.
27685 Calls `org-table-insert-hline', `org-toggle-region-items', or
27686 `org-cycle-list-bullet', depending on context."
27687 (interactive)
27688 (cond
27689 ((org-at-table-p)
27690 (call-interactively 'org-table-insert-hline))
27691 ((org-on-heading-p)
27692 ;; Convert to item
27693 (save-excursion
27694 (beginning-of-line 1)
27695 (if (looking-at "\\*+ ")
27696 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27697 ((org-region-active-p)
27698 ;; Convert all lines in region to list items
27699 (call-interactively 'org-toggle-region-items))
27700 ((org-in-item-p)
27701 (call-interactively 'org-cycle-list-bullet))
27702 (t (org-toggle-region-items (point-at-bol)
27703 (min (1+ (point-at-eol)) (point-max))))))
27705 (defun org-toggle-region-items (beg end)
27706 "Convert all lines in region to list items.
27707 If the first line is already an item, convert all list items in the region
27708 to normal lines."
27709 (interactive "r")
27710 (let (l2 l)
27711 (save-excursion
27712 (goto-char end)
27713 (setq l2 (org-current-line))
27714 (goto-char beg)
27715 (beginning-of-line 1)
27716 (setq l (1- (org-current-line)))
27717 (if (org-at-item-p)
27718 ;; We already have items, de-itemize
27719 (while (< (setq l (1+ l)) l2)
27720 (when (org-at-item-p)
27721 (goto-char (match-beginning 2))
27722 (delete-region (match-beginning 2) (match-end 2))
27723 (and (looking-at "[ \t]+") (replace-match "")))
27724 (beginning-of-line 2))
27725 (while (< (setq l (1+ l)) l2)
27726 (unless (org-at-item-p)
27727 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27728 (replace-match "\\1- \\2")))
27729 (beginning-of-line 2))))))
27731 (defun org-toggle-region-headings (beg end)
27732 "Convert all lines in region to list items.
27733 If the first line is already an item, convert all list items in the region
27734 to normal lines."
27735 (interactive "r")
27736 (let (l2 l)
27737 (save-excursion
27738 (goto-char end)
27739 (setq l2 (org-current-line))
27740 (goto-char beg)
27741 (beginning-of-line 1)
27742 (setq l (1- (org-current-line)))
27743 (if (org-on-heading-p)
27744 ;; We already have headlines, de-star them
27745 (while (< (setq l (1+ l)) l2)
27746 (when (org-on-heading-p t)
27747 (and (looking-at outline-regexp) (replace-match "")))
27748 (beginning-of-line 2))
27749 (let* ((stars (save-excursion
27750 (re-search-backward org-complex-heading-regexp nil t)
27751 (or (match-string 1) "*")))
27752 (add-stars (if org-odd-levels-only "**" "*"))
27753 (rpl (concat stars add-stars " \\2")))
27754 (while (< (setq l (1+ l)) l2)
27755 (unless (org-on-heading-p)
27756 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27757 (replace-match rpl)))
27758 (beginning-of-line 2)))))))
27760 (defun org-meta-return (&optional arg)
27761 "Insert a new heading or wrap a region in a table.
27762 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27763 See the individual commands for more information."
27764 (interactive "P")
27765 (cond
27766 ((org-at-table-p)
27767 (call-interactively 'org-table-wrap-region))
27768 (t (call-interactively 'org-insert-heading))))
27770 ;;; Menu entries
27772 ;; Define the Org-mode menus
27773 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27774 '("Tbl"
27775 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27776 ["Next Field" org-cycle (org-at-table-p)]
27777 ["Previous Field" org-shifttab (org-at-table-p)]
27778 ["Next Row" org-return (org-at-table-p)]
27779 "--"
27780 ["Blank Field" org-table-blank-field (org-at-table-p)]
27781 ["Edit Field" org-table-edit-field (org-at-table-p)]
27782 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27783 "--"
27784 ("Column"
27785 ["Move Column Left" org-metaleft (org-at-table-p)]
27786 ["Move Column Right" org-metaright (org-at-table-p)]
27787 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27788 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27789 ("Row"
27790 ["Move Row Up" org-metaup (org-at-table-p)]
27791 ["Move Row Down" org-metadown (org-at-table-p)]
27792 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27793 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27794 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27795 "--"
27796 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27797 ("Rectangle"
27798 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27799 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27800 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27801 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27802 "--"
27803 ("Calculate"
27804 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27805 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27806 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27807 "--"
27808 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27809 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27810 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27811 "--"
27812 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27813 "--"
27814 ["Sum Column/Rectangle" org-table-sum
27815 (or (org-at-table-p) (org-region-active-p))]
27816 ["Which Column?" org-table-current-column (org-at-table-p)])
27817 ["Debug Formulas"
27818 org-table-toggle-formula-debugger
27819 :style toggle :selected org-table-formula-debug]
27820 ["Show Col/Row Numbers"
27821 org-table-toggle-coordinate-overlays
27822 :style toggle :selected org-table-overlay-coordinates]
27823 "--"
27824 ["Create" org-table-create (and (not (org-at-table-p))
27825 org-enable-table-editor)]
27826 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27827 ["Import from File" org-table-import (not (org-at-table-p))]
27828 ["Export to File" org-table-export (org-at-table-p)]
27829 "--"
27830 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27832 (easy-menu-define org-org-menu org-mode-map "Org menu"
27833 '("Org"
27834 ("Show/Hide"
27835 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27836 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27837 ["Sparse Tree" org-occur t]
27838 ["Reveal Context" org-reveal t]
27839 ["Show All" show-all t]
27840 "--"
27841 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27842 "--"
27843 ["New Heading" org-insert-heading t]
27844 ("Navigate Headings"
27845 ["Up" outline-up-heading t]
27846 ["Next" outline-next-visible-heading t]
27847 ["Previous" outline-previous-visible-heading t]
27848 ["Next Same Level" outline-forward-same-level t]
27849 ["Previous Same Level" outline-backward-same-level t]
27850 "--"
27851 ["Jump" org-goto t])
27852 ("Edit Structure"
27853 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27854 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27855 "--"
27856 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27857 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27858 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27859 "--"
27860 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27861 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27862 ["Demote Heading" org-metaright (not (org-at-table-p))]
27863 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27864 "--"
27865 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27866 "--"
27867 ["Convert to odd levels" org-convert-to-odd-levels t]
27868 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27869 ("Editing"
27870 ["Emphasis..." org-emphasize t])
27871 ("Archive"
27872 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27873 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27874 ; :active t :keys "C-u C-c C-x C-a"]
27875 ["Sparse trees open ARCHIVE trees"
27876 (setq org-sparse-tree-open-archived-trees
27877 (not org-sparse-tree-open-archived-trees))
27878 :style toggle :selected org-sparse-tree-open-archived-trees]
27879 ["Cycling opens ARCHIVE trees"
27880 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27881 :style toggle :selected org-cycle-open-archived-trees]
27882 ["Agenda includes ARCHIVE trees"
27883 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27884 :style toggle :selected (not org-agenda-skip-archived-trees)]
27885 "--"
27886 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27887 ; ["Check and Move Children" (org-archive-subtree '(4))
27888 ; :active t :keys "C-u C-c C-x C-s"]
27890 "--"
27891 ("TODO Lists"
27892 ["TODO/DONE/-" org-todo t]
27893 ("Select keyword"
27894 ["Next keyword" org-shiftright (org-on-heading-p)]
27895 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27896 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27897 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27898 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27899 ["Show TODO Tree" org-show-todo-tree t]
27900 ["Global TODO list" org-todo-list t]
27901 "--"
27902 ["Set Priority" org-priority t]
27903 ["Priority Up" org-shiftup t]
27904 ["Priority Down" org-shiftdown t])
27905 ("TAGS and Properties"
27906 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27907 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27908 "--"
27909 ["Set property" 'org-set-property t]
27910 ["Column view of properties" org-columns t]
27911 ["Insert Column View DBlock" org-insert-columns-dblock t])
27912 ("Dates and Scheduling"
27913 ["Timestamp" org-time-stamp t]
27914 ["Timestamp (inactive)" org-time-stamp-inactive t]
27915 ("Change Date"
27916 ["1 Day Later" org-shiftright t]
27917 ["1 Day Earlier" org-shiftleft t]
27918 ["1 ... Later" org-shiftup t]
27919 ["1 ... Earlier" org-shiftdown t])
27920 ["Compute Time Range" org-evaluate-time-range t]
27921 ["Schedule Item" org-schedule t]
27922 ["Deadline" org-deadline t]
27923 "--"
27924 ["Custom time format" org-toggle-time-stamp-overlays
27925 :style radio :selected org-display-custom-times]
27926 "--"
27927 ["Goto Calendar" org-goto-calendar t]
27928 ["Date from Calendar" org-date-from-calendar t])
27929 ("Logging work"
27930 ["Clock in" org-clock-in t]
27931 ["Clock out" org-clock-out t]
27932 ["Clock cancel" org-clock-cancel t]
27933 ["Goto running clock" org-clock-goto t]
27934 ["Display times" org-clock-display t]
27935 ["Create clock table" org-clock-report t]
27936 "--"
27937 ["Record DONE time"
27938 (progn (setq org-log-done (not org-log-done))
27939 (message "Switching to %s will %s record a timestamp"
27940 (car org-done-keywords)
27941 (if org-log-done "automatically" "not")))
27942 :style toggle :selected org-log-done])
27943 "--"
27944 ["Agenda Command..." org-agenda t]
27945 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
27946 ("File List for Agenda")
27947 ("Special views current file"
27948 ["TODO Tree" org-show-todo-tree t]
27949 ["Check Deadlines" org-check-deadlines t]
27950 ["Timeline" org-timeline t]
27951 ["Tags Tree" org-tags-sparse-tree t])
27952 "--"
27953 ("Hyperlinks"
27954 ["Store Link (Global)" org-store-link t]
27955 ["Insert Link" org-insert-link t]
27956 ["Follow Link" org-open-at-point t]
27957 "--"
27958 ["Next link" org-next-link t]
27959 ["Previous link" org-previous-link t]
27960 "--"
27961 ["Descriptive Links"
27962 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
27963 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
27964 ["Literal Links"
27965 (progn
27966 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
27967 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
27968 "--"
27969 ["Export/Publish..." org-export t]
27970 ("LaTeX"
27971 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
27972 :selected org-cdlatex-mode]
27973 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
27974 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
27975 ["Modify math symbol" org-cdlatex-math-modify
27976 (org-inside-LaTeX-fragment-p)]
27977 ["Export LaTeX fragments as images"
27978 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
27979 :style toggle :selected org-export-with-LaTeX-fragments])
27980 "--"
27981 ("Documentation"
27982 ["Show Version" org-version t]
27983 ["Info Documentation" org-info t])
27984 ("Customize"
27985 ["Browse Org Group" org-customize t]
27986 "--"
27987 ["Expand This Menu" org-create-customize-menu
27988 (fboundp 'customize-menu-create)])
27989 "--"
27990 ["Refresh setup" org-mode-restart t]
27993 (defun org-info (&optional node)
27994 "Read documentation for Org-mode in the info system.
27995 With optional NODE, go directly to that node."
27996 (interactive)
27997 (info (format "(org)%s" (or node ""))))
27999 (defun org-install-agenda-files-menu ()
28000 (let ((bl (buffer-list)))
28001 (save-excursion
28002 (while bl
28003 (set-buffer (pop bl))
28004 (if (org-mode-p) (setq bl nil)))
28005 (when (org-mode-p)
28006 (easy-menu-change
28007 '("Org") "File List for Agenda"
28008 (append
28009 (list
28010 ["Edit File List" (org-edit-agenda-file-list) t]
28011 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
28012 ["Remove Current File from List" org-remove-file t]
28013 ["Cycle through agenda files" org-cycle-agenda-files t]
28014 ["Occur in all agenda files" org-occur-in-agenda-files t]
28015 "--")
28016 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
28018 ;;;; Documentation
28020 (defun org-customize ()
28021 "Call the customize function with org as argument."
28022 (interactive)
28023 (customize-browse 'org))
28025 (defun org-create-customize-menu ()
28026 "Create a full customization menu for Org-mode, insert it into the menu."
28027 (interactive)
28028 (if (fboundp 'customize-menu-create)
28029 (progn
28030 (easy-menu-change
28031 '("Org") "Customize"
28032 `(["Browse Org group" org-customize t]
28033 "--"
28034 ,(customize-menu-create 'org)
28035 ["Set" Custom-set t]
28036 ["Save" Custom-save t]
28037 ["Reset to Current" Custom-reset-current t]
28038 ["Reset to Saved" Custom-reset-saved t]
28039 ["Reset to Standard Settings" Custom-reset-standard t]))
28040 (message "\"Org\"-menu now contains full customization menu"))
28041 (error "Cannot expand menu (outdated version of cus-edit.el)")))
28043 ;;;; Miscellaneous stuff
28046 ;;; Generally useful functions
28048 (defun org-context ()
28049 "Return a list of contexts of the current cursor position.
28050 If several contexts apply, all are returned.
28051 Each context entry is a list with a symbol naming the context, and
28052 two positions indicating start and end of the context. Possible
28053 contexts are:
28055 :headline anywhere in a headline
28056 :headline-stars on the leading stars in a headline
28057 :todo-keyword on a TODO keyword (including DONE) in a headline
28058 :tags on the TAGS in a headline
28059 :priority on the priority cookie in a headline
28060 :item on the first line of a plain list item
28061 :item-bullet on the bullet/number of a plain list item
28062 :checkbox on the checkbox in a plain list item
28063 :table in an org-mode table
28064 :table-special on a special filed in a table
28065 :table-table in a table.el table
28066 :link on a hyperlink
28067 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
28068 :target on a <<target>>
28069 :radio-target on a <<<radio-target>>>
28070 :latex-fragment on a LaTeX fragment
28071 :latex-preview on a LaTeX fragment with overlayed preview image
28073 This function expects the position to be visible because it uses font-lock
28074 faces as a help to recognize the following contexts: :table-special, :link,
28075 and :keyword."
28076 (let* ((f (get-text-property (point) 'face))
28077 (faces (if (listp f) f (list f)))
28078 (p (point)) clist o)
28079 ;; First the large context
28080 (cond
28081 ((org-on-heading-p t)
28082 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28083 (when (progn
28084 (beginning-of-line 1)
28085 (looking-at org-todo-line-tags-regexp))
28086 (push (org-point-in-group p 1 :headline-stars) clist)
28087 (push (org-point-in-group p 2 :todo-keyword) clist)
28088 (push (org-point-in-group p 4 :tags) clist))
28089 (goto-char p)
28090 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28091 (if (looking-at "\\[#[A-Z0-9]\\]")
28092 (push (org-point-in-group p 0 :priority) clist)))
28094 ((org-at-item-p)
28095 (push (org-point-in-group p 2 :item-bullet) clist)
28096 (push (list :item (point-at-bol)
28097 (save-excursion (org-end-of-item) (point)))
28098 clist)
28099 (and (org-at-item-checkbox-p)
28100 (push (org-point-in-group p 0 :checkbox) clist)))
28102 ((org-at-table-p)
28103 (push (list :table (org-table-begin) (org-table-end)) clist)
28104 (if (memq 'org-formula faces)
28105 (push (list :table-special
28106 (previous-single-property-change p 'face)
28107 (next-single-property-change p 'face)) clist)))
28108 ((org-at-table-p 'any)
28109 (push (list :table-table) clist)))
28110 (goto-char p)
28112 ;; Now the small context
28113 (cond
28114 ((org-at-timestamp-p)
28115 (push (org-point-in-group p 0 :timestamp) clist))
28116 ((memq 'org-link faces)
28117 (push (list :link
28118 (previous-single-property-change p 'face)
28119 (next-single-property-change p 'face)) clist))
28120 ((memq 'org-special-keyword faces)
28121 (push (list :keyword
28122 (previous-single-property-change p 'face)
28123 (next-single-property-change p 'face)) clist))
28124 ((org-on-target-p)
28125 (push (org-point-in-group p 0 :target) clist)
28126 (goto-char (1- (match-beginning 0)))
28127 (if (looking-at org-radio-target-regexp)
28128 (push (org-point-in-group p 0 :radio-target) clist))
28129 (goto-char p))
28130 ((setq o (car (delq nil
28131 (mapcar
28132 (lambda (x)
28133 (if (memq x org-latex-fragment-image-overlays) x))
28134 (org-overlays-at (point))))))
28135 (push (list :latex-fragment
28136 (org-overlay-start o) (org-overlay-end o)) clist)
28137 (push (list :latex-preview
28138 (org-overlay-start o) (org-overlay-end o)) clist))
28139 ((org-inside-LaTeX-fragment-p)
28140 ;; FIXME: positions wrong.
28141 (push (list :latex-fragment (point) (point)) clist)))
28143 (setq clist (nreverse (delq nil clist)))
28144 clist))
28146 ;; FIXME: Compare with at-regexp-p Do we need both?
28147 (defun org-in-regexp (re &optional nlines visually)
28148 "Check if point is inside a match of regexp.
28149 Normally only the current line is checked, but you can include NLINES extra
28150 lines both before and after point into the search.
28151 If VISUALLY is set, require that the cursor is not after the match but
28152 really on, so that the block visually is on the match."
28153 (catch 'exit
28154 (let ((pos (point))
28155 (eol (point-at-eol (+ 1 (or nlines 0))))
28156 (inc (if visually 1 0)))
28157 (save-excursion
28158 (beginning-of-line (- 1 (or nlines 0)))
28159 (while (re-search-forward re eol t)
28160 (if (and (<= (match-beginning 0) pos)
28161 (>= (+ inc (match-end 0)) pos))
28162 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28164 (defun org-at-regexp-p (regexp)
28165 "Is point inside a match of REGEXP in the current line?"
28166 (catch 'exit
28167 (save-excursion
28168 (let ((pos (point)) (end (point-at-eol)))
28169 (beginning-of-line 1)
28170 (while (re-search-forward regexp end t)
28171 (if (and (<= (match-beginning 0) pos)
28172 (>= (match-end 0) pos))
28173 (throw 'exit t)))
28174 nil))))
28176 (defun org-occur-in-agenda-files (regexp &optional nlines)
28177 "Call `multi-occur' with buffers for all agenda files."
28178 (interactive "sOrg-files matching: \np")
28179 (let* ((files (org-agenda-files))
28180 (tnames (mapcar 'file-truename files))
28181 (extra org-agenda-text-search-extra-files)
28183 (while (setq f (pop extra))
28184 (unless (member (file-truename f) tnames)
28185 (add-to-list 'files f 'append)
28186 (add-to-list 'tnames (file-truename f) 'append)))
28187 (multi-occur
28188 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28189 regexp)))
28191 (if (boundp 'occur-mode-find-occurrence-hook)
28192 ;; Emacs 23
28193 (add-hook 'occur-mode-find-occurrence-hook
28194 (lambda ()
28195 (when (org-mode-p)
28196 (org-reveal))))
28197 ;; Emacs 22
28198 (defadvice occur-mode-goto-occurrence
28199 (after org-occur-reveal activate)
28200 (and (org-mode-p) (org-reveal)))
28201 (defadvice occur-mode-goto-occurrence-other-window
28202 (after org-occur-reveal activate)
28203 (and (org-mode-p) (org-reveal)))
28204 (defadvice occur-mode-display-occurrence
28205 (after org-occur-reveal activate)
28206 (when (org-mode-p)
28207 (let ((pos (occur-mode-find-occurrence)))
28208 (with-current-buffer (marker-buffer pos)
28209 (save-excursion
28210 (goto-char pos)
28211 (org-reveal)))))))
28213 (defun org-uniquify (list)
28214 "Remove duplicate elements from LIST."
28215 (let (res)
28216 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28217 res))
28219 (defun org-delete-all (elts list)
28220 "Remove all elements in ELTS from LIST."
28221 (while elts
28222 (setq list (delete (pop elts) list)))
28223 list)
28225 (defun org-back-over-empty-lines ()
28226 "Move backwards over witespace, to the beginning of the first empty line.
28227 Returns the number o empty lines passed."
28228 (let ((pos (point)))
28229 (skip-chars-backward " \t\n\r")
28230 (beginning-of-line 2)
28231 (goto-char (min (point) pos))
28232 (count-lines (point) pos)))
28234 (defun org-skip-whitespace ()
28235 (skip-chars-forward " \t\n\r"))
28237 (defun org-point-in-group (point group &optional context)
28238 "Check if POINT is in match-group GROUP.
28239 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28240 match. If the match group does ot exist or point is not inside it,
28241 return nil."
28242 (and (match-beginning group)
28243 (>= point (match-beginning group))
28244 (<= point (match-end group))
28245 (if context
28246 (list context (match-beginning group) (match-end group))
28247 t)))
28249 (defun org-switch-to-buffer-other-window (&rest args)
28250 "Switch to buffer in a second window on the current frame.
28251 In particular, do not allow pop-up frames."
28252 (let (pop-up-frames special-display-buffer-names special-display-regexps
28253 special-display-function)
28254 (apply 'switch-to-buffer-other-window args)))
28256 (defun org-combine-plists (&rest plists)
28257 "Create a single property list from all plists in PLISTS.
28258 The process starts by copying the first list, and then setting properties
28259 from the other lists. Settings in the last list are the most significant
28260 ones and overrule settings in the other lists."
28261 (let ((rtn (copy-sequence (pop plists)))
28262 p v ls)
28263 (while plists
28264 (setq ls (pop plists))
28265 (while ls
28266 (setq p (pop ls) v (pop ls))
28267 (setq rtn (plist-put rtn p v))))
28268 rtn))
28270 (defun org-move-line-down (arg)
28271 "Move the current line down. With prefix argument, move it past ARG lines."
28272 (interactive "p")
28273 (let ((col (current-column))
28274 beg end pos)
28275 (beginning-of-line 1) (setq beg (point))
28276 (beginning-of-line 2) (setq end (point))
28277 (beginning-of-line (+ 1 arg))
28278 (setq pos (move-marker (make-marker) (point)))
28279 (insert (delete-and-extract-region beg end))
28280 (goto-char pos)
28281 (move-to-column col)))
28283 (defun org-move-line-up (arg)
28284 "Move the current line up. With prefix argument, move it past ARG lines."
28285 (interactive "p")
28286 (let ((col (current-column))
28287 beg end pos)
28288 (beginning-of-line 1) (setq beg (point))
28289 (beginning-of-line 2) (setq end (point))
28290 (beginning-of-line (- arg))
28291 (setq pos (move-marker (make-marker) (point)))
28292 (insert (delete-and-extract-region beg end))
28293 (goto-char pos)
28294 (move-to-column col)))
28296 (defun org-replace-escapes (string table)
28297 "Replace %-escapes in STRING with values in TABLE.
28298 TABLE is an association list with keys like \"%a\" and string values.
28299 The sequences in STRING may contain normal field width and padding information,
28300 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28301 so values can contain further %-escapes if they are define later in TABLE."
28302 (let ((case-fold-search nil)
28303 e re rpl)
28304 (while (setq e (pop table))
28305 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28306 (while (string-match re string)
28307 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28308 (cdr e)))
28309 (setq string (replace-match rpl t t string))))
28310 string))
28313 (defun org-sublist (list start end)
28314 "Return a section of LIST, from START to END.
28315 Counting starts at 1."
28316 (let (rtn (c start))
28317 (setq list (nthcdr (1- start) list))
28318 (while (and list (<= c end))
28319 (push (pop list) rtn)
28320 (setq c (1+ c)))
28321 (nreverse rtn)))
28323 (defun org-find-base-buffer-visiting (file)
28324 "Like `find-buffer-visiting' but alway return the base buffer and
28325 not an indirect buffer"
28326 (let ((buf (find-buffer-visiting file)))
28327 (if buf
28328 (or (buffer-base-buffer buf) buf)
28329 nil)))
28331 (defun org-image-file-name-regexp ()
28332 "Return regexp matching the file names of images."
28333 (if (fboundp 'image-file-name-regexp)
28334 (image-file-name-regexp)
28335 (let ((image-file-name-extensions
28336 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28337 "xbm" "xpm" "pbm" "pgm" "ppm")))
28338 (concat "\\."
28339 (regexp-opt (nconc (mapcar 'upcase
28340 image-file-name-extensions)
28341 image-file-name-extensions)
28343 "\\'"))))
28345 (defun org-file-image-p (file)
28346 "Return non-nil if FILE is an image."
28347 (save-match-data
28348 (string-match (org-image-file-name-regexp) file)))
28350 ;;; Paragraph filling stuff.
28351 ;; We want this to be just right, so use the full arsenal.
28353 (defun org-indent-line-function ()
28354 "Indent line like previous, but further if previous was headline or item."
28355 (interactive)
28356 (let* ((pos (point))
28357 (itemp (org-at-item-p))
28358 column bpos bcol tpos tcol bullet btype bullet-type)
28359 ;; Find the previous relevant line
28360 (beginning-of-line 1)
28361 (cond
28362 ((looking-at "#") (setq column 0))
28363 ((looking-at "\\*+ ") (setq column 0))
28365 (beginning-of-line 0)
28366 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28367 (beginning-of-line 0))
28368 (cond
28369 ((looking-at "\\*+[ \t]+")
28370 (goto-char (match-end 0))
28371 (setq column (current-column)))
28372 ((org-in-item-p)
28373 (org-beginning-of-item)
28374 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28375 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28376 (setq bpos (match-beginning 1) tpos (match-end 0)
28377 bcol (progn (goto-char bpos) (current-column))
28378 tcol (progn (goto-char tpos) (current-column))
28379 bullet (match-string 1)
28380 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28381 (if (not itemp)
28382 (setq column tcol)
28383 (goto-char pos)
28384 (beginning-of-line 1)
28385 (if (looking-at "\\S-")
28386 (progn
28387 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28388 (setq bullet (match-string 1)
28389 btype (if (string-match "[0-9]" bullet) "n" bullet))
28390 (setq column (if (equal btype bullet-type) bcol tcol)))
28391 (setq column (org-get-indentation)))))
28392 (t (setq column (org-get-indentation))))))
28393 (goto-char pos)
28394 (if (<= (current-column) (current-indentation))
28395 (indent-line-to column)
28396 (save-excursion (indent-line-to column)))
28397 (setq column (current-column))
28398 (beginning-of-line 1)
28399 (if (looking-at
28400 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28401 (replace-match (concat "\\1" (format org-property-format
28402 (match-string 2) (match-string 3)))
28403 t nil))
28404 (move-to-column column)))
28406 (defun org-set-autofill-regexps ()
28407 (interactive)
28408 ;; In the paragraph separator we include headlines, because filling
28409 ;; text in a line directly attached to a headline would otherwise
28410 ;; fill the headline as well.
28411 (org-set-local 'comment-start-skip "^#+[ \t]*")
28412 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28413 ;; The paragraph starter includes hand-formatted lists.
28414 (org-set-local 'paragraph-start
28415 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28416 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28417 ;; But only if the user has not turned off tables or fixed-width regions
28418 (org-set-local
28419 'auto-fill-inhibit-regexp
28420 (concat "\\*+ \\|#\\+"
28421 "\\|[ \t]*" org-keyword-time-regexp
28422 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28423 (concat
28424 "\\|[ \t]*["
28425 (if org-enable-table-editor "|" "")
28426 (if org-enable-fixed-width-editor ":" "")
28427 "]"))))
28428 ;; We use our own fill-paragraph function, to make sure that tables
28429 ;; and fixed-width regions are not wrapped. That function will pass
28430 ;; through to `fill-paragraph' when appropriate.
28431 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28432 ; Adaptive filling: To get full control, first make sure that
28433 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28434 (org-set-local 'adaptive-fill-regexp "\000")
28435 (org-set-local 'adaptive-fill-function
28436 'org-adaptive-fill-function)
28437 (org-set-local
28438 'align-mode-rules-list
28439 '((org-in-buffer-settings
28440 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28441 (modes . '(org-mode))))))
28443 (defun org-fill-paragraph (&optional justify)
28444 "Re-align a table, pass through to fill-paragraph if no table."
28445 (let ((table-p (org-at-table-p))
28446 (table.el-p (org-at-table.el-p)))
28447 (cond ((and (equal (char-after (point-at-bol)) ?*)
28448 (save-excursion (goto-char (point-at-bol))
28449 (looking-at outline-regexp)))
28450 t) ; skip headlines
28451 (table.el-p t) ; skip table.el tables
28452 (table-p (org-table-align) t) ; align org-mode tables
28453 (t nil)))) ; call paragraph-fill
28455 ;; For reference, this is the default value of adaptive-fill-regexp
28456 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28458 (defun org-adaptive-fill-function ()
28459 "Return a fill prefix for org-mode files.
28460 In particular, this makes sure hanging paragraphs for hand-formatted lists
28461 work correctly."
28462 (cond ((looking-at "#[ \t]+")
28463 (match-string 0))
28464 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28465 (save-excursion
28466 (goto-char (match-end 0))
28467 (make-string (current-column) ?\ )))
28468 (t nil)))
28470 ;;;; Functions extending outline functionality
28473 (defun org-beginning-of-line (&optional arg)
28474 "Go to the beginning of the current line. If that is invisible, continue
28475 to a visible line beginning. This makes the function of C-a more intuitive.
28476 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28477 first attempt, and only move to after the tags when the cursor is already
28478 beyond the end of the headline."
28479 (interactive "P")
28480 (let ((pos (point)))
28481 (beginning-of-line 1)
28482 (if (bobp)
28484 (backward-char 1)
28485 (if (org-invisible-p)
28486 (while (and (not (bobp)) (org-invisible-p))
28487 (backward-char 1)
28488 (beginning-of-line 1))
28489 (forward-char 1)))
28490 (when org-special-ctrl-a/e
28491 (cond
28492 ((and (looking-at org-todo-line-regexp)
28493 (= (char-after (match-end 1)) ?\ ))
28494 (goto-char
28495 (if (eq org-special-ctrl-a/e t)
28496 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28497 ((= pos (point)) (match-beginning 3))
28498 (t (point)))
28499 (cond ((> pos (point)) (point))
28500 ((not (eq last-command this-command)) (point))
28501 (t (match-beginning 3))))))
28502 ((org-at-item-p)
28503 (goto-char
28504 (if (eq org-special-ctrl-a/e t)
28505 (cond ((> pos (match-end 4)) (match-end 4))
28506 ((= pos (point)) (match-end 4))
28507 (t (point)))
28508 (cond ((> pos (point)) (point))
28509 ((not (eq last-command this-command)) (point))
28510 (t (match-end 4))))))))))
28512 (defun org-end-of-line (&optional arg)
28513 "Go to the end of the line.
28514 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28515 first attempt, and only move to after the tags when the cursor is already
28516 beyond the end of the headline."
28517 (interactive "P")
28518 (if (or (not org-special-ctrl-a/e)
28519 (not (org-on-heading-p)))
28520 (end-of-line arg)
28521 (let ((pos (point)))
28522 (beginning-of-line 1)
28523 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28524 (if (eq org-special-ctrl-a/e t)
28525 (if (or (< pos (match-beginning 1))
28526 (= pos (match-end 0)))
28527 (goto-char (match-beginning 1))
28528 (goto-char (match-end 0)))
28529 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28530 (goto-char (match-end 0))
28531 (goto-char (match-beginning 1))))
28532 (end-of-line arg)))))
28534 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28535 (define-key org-mode-map "\C-e" 'org-end-of-line)
28537 (defun org-kill-line (&optional arg)
28538 "Kill line, to tags or end of line."
28539 (interactive "P")
28540 (cond
28541 ((or (not org-special-ctrl-k)
28542 (bolp)
28543 (not (org-on-heading-p)))
28544 (call-interactively 'kill-line))
28545 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28546 (kill-region (point) (match-beginning 1))
28547 (org-set-tags nil t))
28548 (t (kill-region (point) (point-at-eol)))))
28550 (define-key org-mode-map "\C-k" 'org-kill-line)
28552 (defun org-invisible-p ()
28553 "Check if point is at a character currently not visible."
28554 ;; Early versions of noutline don't have `outline-invisible-p'.
28555 (if (fboundp 'outline-invisible-p)
28556 (outline-invisible-p)
28557 (get-char-property (point) 'invisible)))
28559 (defun org-invisible-p2 ()
28560 "Check if point is at a character currently not visible."
28561 (save-excursion
28562 (if (and (eolp) (not (bobp))) (backward-char 1))
28563 ;; Early versions of noutline don't have `outline-invisible-p'.
28564 (if (fboundp 'outline-invisible-p)
28565 (outline-invisible-p)
28566 (get-char-property (point) 'invisible))))
28568 (defalias 'org-back-to-heading 'outline-back-to-heading)
28569 (defalias 'org-on-heading-p 'outline-on-heading-p)
28570 (defalias 'org-at-heading-p 'outline-on-heading-p)
28571 (defun org-at-heading-or-item-p ()
28572 (or (org-on-heading-p) (org-at-item-p)))
28574 (defun org-on-target-p ()
28575 (or (org-in-regexp org-radio-target-regexp)
28576 (org-in-regexp org-target-regexp)))
28578 (defun org-up-heading-all (arg)
28579 "Move to the heading line of which the present line is a subheading.
28580 This function considers both visible and invisible heading lines.
28581 With argument, move up ARG levels."
28582 (if (fboundp 'outline-up-heading-all)
28583 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28584 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28586 (defun org-up-heading-safe ()
28587 "Move to the heading line of which the present line is a subheading.
28588 This version will not throw an error. It will return the level of the
28589 headline found, or nil if no higher level is found."
28590 (let ((pos (point)) start-level level
28591 (re (concat "^" outline-regexp)))
28592 (catch 'exit
28593 (outline-back-to-heading t)
28594 (setq start-level (funcall outline-level))
28595 (if (equal start-level 1) (throw 'exit nil))
28596 (while (re-search-backward re nil t)
28597 (setq level (funcall outline-level))
28598 (if (< level start-level) (throw 'exit level)))
28599 nil)))
28601 (defun org-first-sibling-p ()
28602 "Is this heading the first child of its parents?"
28603 (interactive)
28604 (let ((re (concat "^" outline-regexp))
28605 level l)
28606 (unless (org-at-heading-p t)
28607 (error "Not at a heading"))
28608 (setq level (funcall outline-level))
28609 (save-excursion
28610 (if (not (re-search-backward re nil t))
28612 (setq l (funcall outline-level))
28613 (< l level)))))
28615 (defun org-goto-sibling (&optional previous)
28616 "Goto the next sibling, even if it is invisible.
28617 When PREVIOUS is set, go to the previous sibling instead. Returns t
28618 when a sibling was found. When none is found, return nil and don't
28619 move point."
28620 (let ((fun (if previous 're-search-backward 're-search-forward))
28621 (pos (point))
28622 (re (concat "^" outline-regexp))
28623 level l)
28624 (when (condition-case nil (org-back-to-heading t) (error nil))
28625 (setq level (funcall outline-level))
28626 (catch 'exit
28627 (or previous (forward-char 1))
28628 (while (funcall fun re nil t)
28629 (setq l (funcall outline-level))
28630 (when (< l level) (goto-char pos) (throw 'exit nil))
28631 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28632 (goto-char pos)
28633 nil))))
28635 (defun org-show-siblings ()
28636 "Show all siblings of the current headline."
28637 (save-excursion
28638 (while (org-goto-sibling) (org-flag-heading nil)))
28639 (save-excursion
28640 (while (org-goto-sibling 'previous)
28641 (org-flag-heading nil))))
28643 (defun org-show-hidden-entry ()
28644 "Show an entry where even the heading is hidden."
28645 (save-excursion
28646 (org-show-entry)))
28648 (defun org-flag-heading (flag &optional entry)
28649 "Flag the current heading. FLAG non-nil means make invisible.
28650 When ENTRY is non-nil, show the entire entry."
28651 (save-excursion
28652 (org-back-to-heading t)
28653 ;; Check if we should show the entire entry
28654 (if entry
28655 (progn
28656 (org-show-entry)
28657 (save-excursion
28658 (and (outline-next-heading)
28659 (org-flag-heading nil))))
28660 (outline-flag-region (max (point-min) (1- (point)))
28661 (save-excursion (outline-end-of-heading) (point))
28662 flag))))
28664 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28665 ;; This is an exact copy of the original function, but it uses
28666 ;; `org-back-to-heading', to make it work also in invisible
28667 ;; trees. And is uses an invisible-OK argument.
28668 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28669 (org-back-to-heading invisible-OK)
28670 (let ((first t)
28671 (level (funcall outline-level)))
28672 (while (and (not (eobp))
28673 (or first (> (funcall outline-level) level)))
28674 (setq first nil)
28675 (outline-next-heading))
28676 (unless to-heading
28677 (if (memq (preceding-char) '(?\n ?\^M))
28678 (progn
28679 ;; Go to end of line before heading
28680 (forward-char -1)
28681 (if (memq (preceding-char) '(?\n ?\^M))
28682 ;; leave blank line before heading
28683 (forward-char -1))))))
28684 (point))
28686 (defun org-show-subtree ()
28687 "Show everything after this heading at deeper levels."
28688 (outline-flag-region
28689 (point)
28690 (save-excursion
28691 (outline-end-of-subtree) (outline-next-heading) (point))
28692 nil))
28694 (defun org-show-entry ()
28695 "Show the body directly following this heading.
28696 Show the heading too, if it is currently invisible."
28697 (interactive)
28698 (save-excursion
28699 (condition-case nil
28700 (progn
28701 (org-back-to-heading t)
28702 (outline-flag-region
28703 (max (point-min) (1- (point)))
28704 (save-excursion
28705 (re-search-forward
28706 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28707 (or (match-beginning 1) (point-max)))
28708 nil))
28709 (error nil))))
28711 (defun org-make-options-regexp (kwds)
28712 "Make a regular expression for keyword lines."
28713 (concat
28715 "#?[ \t]*\\+\\("
28716 (mapconcat 'regexp-quote kwds "\\|")
28717 "\\):[ \t]*"
28718 "\\(.+\\)"))
28720 ;; Make isearch reveal the necessary context
28721 (defun org-isearch-end ()
28722 "Reveal context after isearch exits."
28723 (when isearch-success ; only if search was successful
28724 (if (featurep 'xemacs)
28725 ;; Under XEmacs, the hook is run in the correct place,
28726 ;; we directly show the context.
28727 (org-show-context 'isearch)
28728 ;; In Emacs the hook runs *before* restoring the overlays.
28729 ;; So we have to use a one-time post-command-hook to do this.
28730 ;; (Emacs 22 has a special variable, see function `org-mode')
28731 (unless (and (boundp 'isearch-mode-end-hook-quit)
28732 isearch-mode-end-hook-quit)
28733 ;; Only when the isearch was not quitted.
28734 (org-add-hook 'post-command-hook 'org-isearch-post-command
28735 'append 'local)))))
28737 (defun org-isearch-post-command ()
28738 "Remove self from hook, and show context."
28739 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28740 (org-show-context 'isearch))
28743 ;;;; Integration with and fixes for other packages
28745 ;;; Imenu support
28747 (defvar org-imenu-markers nil
28748 "All markers currently used by Imenu.")
28749 (make-variable-buffer-local 'org-imenu-markers)
28751 (defun org-imenu-new-marker (&optional pos)
28752 "Return a new marker for use by Imenu, and remember the marker."
28753 (let ((m (make-marker)))
28754 (move-marker m (or pos (point)))
28755 (push m org-imenu-markers)
28758 (defun org-imenu-get-tree ()
28759 "Produce the index for Imenu."
28760 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28761 (setq org-imenu-markers nil)
28762 (let* ((n org-imenu-depth)
28763 (re (concat "^" outline-regexp))
28764 (subs (make-vector (1+ n) nil))
28765 (last-level 0)
28766 m tree level head)
28767 (save-excursion
28768 (save-restriction
28769 (widen)
28770 (goto-char (point-max))
28771 (while (re-search-backward re nil t)
28772 (setq level (org-reduced-level (funcall outline-level)))
28773 (when (<= level n)
28774 (looking-at org-complex-heading-regexp)
28775 (setq head (org-match-string-no-properties 4)
28776 m (org-imenu-new-marker))
28777 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28778 (if (>= level last-level)
28779 (push (cons head m) (aref subs level))
28780 (push (cons head (aref subs (1+ level))) (aref subs level))
28781 (loop for i from (1+ level) to n do (aset subs i nil)))
28782 (setq last-level level)))))
28783 (aref subs 1)))
28785 (eval-after-load "imenu"
28786 '(progn
28787 (add-hook 'imenu-after-jump-hook
28788 (lambda () (org-show-context 'org-goto)))))
28790 ;; Speedbar support
28792 (defun org-speedbar-set-agenda-restriction ()
28793 "Restrict future agenda commands to the location at point in speedbar.
28794 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28795 (interactive)
28796 (let (p m tp np dir txt w)
28797 (cond
28798 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28799 'org-imenu t))
28800 (setq m (get-text-property p 'org-imenu-marker))
28801 (save-excursion
28802 (save-restriction
28803 (set-buffer (marker-buffer m))
28804 (goto-char m)
28805 (org-agenda-set-restriction-lock 'subtree))))
28806 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28807 'speedbar-function 'speedbar-find-file))
28808 (setq tp (previous-single-property-change
28809 (1+ p) 'speedbar-function)
28810 np (next-single-property-change
28811 tp 'speedbar-function)
28812 dir (speedbar-line-directory)
28813 txt (buffer-substring-no-properties (or tp (point-min))
28814 (or np (point-max))))
28815 (save-excursion
28816 (save-restriction
28817 (set-buffer (find-file-noselect
28818 (let ((default-directory dir))
28819 (expand-file-name txt))))
28820 (unless (org-mode-p)
28821 (error "Cannot restrict to non-Org-mode file"))
28822 (org-agenda-set-restriction-lock 'file))))
28823 (t (error "Don't know how to restrict Org-mode's agenda")))
28824 (org-move-overlay org-speedbar-restriction-lock-overlay
28825 (point-at-bol) (point-at-eol))
28826 (setq current-prefix-arg nil)
28827 (org-agenda-maybe-redo)))
28829 (eval-after-load "speedbar"
28830 '(progn
28831 (speedbar-add-supported-extension ".org")
28832 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28833 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28834 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28835 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28836 (add-hook 'speedbar-visiting-tag-hook
28837 (lambda () (org-show-context 'org-goto)))))
28840 ;;; Fixes and Hacks
28842 ;; Make flyspell not check words in links, to not mess up our keymap
28843 (defun org-mode-flyspell-verify ()
28844 "Don't let flyspell put overlays at active buttons."
28845 (not (get-text-property (point) 'keymap)))
28847 ;; Make `bookmark-jump' show the jump location if it was hidden.
28848 (eval-after-load "bookmark"
28849 '(if (boundp 'bookmark-after-jump-hook)
28850 ;; We can use the hook
28851 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28852 ;; Hook not available, use advice
28853 (defadvice bookmark-jump (after org-make-visible activate)
28854 "Make the position visible."
28855 (org-bookmark-jump-unhide))))
28857 (defun org-bookmark-jump-unhide ()
28858 "Unhide the current position, to show the bookmark location."
28859 (and (org-mode-p)
28860 (or (org-invisible-p)
28861 (save-excursion (goto-char (max (point-min) (1- (point))))
28862 (org-invisible-p)))
28863 (org-show-context 'bookmark-jump)))
28865 ;; Make session.el ignore our circular variable
28866 (eval-after-load "session"
28867 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28869 ;;;; Experimental code
28871 (defun org-closed-in-range ()
28872 "Sparse tree of items closed in a certain time range.
28873 Still experimental, may disappear in the future."
28874 (interactive)
28875 ;; Get the time interval from the user.
28876 (let* ((time1 (time-to-seconds
28877 (org-read-date nil 'to-time nil "Starting date: ")))
28878 (time2 (time-to-seconds
28879 (org-read-date nil 'to-time nil "End date:")))
28880 ;; callback function
28881 (callback (lambda ()
28882 (let ((time
28883 (time-to-seconds
28884 (apply 'encode-time
28885 (org-parse-time-string
28886 (match-string 1))))))
28887 ;; check if time in interval
28888 (and (>= time time1) (<= time time2))))))
28889 ;; make tree, check each match with the callback
28890 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28892 ;;;; Finish up
28894 (provide 'org)
28896 (run-hooks 'org-load-hook)
28898 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28899 ;;; org.el ends here