Merge branch 'master' of git+ssh://repo.or.cz/srv/git/org-mode
[org-mode.git] / org.el
blobb1d360b30d22f023b18f3391c71ea9aa094a6d92
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 0)
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 ;; Make sure old customizations of this variable don't lead to problems.
2009 (when (integerp org-time-stamp-rounding-minutes)
2010 (setq org-time-stamp-rounding-minutes
2011 (list org-time-stamp-rounding-minutes
2012 org-time-stamp-rounding-minutes)))
2014 (defcustom org-display-custom-times nil
2015 "Non-nil means, overlay custom formats over all time stamps.
2016 The formats are defined through the variable `org-time-stamp-custom-formats'.
2017 To turn this on on a per-file basis, insert anywhere in the file:
2018 #+STARTUP: customtime"
2019 :group 'org-time
2020 :set 'set-default
2021 :type 'sexp)
2022 (make-variable-buffer-local 'org-display-custom-times)
2024 (defcustom org-time-stamp-custom-formats
2025 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2026 "Custom formats for time stamps. See `format-time-string' for the syntax.
2027 These are overlayed over the default ISO format if the variable
2028 `org-display-custom-times' is set. Time like %H:%M should be at the
2029 end of the second format."
2030 :group 'org-time
2031 :type 'sexp)
2033 (defun org-time-stamp-format (&optional long inactive)
2034 "Get the right format for a time string."
2035 (let ((f (if long (cdr org-time-stamp-formats)
2036 (car org-time-stamp-formats))))
2037 (if inactive
2038 (concat "[" (substring f 1 -1) "]")
2039 f)))
2041 (defcustom org-read-date-prefer-future t
2042 "Non-nil means, assume future for incomplete date input from user.
2043 This affects the following situations:
2044 1. The user gives a day, but no month.
2045 For example, if today is the 15th, and you enter \"3\", Org-mode will
2046 read this as the third of *next* month. However, if you enter \"17\",
2047 it will be considered as *this* month.
2048 2. The user gives a month but not a year.
2049 For example, if it is april and you enter \"feb 2\", this will be read
2050 as feb 2, *next* year. \"May 5\", however, will be this year.
2052 When this option is nil, the current month and year will always be used
2053 as defaults."
2054 :group 'org-time
2055 :type 'boolean)
2057 (defcustom org-read-date-display-live t
2058 "Non-nil means, display current interpretation of date prompt live.
2059 This display will be in an overlay, in the minibuffer."
2060 :group 'org-time
2061 :type 'boolean)
2063 (defcustom org-read-date-popup-calendar t
2064 "Non-nil means, pop up a calendar when prompting for a date.
2065 In the calendar, the date can be selected with mouse-1. However, the
2066 minibuffer will also be active, and you can simply enter the date as well.
2067 When nil, only the minibuffer will be available."
2068 :group 'org-time
2069 :type 'boolean)
2070 (if (fboundp 'defvaralias)
2071 (defvaralias 'org-popup-calendar-for-date-prompt
2072 'org-read-date-popup-calendar))
2074 (defcustom org-extend-today-until 0
2075 "The hour when your day really ends.
2076 This has influence for the following applications:
2077 - When switching the agenda to \"today\". It it is still earlier than
2078 the time given here, the day recognized as TODAY is actually yesterday.
2079 - When a date is read from the user and it is still before the time given
2080 here, the current date and time will be assumed to be yesterday, 23:59.
2082 FIXME:
2083 IMPORTANT: This is still a very experimental feature, it may disappear
2084 again or it may be extended to mean more things."
2085 :group 'org-time
2086 :type 'number)
2088 (defcustom org-edit-timestamp-down-means-later nil
2089 "Non-nil means, S-down will increase the time in a time stamp.
2090 When nil, S-up will increase."
2091 :group 'org-time
2092 :type 'boolean)
2094 (defcustom org-calendar-follow-timestamp-change t
2095 "Non-nil means, make the calendar window follow timestamp changes.
2096 When a timestamp is modified and the calendar window is visible, it will be
2097 moved to the new date."
2098 :group 'org-time
2099 :type 'boolean)
2101 (defcustom org-clock-heading-function nil
2102 "When non-nil, should be a function to create `org-clock-heading'.
2103 This is the string shown in the mode line when a clock is running.
2104 The function is called with point at the beginning of the headline."
2105 :group 'org-time ; FIXME: Should we have a separate group????
2106 :type 'function)
2108 (defgroup org-tags nil
2109 "Options concerning tags in Org-mode."
2110 :tag "Org Tags"
2111 :group 'org)
2113 (defcustom org-tag-alist nil
2114 "List of tags allowed in Org-mode files.
2115 When this list is nil, Org-mode will base TAG input on what is already in the
2116 buffer.
2117 The value of this variable is an alist, the car of each entry must be a
2118 keyword as a string, the cdr may be a character that is used to select
2119 that tag through the fast-tag-selection interface.
2120 See the manual for details."
2121 :group 'org-tags
2122 :type '(repeat
2123 (choice
2124 (cons (string :tag "Tag name")
2125 (character :tag "Access char"))
2126 (const :tag "Start radio group" (:startgroup))
2127 (const :tag "End radio group" (:endgroup)))))
2129 (defcustom org-use-fast-tag-selection 'auto
2130 "Non-nil means, use fast tag selection scheme.
2131 This is a special interface to select and deselect tags with single keys.
2132 When nil, fast selection is never used.
2133 When the symbol `auto', fast selection is used if and only if selection
2134 characters for tags have been configured, either through the variable
2135 `org-tag-alist' or through a #+TAGS line in the buffer.
2136 When t, fast selection is always used and selection keys are assigned
2137 automatically if necessary."
2138 :group 'org-tags
2139 :type '(choice
2140 (const :tag "Always" t)
2141 (const :tag "Never" nil)
2142 (const :tag "When selection characters are configured" 'auto)))
2144 (defcustom org-fast-tag-selection-single-key nil
2145 "Non-nil means, fast tag selection exits after first change.
2146 When nil, you have to press RET to exit it.
2147 During fast tag selection, you can toggle this flag with `C-c'.
2148 This variable can also have the value `expert'. In this case, the window
2149 displaying the tags menu is not even shown, until you press C-c again."
2150 :group 'org-tags
2151 :type '(choice
2152 (const :tag "No" nil)
2153 (const :tag "Yes" t)
2154 (const :tag "Expert" expert)))
2156 (defvar org-fast-tag-selection-include-todo nil
2157 "Non-nil means, fast tags selection interface will also offer TODO states.
2158 This is an undocumented feature, you should not rely on it.")
2160 (defcustom org-tags-column -80
2161 "The column to which tags should be indented in a headline.
2162 If this number is positive, it specifies the column. If it is negative,
2163 it means that the tags should be flushright to that column. For example,
2164 -80 works well for a normal 80 character screen."
2165 :group 'org-tags
2166 :type 'integer)
2168 (defcustom org-auto-align-tags t
2169 "Non-nil means, realign tags after pro/demotion of TODO state change.
2170 These operations change the length of a headline and therefore shift
2171 the tags around. With this options turned on, after each such operation
2172 the tags are again aligned to `org-tags-column'."
2173 :group 'org-tags
2174 :type 'boolean)
2176 (defcustom org-use-tag-inheritance t
2177 "Non-nil means, tags in levels apply also for sublevels.
2178 When nil, only the tags directly given in a specific line apply there.
2179 If you turn off this option, you very likely want to turn on the
2180 companion option `org-tags-match-list-sublevels'."
2181 :group 'org-tags
2182 :type 'boolean)
2184 (defcustom org-tags-match-list-sublevels nil
2185 "Non-nil means list also sublevels of headlines matching tag search.
2186 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2187 the sublevels of a headline matching a tag search often also match
2188 the same search. Listing all of them can create very long lists.
2189 Setting this variable to nil causes subtrees of a match to be skipped.
2190 This option is off by default, because inheritance in on. If you turn
2191 inheritance off, you very likely want to turn this option on.
2193 As a special case, if the tag search is restricted to TODO items, the
2194 value of this variable is ignored and sublevels are always checked, to
2195 make sure all corresponding TODO items find their way into the list."
2196 :group 'org-tags
2197 :type 'boolean)
2199 (defvar org-tags-history nil
2200 "History of minibuffer reads for tags.")
2201 (defvar org-last-tags-completion-table nil
2202 "The last used completion table for tags.")
2203 (defvar org-after-tags-change-hook nil
2204 "Hook that is run after the tags in a line have changed.")
2206 (defgroup org-properties nil
2207 "Options concerning properties in Org-mode."
2208 :tag "Org Properties"
2209 :group 'org)
2211 (defcustom org-property-format "%-10s %s"
2212 "How property key/value pairs should be formatted by `indent-line'.
2213 When `indent-line' hits a property definition, it will format the line
2214 according to this format, mainly to make sure that the values are
2215 lined-up with respect to each other."
2216 :group 'org-properties
2217 :type 'string)
2219 (defcustom org-use-property-inheritance nil
2220 "Non-nil means, properties apply also for sublevels.
2221 This setting is only relevant during property searches, not when querying
2222 an entry with `org-entry-get'. To retrieve a property with inheritance,
2223 you need to call `org-entry-get' with the inheritance flag.
2224 Turning this on can cause significant overhead when doing a search, so
2225 this is turned off by default.
2226 When nil, only the properties directly given in the current entry count.
2227 The value may also be a list of properties that shouldhave inheritance.
2229 However, note that some special properties use inheritance under special
2230 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2231 and the properties ending in \"_ALL\" when they are used as descriptor
2232 for valid values of a property."
2233 :group 'org-properties
2234 :type '(choice
2235 (const :tag "Not" nil)
2236 (const :tag "Always" nil)
2237 (repeat :tag "Specific properties" (string :tag "Property"))))
2239 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2240 "The default column format, if no other format has been defined.
2241 This variable can be set on the per-file basis by inserting a line
2243 #+COLUMNS: %25ITEM ....."
2244 :group 'org-properties
2245 :type 'string)
2247 (defcustom org-global-properties nil
2248 "List of property/value pairs that can be inherited by any entry.
2249 You can set buffer-local values for this by adding lines like
2251 #+PROPERTY: NAME VALUE"
2252 :group 'org-properties
2253 :type '(repeat
2254 (cons (string :tag "Property")
2255 (string :tag "Value"))))
2257 (defvar org-local-properties nil
2258 "List of property/value pairs that can be inherited by any entry.
2259 Valid for the current buffer.
2260 This variable is populated from #+PROPERTY lines.")
2262 (defgroup org-agenda nil
2263 "Options concerning agenda views in Org-mode."
2264 :tag "Org Agenda"
2265 :group 'org)
2267 (defvar org-category nil
2268 "Variable used by org files to set a category for agenda display.
2269 Such files should use a file variable to set it, for example
2271 # -*- mode: org; org-category: \"ELisp\"
2273 or contain a special line
2275 #+CATEGORY: ELisp
2277 If the file does not specify a category, then file's base name
2278 is used instead.")
2279 (make-variable-buffer-local 'org-category)
2281 (defcustom org-agenda-files nil
2282 "The files to be used for agenda display.
2283 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2284 \\[org-remove-file]. You can also use customize to edit the list.
2286 If an entry is a directory, all files in that directory that are matched by
2287 `org-agenda-file-regexp' will be part of the file list.
2289 If the value of the variable is not a list but a single file name, then
2290 the list of agenda files is actually stored and maintained in that file, one
2291 agenda file per line."
2292 :group 'org-agenda
2293 :type '(choice
2294 (repeat :tag "List of files and directories" file)
2295 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2297 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2298 "Regular expression to match files for `org-agenda-files'.
2299 If any element in the list in that variable contains a directory instead
2300 of a normal file, all files in that directory that are matched by this
2301 regular expression will be included."
2302 :group 'org-agenda
2303 :type 'regexp)
2305 (defcustom org-agenda-skip-unavailable-files nil
2306 "t means to just skip non-reachable files in `org-agenda-files'.
2307 Nil means to remove them, after a query, from the list."
2308 :group 'org-agenda
2309 :type 'boolean)
2311 (defcustom org-agenda-text-search-extra-files nil
2312 "List of extra files to be searched by text search commands.
2313 These files will be search in addition to the agenda files bu the
2314 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2315 Note that these files will only be searched for text search commands,
2316 not for the other agenda views like todo lists, tag earches or the weekly
2317 agenda. This variable is intended to list notes and possibly archive files
2318 that should also be searched by these two commands."
2319 :group 'org-agenda
2320 :type '(repeat file))
2322 (if (fboundp 'defvaralias)
2323 (defvaralias 'org-agenda-multi-occur-extra-files
2324 'org-agenda-text-search-extra-files))
2326 (defcustom org-agenda-confirm-kill 1
2327 "When set, remote killing from the agenda buffer needs confirmation.
2328 When t, a confirmation is always needed. When a number N, confirmation is
2329 only needed when the text to be killed contains more than N non-white lines."
2330 :group 'org-agenda
2331 :type '(choice
2332 (const :tag "Never" nil)
2333 (const :tag "Always" t)
2334 (number :tag "When more than N lines")))
2336 (defcustom org-calendar-to-agenda-key [?c]
2337 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2338 The command `org-calendar-goto-agenda' will be bound to this key. The
2339 default is the character `c' because then `c' can be used to switch back and
2340 forth between agenda and calendar."
2341 :group 'org-agenda
2342 :type 'sexp)
2344 (defcustom org-agenda-compact-blocks nil
2345 "Non-nil means, make the block agenda more compact.
2346 This is done by leaving out unnecessary lines."
2347 :group 'org-agenda
2348 :type nil)
2350 (defgroup org-agenda-export nil
2351 "Options concerning exporting agenda views in Org-mode."
2352 :tag "Org Agenda Export"
2353 :group 'org-agenda)
2355 (defcustom org-agenda-with-colors t
2356 "Non-nil means, use colors in agenda views."
2357 :group 'org-agenda-export
2358 :type 'boolean)
2360 (defcustom org-agenda-exporter-settings nil
2361 "Alist of variable/value pairs that should be active during agenda export.
2362 This is a good place to set uptions for ps-print and for htmlize."
2363 :group 'org-agenda-export
2364 :type '(repeat
2365 (list
2366 (variable)
2367 (sexp :tag "Value"))))
2369 (defcustom org-agenda-export-html-style ""
2370 "The style specification for exported HTML Agenda files.
2371 If this variable contains a string, it will replace the default <style>
2372 section as produced by `htmlize'.
2373 Since there are different ways of setting style information, this variable
2374 needs to contain the full HTML structure to provide a style, including the
2375 surrounding HTML tags. The style specifications should include definitions
2376 the fonts used by the agenda, here is an example:
2378 <style type=\"text/css\">
2379 p { font-weight: normal; color: gray; }
2380 .org-agenda-structure {
2381 font-size: 110%;
2382 color: #003399;
2383 font-weight: 600;
2385 .org-todo {
2386 color: #cc6666;
2387 font-weight: bold;
2389 .org-done {
2390 color: #339933;
2392 .title { text-align: center; }
2393 .todo, .deadline { color: red; }
2394 .done { color: green; }
2395 </style>
2397 or, if you want to keep the style in a file,
2399 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2401 As the value of this option simply gets inserted into the HTML <head> header,
2402 you can \"misuse\" it to also add other text to the header. However,
2403 <style>...</style> is required, if not present the variable will be ignored."
2404 :group 'org-agenda-export
2405 :group 'org-export-html
2406 :type 'string)
2408 (defgroup org-agenda-custom-commands nil
2409 "Options concerning agenda views in Org-mode."
2410 :tag "Org Agenda Custom Commands"
2411 :group 'org-agenda)
2413 (defconst org-sorting-choice
2414 '(choice
2415 (const time-up) (const time-down)
2416 (const category-keep) (const category-up) (const category-down)
2417 (const tag-down) (const tag-up)
2418 (const priority-up) (const priority-down))
2419 "Sorting choices.")
2421 (defconst org-agenda-custom-commands-local-options
2422 `(repeat :tag "Local settings for this command. Remember to quote values"
2423 (choice :tag "Setting"
2424 (list :tag "Any variable"
2425 (variable :tag "Variable")
2426 (sexp :tag "Value"))
2427 (list :tag "Files to be searched"
2428 (const org-agenda-files)
2429 (list
2430 (const :format "" quote)
2431 (repeat
2432 (file))))
2433 (list :tag "Sorting strategy"
2434 (const org-agenda-sorting-strategy)
2435 (list
2436 (const :format "" quote)
2437 (repeat
2438 ,org-sorting-choice)))
2439 (list :tag "Prefix format"
2440 (const org-agenda-prefix-format :value " %-12:c%?-12t% s")
2441 (string))
2442 (list :tag "Number of days in agenda"
2443 (const org-agenda-ndays)
2444 (integer :value 1))
2445 (list :tag "Fixed starting date"
2446 (const org-agenda-start-day)
2447 (string :value "2007-11-01"))
2448 (list :tag "Start on day of week"
2449 (const org-agenda-start-on-weekday)
2450 (choice :value 1
2451 (const :tag "Today" nil)
2452 (number :tag "Weekday No.")))
2453 (list :tag "Include data from diary"
2454 (const org-agenda-include-diary)
2455 (boolean))
2456 (list :tag "Deadline Warning days"
2457 (const org-deadline-warning-days)
2458 (integer :value 1))
2459 (list :tag "Standard skipping condition"
2460 :value (org-agenda-skip-function '(org-agenda-skip-entry-if))
2461 (const org-agenda-skip-function)
2462 (list
2463 (const :format "" quote)
2464 (list
2465 (choice
2466 :tag "Skiping range"
2467 (const :tag "Skip entry" org-agenda-skip-entry-if)
2468 (const :tag "Skip subtree" org-agenda-skip-subtree-if))
2469 (repeat :inline t :tag "Conditions for skipping"
2470 (choice
2471 :tag "Condition type"
2472 (list :tag "Regexp matches" :inline t (const :format "" 'regexp) (regexp))
2473 (list :tag "Regexp does not match" :inline t (const :format "" 'notregexp) (regexp))
2474 (const :tag "scheduled" 'scheduled)
2475 (const :tag "not scheduled" 'notscheduled)
2476 (const :tag "deadline" 'deadline)
2477 (const :tag "no deadline" 'notdeadline))))))
2478 (list :tag "Non-standard skipping condition"
2479 :value (org-agenda-skip-function)
2480 (list
2481 (const org-agenda-skip-function)
2482 (sexp :tag "Function or form (quoted!)")))))
2483 "Selection of examples for agenda command settings.
2484 This will be spliced into the custom type of
2485 `org-agenda-custom-commands'.")
2488 (defcustom org-agenda-custom-commands nil
2489 "Custom commands for the agenda.
2490 These commands will be offered on the splash screen displayed by the
2491 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
2493 (key desc type match settings files)
2495 key The key (one or more characters as a string) to be associated
2496 with the command.
2497 desc A description of the command, when omitted or nil, a default
2498 description is built using MATCH.
2499 type The command type, any of the following symbols:
2500 agenda The daily/weekly agenda.
2501 todo Entries with a specific TODO keyword, in all agenda files.
2502 search Entries containing search words entry or headline.
2503 tags Tags/Property/TODO match in all agenda files.
2504 tags-todo Tags/P/T match in all agenda files, TODO entries only.
2505 todo-tree Sparse tree of specific TODO keyword in *current* file.
2506 tags-tree Sparse tree with all tags matches in *current* file.
2507 occur-tree Occur sparse tree for *current* file.
2508 ... A user-defined function.
2509 match What to search for:
2510 - a single keyword for TODO keyword searches
2511 - a tags match expression for tags searches
2512 - a word search expression for text searches.
2513 - a regular expression for occur searches
2514 For all other commands, this should be the empty string.
2515 settings A list of option settings, similar to that in a let form, so like
2516 this: ((opt1 val1) (opt2 val2) ...). The values will be
2517 evaluated at the moment of execution, so quote them when needed.
2518 files A list of files file to write the produced agenda buffer to
2519 with the command `org-store-agenda-views'.
2520 If a file name ends in \".html\", an HTML version of the buffer
2521 is written out. If it ends in \".ps\", a postscript version is
2522 produced. Otherwide, only the plain text is written to the file.
2524 You can also define a set of commands, to create a composite agenda buffer.
2525 In this case, an entry looks like this:
2527 (key desc (cmd1 cmd2 ...) general-settings-for-whole-set files)
2529 where
2531 desc A description string to be displayed in the dispatcher menu.
2532 cmd An agenda command, similar to the above. However, tree commands
2533 are no allowed, but instead you can get agenda and global todo list.
2534 So valid commands for a set are:
2535 (agenda \"\" settings)
2536 (alltodo \"\" settings)
2537 (stuck \"\" settings)
2538 (todo \"match\" settings files)
2539 (search \"match\" settings files)
2540 (tags \"match\" settings files)
2541 (tags-todo \"match\" settings files)
2543 Each command can carry a list of options, and another set of options can be
2544 given for the whole set of commands. Individual command options take
2545 precedence over the general options.
2547 When using several characters as key to a command, the first characters
2548 are prefix commands. For the dispatcher to display useful information, you
2549 should provide a description for the prefix, like
2551 (setq org-agenda-custom-commands
2552 '((\"h\" . \"HOME + Name tag searches\") ; describe prefix \"h\"
2553 (\"hl\" tags \"+HOME+Lisa\")
2554 (\"hp\" tags \"+HOME+Peter\")
2555 (\"hk\" tags \"+HOME+Kim\")))"
2556 :group 'org-agenda-custom-commands
2557 :type `(repeat
2558 (choice :value ("x" "Describe command here" tags "" nil)
2559 (list :tag "Single command"
2560 (string :tag "Access Key(s) ")
2561 (option (string :tag "Description"))
2562 (choice
2563 (const :tag "Agenda" agenda)
2564 (const :tag "TODO list" alltodo)
2565 (const :tag "Search words" search)
2566 (const :tag "Stuck projects" stuck)
2567 (const :tag "Tags search (all agenda files)" tags)
2568 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
2569 (const :tag "TODO keyword search (all agenda files)" todo)
2570 (const :tag "Tags sparse tree (current buffer)" tags-tree)
2571 (const :tag "TODO keyword tree (current buffer)" todo-tree)
2572 (const :tag "Occur tree (current buffer)" occur-tree)
2573 (sexp :tag "Other, user-defined function"))
2574 (string :tag "Match (only for some commands)")
2575 ,org-agenda-custom-commands-local-options
2576 (option (repeat :tag "Export" (file :tag "Export to"))))
2577 (list :tag "Command series, all agenda files"
2578 (string :tag "Access Key(s)")
2579 (string :tag "Description ")
2580 (repeat :tag "Component"
2581 (choice
2582 (list :tag "Agenda"
2583 (const :format "" agenda)
2584 (const :tag "" :format "" "")
2585 ,org-agenda-custom-commands-local-options)
2586 (list :tag "TODO list (all keywords)"
2587 (const :format "" alltodo)
2588 (const :tag "" :format "" "")
2589 ,org-agenda-custom-commands-local-options)
2590 (list :tag "Search words"
2591 (const :format "" search)
2592 (string :tag "Match")
2593 ,org-agenda-custom-commands-local-options)
2594 (list :tag "Stuck projects"
2595 (const :format "" stuck)
2596 (const :tag "" :format "" "")
2597 ,org-agenda-custom-commands-local-options)
2598 (list :tag "Tags search"
2599 (const :format "" tags)
2600 (string :tag "Match")
2601 ,org-agenda-custom-commands-local-options)
2602 (list :tag "Tags search, TODO entries only"
2603 (const :format "" tags-todo)
2604 (string :tag "Match")
2605 ,org-agenda-custom-commands-local-options)
2606 (list :tag "TODO keyword search"
2607 (const :format "" todo)
2608 (string :tag "Match")
2609 ,org-agenda-custom-commands-local-options)
2610 (list :tag "Other, user-defined function"
2611 (symbol :tag "function")
2612 (string :tag "Match")
2613 ,org-agenda-custom-commands-local-options)))
2615 (repeat :tag "Settings for entire command set"
2616 (list (variable :tag "Any variable")
2617 (sexp :tag "Value")))
2618 (option (repeat :tag "Export" (file :tag "Export to"))))
2619 (cons :tag "Prefix key documentation"
2620 (string :tag "Access Key(s)")
2621 (string :tag "Description ")))))
2623 (defcustom org-agenda-query-register ?o
2624 "The register holding the current query string.
2625 The prupose of this is that if you construct a query string interactively,
2626 you can then use it to define a custom command."
2627 :group 'org-agenda-custom-commands
2628 :type 'character)
2630 (defcustom org-stuck-projects
2631 '("+LEVEL=2/-DONE" ("TODO" "NEXT" "NEXTACTION") nil "")
2632 "How to identify stuck projects.
2633 This is a list of four items:
2634 1. A tags/todo matcher string that is used to identify a project.
2635 The entire tree below a headline matched by this is considered one project.
2636 2. A list of TODO keywords identifying non-stuck projects.
2637 If the project subtree contains any headline with one of these todo
2638 keywords, the project is considered to be not stuck. If you specify
2639 \"*\" as a keyword, any TODO keyword will mark the project unstuck.
2640 3. A list of tags identifying non-stuck projects.
2641 If the project subtree contains any headline with one of these tags,
2642 the project is considered to be not stuck. If you specify \"*\" as
2643 a tag, any tag will mark the project unstuck.
2644 4. An arbitrary regular expression matching non-stuck projects.
2646 After defining this variable, you may use \\[org-agenda-list-stuck-projects]
2647 or `C-c a #' to produce the list."
2648 :group 'org-agenda-custom-commands
2649 :type '(list
2650 (string :tag "Tags/TODO match to identify a project")
2651 (repeat :tag "Projects are *not* stuck if they have an entry with TODO keyword any of" (string))
2652 (repeat :tag "Projects are *not* stuck if they have an entry with TAG being any of" (string))
2653 (regexp :tag "Projects are *not* stuck if this regexp matches\ninside the subtree")))
2656 (defgroup org-agenda-skip nil
2657 "Options concerning skipping parts of agenda files."
2658 :tag "Org Agenda Skip"
2659 :group 'org-agenda)
2661 (defcustom org-agenda-todo-list-sublevels t
2662 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
2663 When nil, the sublevels of a TODO entry are not checked, resulting in
2664 potentially much shorter TODO lists."
2665 :group 'org-agenda-skip
2666 :group 'org-todo
2667 :type 'boolean)
2669 (defcustom org-agenda-todo-ignore-with-date nil
2670 "Non-nil means, don't show entries with a date in the global todo list.
2671 You can use this if you prefer to mark mere appointments with a TODO keyword,
2672 but don't want them to show up in the TODO list.
2673 When this is set, it also covers deadlines and scheduled items, the settings
2674 of `org-agenda-todo-ignore-scheduled' and `org-agenda-todo-ignore-deadlines'
2675 will be ignored."
2676 :group 'org-agenda-skip
2677 :group 'org-todo
2678 :type 'boolean)
2680 (defcustom org-agenda-todo-ignore-scheduled nil
2681 "Non-nil means, don't show scheduled entries in the global todo list.
2682 The idea behind this is that by scheduling it, you have already taken care
2683 of this item.
2684 See also `org-agenda-todo-ignore-with-date'."
2685 :group 'org-agenda-skip
2686 :group 'org-todo
2687 :type 'boolean)
2689 (defcustom org-agenda-todo-ignore-deadlines nil
2690 "Non-nil means, don't show near deadline entries in the global todo list.
2691 Near means closer than `org-deadline-warning-days' days.
2692 The idea behind this is that such items will appear in the agenda anyway.
2693 See also `org-agenda-todo-ignore-with-date'."
2694 :group 'org-agenda-skip
2695 :group 'org-todo
2696 :type 'boolean)
2698 (defcustom org-agenda-skip-scheduled-if-done nil
2699 "Non-nil means don't show scheduled items in agenda when they are done.
2700 This is relevant for the daily/weekly agenda, not for the TODO list. And
2701 it applies only to the actual date of the scheduling. Warnings about
2702 an item with a past scheduling dates are always turned off when the item
2703 is DONE."
2704 :group 'org-agenda-skip
2705 :type 'boolean)
2707 (defcustom org-agenda-skip-deadline-if-done nil
2708 "Non-nil means don't show deadines when the corresponding item is done.
2709 When nil, the deadline is still shown and should give you a happy feeling.
2710 This is relevant for the daily/weekly agenda. And it applied only to the
2711 actualy date of the deadline. Warnings about approching and past-due
2712 deadlines are always turned off when the item is DONE."
2713 :group 'org-agenda-skip
2714 :type 'boolean)
2716 (defcustom org-agenda-skip-timestamp-if-done nil
2717 "Non-nil means don't select item by timestamp or -range if it is DONE."
2718 :group 'org-agenda-skip
2719 :type 'boolean)
2721 (defcustom org-timeline-show-empty-dates 3
2722 "Non-nil means, `org-timeline' also shows dates without an entry.
2723 When nil, only the days which actually have entries are shown.
2724 When t, all days between the first and the last date are shown.
2725 When an integer, show also empty dates, but if there is a gap of more than
2726 N days, just insert a special line indicating the size of the gap."
2727 :group 'org-agenda-skip
2728 :type '(choice
2729 (const :tag "None" nil)
2730 (const :tag "All" t)
2731 (number :tag "at most")))
2734 (defgroup org-agenda-startup nil
2735 "Options concerning initial settings in the Agenda in Org Mode."
2736 :tag "Org Agenda Startup"
2737 :group 'org-agenda)
2739 (defcustom org-finalize-agenda-hook nil
2740 "Hook run just before displaying an agenda buffer."
2741 :group 'org-agenda-startup
2742 :type 'hook)
2744 (defcustom org-agenda-mouse-1-follows-link nil
2745 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
2746 A longer mouse click will still set point. Does not work on XEmacs.
2747 Needs to be set before org.el is loaded."
2748 :group 'org-agenda-startup
2749 :type 'boolean)
2751 (defcustom org-agenda-start-with-follow-mode nil
2752 "The initial value of follow-mode in a newly created agenda window."
2753 :group 'org-agenda-startup
2754 :type 'boolean)
2756 (defgroup org-agenda-windows nil
2757 "Options concerning the windows used by the Agenda in Org Mode."
2758 :tag "Org Agenda Windows"
2759 :group 'org-agenda)
2761 (defcustom org-agenda-window-setup 'reorganize-frame
2762 "How the agenda buffer should be displayed.
2763 Possible values for this option are:
2765 current-window Show agenda in the current window, keeping all other windows.
2766 other-frame Use `switch-to-buffer-other-frame' to display agenda.
2767 other-window Use `switch-to-buffer-other-window' to display agenda.
2768 reorganize-frame Show only two windows on the current frame, the current
2769 window and the agenda.
2770 See also the variable `org-agenda-restore-windows-after-quit'."
2771 :group 'org-agenda-windows
2772 :type '(choice
2773 (const current-window)
2774 (const other-frame)
2775 (const other-window)
2776 (const reorganize-frame)))
2778 (defcustom org-agenda-window-frame-fractions '(0.5 . 0.75)
2779 "The min and max height of the agenda window as a fraction of frame height.
2780 The value of the variable is a cons cell with two numbers between 0 and 1.
2781 It only matters if `org-agenda-window-setup' is `reorganize-frame'."
2782 :group 'org-agenda-windows
2783 :type '(cons (number :tag "Minimum") (number :tag "Maximum")))
2785 (defcustom org-agenda-restore-windows-after-quit nil
2786 "Non-nil means, restore window configuration open exiting agenda.
2787 Before the window configuration is changed for displaying the agenda,
2788 the current status is recorded. When the agenda is exited with
2789 `q' or `x' and this option is set, the old state is restored. If
2790 `org-agenda-window-setup' is `other-frame', the value of this
2791 option will be ignored.."
2792 :group 'org-agenda-windows
2793 :type 'boolean)
2795 (defcustom org-indirect-buffer-display 'other-window
2796 "How should indirect tree buffers be displayed?
2797 This applies to indirect buffers created with the commands
2798 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
2799 Valid values are:
2800 current-window Display in the current window
2801 other-window Just display in another window.
2802 dedicated-frame Create one new frame, and re-use it each time.
2803 new-frame Make a new frame each time. Note that in this case
2804 previously-made indirect buffers are kept, and you need to
2805 kill these buffers yourself."
2806 :group 'org-structure
2807 :group 'org-agenda-windows
2808 :type '(choice
2809 (const :tag "In current window" current-window)
2810 (const :tag "In current frame, other window" other-window)
2811 (const :tag "Each time a new frame" new-frame)
2812 (const :tag "One dedicated frame" dedicated-frame)))
2814 (defgroup org-agenda-daily/weekly nil
2815 "Options concerning the daily/weekly agenda."
2816 :tag "Org Agenda Daily/Weekly"
2817 :group 'org-agenda)
2819 (defcustom org-agenda-ndays 7
2820 "Number of days to include in overview display.
2821 Should be 1 or 7."
2822 :group 'org-agenda-daily/weekly
2823 :type 'number)
2825 (defcustom org-agenda-start-on-weekday 1
2826 "Non-nil means, start the overview always on the specified weekday.
2827 0 denotes Sunday, 1 denotes Monday etc.
2828 When nil, always start on the current day."
2829 :group 'org-agenda-daily/weekly
2830 :type '(choice (const :tag "Today" nil)
2831 (number :tag "Weekday No.")))
2833 (defcustom org-agenda-show-all-dates t
2834 "Non-nil means, `org-agenda' shows every day in the selected range.
2835 When nil, only the days which actually have entries are shown."
2836 :group 'org-agenda-daily/weekly
2837 :type 'boolean)
2839 (defcustom org-agenda-format-date 'org-agenda-format-date-aligned
2840 "Format string for displaying dates in the agenda.
2841 Used by the daily/weekly agenda and by the timeline. This should be
2842 a format string understood by `format-time-string', or a function returning
2843 the formatted date as a string. The function must take a single argument,
2844 a calendar-style date list like (month day year)."
2845 :group 'org-agenda-daily/weekly
2846 :type '(choice
2847 (string :tag "Format string")
2848 (function :tag "Function")))
2850 (defun org-agenda-format-date-aligned (date)
2851 "Format a date string for display in the daily/weekly agenda, or timeline.
2852 This function makes sure that dates are aligned for easy reading."
2853 (format "%-9s %2d %s %4d"
2854 (calendar-day-name date)
2855 (extract-calendar-day date)
2856 (calendar-month-name (extract-calendar-month date))
2857 (extract-calendar-year date)))
2859 (defcustom org-agenda-include-diary nil
2860 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
2861 :group 'org-agenda-daily/weekly
2862 :type 'boolean)
2864 (defcustom org-agenda-include-all-todo nil
2865 "Set means weekly/daily agenda will always contain all TODO entries.
2866 The TODO entries will be listed at the top of the agenda, before
2867 the entries for specific days."
2868 :group 'org-agenda-daily/weekly
2869 :type 'boolean)
2871 (defcustom org-agenda-repeating-timestamp-show-all t
2872 "Non-nil means, show all occurences of a repeating stamp in the agenda.
2873 When nil, only one occurence is shown, either today or the
2874 nearest into the future."
2875 :group 'org-agenda-daily/weekly
2876 :type 'boolean)
2878 (defcustom org-deadline-warning-days 14
2879 "No. of days before expiration during which a deadline becomes active.
2880 This variable governs the display in sparse trees and in the agenda.
2881 When 0 or negative, it means use this number (the absolute value of it)
2882 even if a deadline has a different individual lead time specified."
2883 :group 'org-time
2884 :group 'org-agenda-daily/weekly
2885 :type 'number)
2887 (defcustom org-scheduled-past-days 10000
2888 "No. of days to continue listing scheduled items that are not marked DONE.
2889 When an item is scheduled on a date, it shows up in the agenda on this
2890 day and will be listed until it is marked done for the number of days
2891 given here."
2892 :group 'org-agenda-daily/weekly
2893 :type 'number)
2895 (defgroup org-agenda-time-grid nil
2896 "Options concerning the time grid in the Org-mode Agenda."
2897 :tag "Org Agenda Time Grid"
2898 :group 'org-agenda)
2900 (defcustom org-agenda-use-time-grid t
2901 "Non-nil means, show a time grid in the agenda schedule.
2902 A time grid is a set of lines for specific times (like every two hours between
2903 8:00 and 20:00). The items scheduled for a day at specific times are
2904 sorted in between these lines.
2905 For details about when the grid will be shown, and what it will look like, see
2906 the variable `org-agenda-time-grid'."
2907 :group 'org-agenda-time-grid
2908 :type 'boolean)
2910 (defcustom org-agenda-time-grid
2911 '((daily today require-timed)
2912 "----------------"
2913 (800 1000 1200 1400 1600 1800 2000))
2915 "The settings for time grid for agenda display.
2916 This is a list of three items. The first item is again a list. It contains
2917 symbols specifying conditions when the grid should be displayed:
2919 daily if the agenda shows a single day
2920 weekly if the agenda shows an entire week
2921 today show grid on current date, independent of daily/weekly display
2922 require-timed show grid only if at least one item has a time specification
2924 The second item is a string which will be places behing the grid time.
2926 The third item is a list of integers, indicating the times that should have
2927 a grid line."
2928 :group 'org-agenda-time-grid
2929 :type
2930 '(list
2931 (set :greedy t :tag "Grid Display Options"
2932 (const :tag "Show grid in single day agenda display" daily)
2933 (const :tag "Show grid in weekly agenda display" weekly)
2934 (const :tag "Always show grid for today" today)
2935 (const :tag "Show grid only if any timed entries are present"
2936 require-timed)
2937 (const :tag "Skip grid times already present in an entry"
2938 remove-match))
2939 (string :tag "Grid String")
2940 (repeat :tag "Grid Times" (integer :tag "Time"))))
2942 (defgroup org-agenda-sorting nil
2943 "Options concerning sorting in the Org-mode Agenda."
2944 :tag "Org Agenda Sorting"
2945 :group 'org-agenda)
2947 (defcustom org-agenda-sorting-strategy
2948 '((agenda time-up category-keep priority-down)
2949 (todo category-keep priority-down)
2950 (tags category-keep priority-down)
2951 (search category-keep))
2952 "Sorting structure for the agenda items of a single day.
2953 This is a list of symbols which will be used in sequence to determine
2954 if an entry should be listed before another entry. The following
2955 symbols are recognized:
2957 time-up Put entries with time-of-day indications first, early first
2958 time-down Put entries with time-of-day indications first, late first
2959 category-keep Keep the default order of categories, corresponding to the
2960 sequence in `org-agenda-files'.
2961 category-up Sort alphabetically by category, A-Z.
2962 category-down Sort alphabetically by category, Z-A.
2963 tag-up Sort alphabetically by last tag, A-Z.
2964 tag-down Sort alphabetically by last tag, Z-A.
2965 priority-up Sort numerically by priority, high priority last.
2966 priority-down Sort numerically by priority, high priority first.
2968 The different possibilities will be tried in sequence, and testing stops
2969 if one comparison returns a \"not-equal\". For example, the default
2970 '(time-up category-keep priority-down)
2971 means: Pull out all entries having a specified time of day and sort them,
2972 in order to make a time schedule for the current day the first thing in the
2973 agenda listing for the day. Of the entries without a time indication, keep
2974 the grouped in categories, don't sort the categories, but keep them in
2975 the sequence given in `org-agenda-files'. Within each category sort by
2976 priority.
2978 Leaving out `category-keep' would mean that items will be sorted across
2979 categories by priority.
2981 Instead of a single list, this can also be a set of list for specific
2982 contents, with a context symbol in the car of the list, any of
2983 `agenda', `todo', `tags' for the corresponding agenda views."
2984 :group 'org-agenda-sorting
2985 :type `(choice
2986 (repeat :tag "General" ,org-sorting-choice)
2987 (list :tag "Individually"
2988 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
2989 (repeat ,org-sorting-choice))
2990 (cons (const :tag "Strategy for TODO lists" todo)
2991 (repeat ,org-sorting-choice))
2992 (cons (const :tag "Strategy for Tags matches" tags)
2993 (repeat ,org-sorting-choice)))))
2995 (defcustom org-sort-agenda-notime-is-late t
2996 "Non-nil means, items without time are considered late.
2997 This is only relevant for sorting. When t, items which have no explicit
2998 time like 15:30 will be considered as 99:01, i.e. later than any items which
2999 do have a time. When nil, the default time is before 0:00. You can use this
3000 option to decide if the schedule for today should come before or after timeless
3001 agenda entries."
3002 :group 'org-agenda-sorting
3003 :type 'boolean)
3005 (defgroup org-agenda-line-format nil
3006 "Options concerning the entry prefix in the Org-mode agenda display."
3007 :tag "Org Agenda Line Format"
3008 :group 'org-agenda)
3010 (defcustom org-agenda-prefix-format
3011 '((agenda . " %-12:c%?-12t% s")
3012 (timeline . " % s")
3013 (todo . " %-12:c")
3014 (tags . " %-12:c")
3015 (search . " %-12:c"))
3016 "Format specifications for the prefix of items in the agenda views.
3017 An alist with four entries, for the different agenda types. The keys to the
3018 sublists are `agenda', `timeline', `todo', and `tags'. The values
3019 are format strings.
3020 This format works similar to a printf format, with the following meaning:
3022 %c the category of the item, \"Diary\" for entries from the diary, or
3023 as given by the CATEGORY keyword or derived from the file name.
3024 %T the *last* tag of the item. Last because inherited tags come
3025 first in the list.
3026 %t the time-of-day specification if one applies to the entry, in the
3027 format HH:MM
3028 %s Scheduling/Deadline information, a short string
3030 All specifiers work basically like the standard `%s' of printf, but may
3031 contain two additional characters: A question mark just after the `%' and
3032 a whitespace/punctuation character just before the final letter.
3034 If the first character after `%' is a question mark, the entire field
3035 will only be included if the corresponding value applies to the
3036 current entry. This is useful for fields which should have fixed
3037 width when present, but zero width when absent. For example,
3038 \"%?-12t\" will result in a 12 character time field if a time of the
3039 day is specified, but will completely disappear in entries which do
3040 not contain a time.
3042 If there is punctuation or whitespace character just before the final
3043 format letter, this character will be appended to the field value if
3044 the value is not empty. For example, the format \"%-12:c\" leads to
3045 \"Diary: \" if the category is \"Diary\". If the category were be
3046 empty, no additional colon would be interted.
3048 The default value of this option is \" %-12:c%?-12t% s\", meaning:
3049 - Indent the line with two space characters
3050 - Give the category in a 12 chars wide field, padded with whitespace on
3051 the right (because of `-'). Append a colon if there is a category
3052 (because of `:').
3053 - If there is a time-of-day, put it into a 12 chars wide field. If no
3054 time, don't put in an empty field, just skip it (because of '?').
3055 - Finally, put the scheduling information and append a whitespace.
3057 As another example, if you don't want the time-of-day of entries in
3058 the prefix, you could use:
3060 (setq org-agenda-prefix-format \" %-11:c% s\")
3062 See also the variables `org-agenda-remove-times-when-in-prefix' and
3063 `org-agenda-remove-tags'."
3064 :type '(choice
3065 (string :tag "General format")
3066 (list :greedy t :tag "View dependent"
3067 (cons (const agenda) (string :tag "Format"))
3068 (cons (const timeline) (string :tag "Format"))
3069 (cons (const todo) (string :tag "Format"))
3070 (cons (const tags) (string :tag "Format"))
3071 (cons (const search) (string :tag "Format"))))
3072 :group 'org-agenda-line-format)
3074 (defvar org-prefix-format-compiled nil
3075 "The compiled version of the most recently used prefix format.
3076 See the variable `org-agenda-prefix-format'.")
3078 (defcustom org-agenda-todo-keyword-format "%-1s"
3079 "Format for the TODO keyword in agenda lines.
3080 Set this to something like \"%-12s\" if you want all TODO keywords
3081 to occupy a fixed space in the agenda display."
3082 :group 'org-agenda-line-format
3083 :type 'string)
3085 (defcustom org-agenda-scheduled-leaders '("Scheduled: " "Sched.%2dx: ")
3086 "Text preceeding scheduled items in the agenda view.
3087 This is a list with two strings. The first applies when the item is
3088 scheduled on the current day. The second applies when it has been scheduled
3089 previously, it may contain a %d to capture how many days ago the item was
3090 scheduled."
3091 :group 'org-agenda-line-format
3092 :type '(list
3093 (string :tag "Scheduled today ")
3094 (string :tag "Scheduled previously")))
3096 (defcustom org-agenda-deadline-leaders '("Deadline: " "In %3d d.: ")
3097 "Text preceeding deadline items in the agenda view.
3098 This is a list with two strings. The first applies when the item has its
3099 deadline on the current day. The second applies when it is in the past or
3100 in the future, it may contain %d to capture how many days away the deadline
3101 is (was)."
3102 :group 'org-agenda-line-format
3103 :type '(list
3104 (string :tag "Deadline today ")
3105 (string :tag "Deadline relative")))
3107 (defcustom org-agenda-remove-times-when-in-prefix t
3108 "Non-nil means, remove duplicate time specifications in agenda items.
3109 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
3110 time-of-day specification in a headline or diary entry is extracted and
3111 placed into the prefix. If this option is non-nil, the original specification
3112 \(a timestamp or -range, or just a plain time(range) specification like
3113 11:30-4pm) will be removed for agenda display. This makes the agenda less
3114 cluttered.
3115 The option can be t or nil. It may also be the symbol `beg', indicating
3116 that the time should only be removed what it is located at the beginning of
3117 the headline/diary entry."
3118 :group 'org-agenda-line-format
3119 :type '(choice
3120 (const :tag "Always" t)
3121 (const :tag "Never" nil)
3122 (const :tag "When at beginning of entry" beg)))
3125 (defcustom org-agenda-default-appointment-duration nil
3126 "Default duration for appointments that only have a starting time.
3127 When nil, no duration is specified in such cases.
3128 When non-nil, this must be the number of minutes, e.g. 60 for one hour."
3129 :group 'org-agenda-line-format
3130 :type '(choice
3131 (integer :tag "Minutes")
3132 (const :tag "No default duration")))
3135 (defcustom org-agenda-remove-tags nil
3136 "Non-nil means, remove the tags from the headline copy in the agenda.
3137 When this is the symbol `prefix', only remove tags when
3138 `org-agenda-prefix-format' contains a `%T' specifier."
3139 :group 'org-agenda-line-format
3140 :type '(choice
3141 (const :tag "Always" t)
3142 (const :tag "Never" nil)
3143 (const :tag "When prefix format contains %T" prefix)))
3145 (if (fboundp 'defvaralias)
3146 (defvaralias 'org-agenda-remove-tags-when-in-prefix
3147 'org-agenda-remove-tags))
3149 (defcustom org-agenda-tags-column -80
3150 "Shift tags in agenda items to this column.
3151 If this number is positive, it specifies the column. If it is negative,
3152 it means that the tags should be flushright to that column. For example,
3153 -80 works well for a normal 80 character screen."
3154 :group 'org-agenda-line-format
3155 :type 'integer)
3157 (if (fboundp 'defvaralias)
3158 (defvaralias 'org-agenda-align-tags-to-column 'org-agenda-tags-column))
3160 (defcustom org-agenda-fontify-priorities t
3161 "Non-nil means, highlight low and high priorities in agenda.
3162 When t, the highest priority entries are bold, lowest priority italic.
3163 This may also be an association list of priority faces. The face may be
3164 a names face, or a list like `(:background \"Red\")'."
3165 :group 'org-agenda-line-format
3166 :type '(choice
3167 (const :tag "Never" nil)
3168 (const :tag "Defaults" t)
3169 (repeat :tag "Specify"
3170 (list (character :tag "Priority" :value ?A)
3171 (sexp :tag "face")))))
3173 (defgroup org-latex nil
3174 "Options for embedding LaTeX code into Org-mode"
3175 :tag "Org LaTeX"
3176 :group 'org)
3178 (defcustom org-format-latex-options
3179 '(:foreground default :background default :scale 1.0
3180 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
3181 :matchers ("begin" "$" "$$" "\\(" "\\["))
3182 "Options for creating images from LaTeX fragments.
3183 This is a property list with the following properties:
3184 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
3185 `default' means use the forground of the default face.
3186 :background the background color, or \"Transparent\".
3187 `default' means use the background of the default face.
3188 :scale a scaling factor for the size of the images
3189 :html-foreground, :html-background, :html-scale
3190 The same numbers for HTML export.
3191 :matchers a list indicating which matchers should be used to
3192 find LaTeX fragments. Valid members of this list are:
3193 \"begin\" find environments
3194 \"$\" find math expressions surrounded by $...$
3195 \"$$\" find math expressions surrounded by $$....$$
3196 \"\\(\" find math expressions surrounded by \\(...\\)
3197 \"\\ [\" find math expressions surrounded by \\ [...\\]"
3198 :group 'org-latex
3199 :type 'plist)
3201 (defcustom org-format-latex-header "\\documentclass{article}
3202 \\usepackage{fullpage} % do not remove
3203 \\usepackage{amssymb}
3204 \\usepackage[usenames]{color}
3205 \\usepackage{amsmath}
3206 \\usepackage{latexsym}
3207 \\usepackage[mathscr]{eucal}
3208 \\pagestyle{empty} % do not remove"
3209 "The document header used for processing LaTeX fragments."
3210 :group 'org-latex
3211 :type 'string)
3213 (defgroup org-export nil
3214 "Options for exporting org-listings."
3215 :tag "Org Export"
3216 :group 'org)
3218 (defgroup org-export-general nil
3219 "General options for exporting Org-mode files."
3220 :tag "Org Export General"
3221 :group 'org-export)
3223 ;; FIXME
3224 (defvar org-export-publishing-directory nil)
3226 (defcustom org-export-with-special-strings t
3227 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3228 When this option is turned on, these strings will be exported as:
3230 Org HTML LaTeX
3231 -----+----------+--------
3232 \\- &shy; \\-
3233 -- &ndash; --
3234 --- &mdash; ---
3235 ... &hellip; \ldots
3237 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3238 :group 'org-export-translation
3239 :type 'boolean)
3241 (defcustom org-export-language-setup
3242 '(("en" "Author" "Date" "Table of Contents")
3243 ("cs" "Autor" "Datum" "Obsah")
3244 ("da" "Ophavsmand" "Dato" "Indhold")
3245 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
3246 ("es" "Autor" "Fecha" "\xcdndice")
3247 ("fr" "Auteur" "Date" "Table des mati\xe8res")
3248 ("it" "Autore" "Data" "Indice")
3249 ("nl" "Auteur" "Datum" "Inhoudsopgave")
3250 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
3251 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
3252 "Terms used in export text, translated to different languages.
3253 Use the variable `org-export-default-language' to set the language,
3254 or use the +OPTION lines for a per-file setting."
3255 :group 'org-export-general
3256 :type '(repeat
3257 (list
3258 (string :tag "HTML language tag")
3259 (string :tag "Author")
3260 (string :tag "Date")
3261 (string :tag "Table of Contents"))))
3263 (defcustom org-export-default-language "en"
3264 "The default language of HTML export, as a string.
3265 This should have an association in `org-export-language-setup'."
3266 :group 'org-export-general
3267 :type 'string)
3269 (defcustom org-export-skip-text-before-1st-heading t
3270 "Non-nil means, skip all text before the first headline when exporting.
3271 When nil, that text is exported as well."
3272 :group 'org-export-general
3273 :type 'boolean)
3275 (defcustom org-export-headline-levels 3
3276 "The last level which is still exported as a headline.
3277 Inferior levels will produce itemize lists when exported.
3278 Note that a numeric prefix argument to an exporter function overrides
3279 this setting.
3281 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
3282 :group 'org-export-general
3283 :type 'number)
3285 (defcustom org-export-with-section-numbers t
3286 "Non-nil means, add section numbers to headlines when exporting.
3288 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
3289 :group 'org-export-general
3290 :type 'boolean)
3292 (defcustom org-export-with-toc t
3293 "Non-nil means, create a table of contents in exported files.
3294 The TOC contains headlines with levels up to`org-export-headline-levels'.
3295 When an integer, include levels up to N in the toc, this may then be
3296 different from `org-export-headline-levels', but it will not be allowed
3297 to be larger than the number of headline levels.
3298 When nil, no table of contents is made.
3300 Headlines which contain any TODO items will be marked with \"(*)\" in
3301 ASCII export, and with red color in HTML output, if the option
3302 `org-export-mark-todo-in-toc' is set.
3304 In HTML output, the TOC will be clickable.
3306 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"
3307 or \"toc:3\"."
3308 :group 'org-export-general
3309 :type '(choice
3310 (const :tag "No Table of Contents" nil)
3311 (const :tag "Full Table of Contents" t)
3312 (integer :tag "TOC to level")))
3314 (defcustom org-export-mark-todo-in-toc nil
3315 "Non-nil means, mark TOC lines that contain any open TODO items."
3316 :group 'org-export-general
3317 :type 'boolean)
3319 (defcustom org-export-preserve-breaks nil
3320 "Non-nil means, preserve all line breaks when exporting.
3321 Normally, in HTML output paragraphs will be reformatted. In ASCII
3322 export, line breaks will always be preserved, regardless of this variable.
3324 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
3325 :group 'org-export-general
3326 :type 'boolean)
3328 (defcustom org-export-with-archived-trees 'headline
3329 "Whether subtrees with the ARCHIVE tag should be exported.
3330 This can have three different values
3331 nil Do not export, pretend this tree is not present
3332 t Do export the entire tree
3333 headline Only export the headline, but skip the tree below it."
3334 :group 'org-export-general
3335 :group 'org-archive
3336 :type '(choice
3337 (const :tag "not at all" nil)
3338 (const :tag "headline only" 'headline)
3339 (const :tag "entirely" t)))
3341 (defcustom org-export-author-info t
3342 "Non-nil means, insert author name and email into the exported file.
3344 This option can also be set with the +OPTIONS line,
3345 e.g. \"author-info:nil\"."
3346 :group 'org-export-general
3347 :type 'boolean)
3349 (defcustom org-export-time-stamp-file t
3350 "Non-nil means, insert a time stamp into the exported file.
3351 The time stamp shows when the file was created.
3353 This option can also be set with the +OPTIONS line,
3354 e.g. \"timestamp:nil\"."
3355 :group 'org-export-general
3356 :type 'boolean)
3358 (defcustom org-export-with-timestamps t
3359 "If nil, do not export time stamps and associated keywords."
3360 :group 'org-export-general
3361 :type 'boolean)
3363 (defcustom org-export-remove-timestamps-from-toc t
3364 "If nil, remove timestamps from the table of contents entries."
3365 :group 'org-export-general
3366 :type 'boolean)
3368 (defcustom org-export-with-tags 'not-in-toc
3369 "If nil, do not export tags, just remove them from headlines.
3370 If this is the symbol `not-in-toc', tags will be removed from table of
3371 contents entries, but still be shown in the headlines of the document.
3373 This option can also be set with the +OPTIONS line, e.g. \"tags:nil\"."
3374 :group 'org-export-general
3375 :type '(choice
3376 (const :tag "Off" nil)
3377 (const :tag "Not in TOC" not-in-toc)
3378 (const :tag "On" t)))
3380 (defcustom org-export-with-drawers nil
3381 "Non-nil means, export with drawers like the property drawer.
3382 When t, all drawers are exported. This may also be a list of
3383 drawer names to export."
3384 :group 'org-export-general
3385 :type '(choice
3386 (const :tag "All drawers" t)
3387 (const :tag "None" nil)
3388 (repeat :tag "Selected drawers"
3389 (string :tag "Drawer name"))))
3391 (defgroup org-export-translation nil
3392 "Options for translating special ascii sequences for the export backends."
3393 :tag "Org Export Translation"
3394 :group 'org-export)
3396 (defcustom org-export-with-emphasize t
3397 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
3398 If the export target supports emphasizing text, the word will be
3399 typeset in bold, italic, or underlined, respectively. Works only for
3400 single words, but you can say: I *really* *mean* *this*.
3401 Not all export backends support this.
3403 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
3404 :group 'org-export-translation
3405 :type 'boolean)
3407 (defcustom org-export-with-footnotes t
3408 "If nil, export [1] as a footnote marker.
3409 Lines starting with [1] will be formatted as footnotes.
3411 This option can also be set with the +OPTIONS line, e.g. \"f:nil\"."
3412 :group 'org-export-translation
3413 :type 'boolean)
3415 (defcustom org-export-with-sub-superscripts t
3416 "Non-nil means, interpret \"_\" and \"^\" for export.
3417 When this option is turned on, you can use TeX-like syntax for sub- and
3418 superscripts. Several characters after \"_\" or \"^\" will be
3419 considered as a single item - so grouping with {} is normally not
3420 needed. For example, the following things will be parsed as single
3421 sub- or superscripts.
3423 10^24 or 10^tau several digits will be considered 1 item.
3424 10^-12 or 10^-tau a leading sign with digits or a word
3425 x^2-y^3 will be read as x^2 - y^3, because items are
3426 terminated by almost any nonword/nondigit char.
3427 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
3429 Still, ambiguity is possible - so when in doubt use {} to enclose the
3430 sub/superscript. If you set this variable to the symbol `{}',
3431 the braces are *required* in order to trigger interpretations as
3432 sub/superscript. This can be helpful in documents that need \"_\"
3433 frequently in plain text.
3435 Not all export backends support this, but HTML does.
3437 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
3438 :group 'org-export-translation
3439 :type '(choice
3440 (const :tag "Always interpret" t)
3441 (const :tag "Only with braces" {})
3442 (const :tag "Never interpret" nil)))
3444 (defcustom org-export-with-special-strings t
3445 "Non-nil means, interpret \"\-\", \"--\" and \"---\" for export.
3446 When this option is turned on, these strings will be exported as:
3448 \\- : &shy;
3449 -- : &ndash;
3450 --- : &mdash;
3452 Not all export backends support this, but HTML does.
3454 This option can also be set with the +OPTIONS line, e.g. \"-:nil\"."
3455 :group 'org-export-translation
3456 :type 'boolean)
3458 (defcustom org-export-with-TeX-macros t
3459 "Non-nil means, interpret simple TeX-like macros when exporting.
3460 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
3461 No only real TeX macros will work here, but the standard HTML entities
3462 for math can be used as macro names as well. For a list of supported
3463 names in HTML export, see the constant `org-html-entities'.
3464 Not all export backends support this.
3466 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
3467 :group 'org-export-translation
3468 :group 'org-export-latex
3469 :type 'boolean)
3471 (defcustom org-export-with-LaTeX-fragments nil
3472 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
3473 When set, the exporter will find LaTeX environments if the \\begin line is
3474 the first non-white thing on a line. It will also find the math delimiters
3475 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
3476 display math.
3478 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
3479 :group 'org-export-translation
3480 :group 'org-export-latex
3481 :type 'boolean)
3483 (defcustom org-export-with-fixed-width t
3484 "Non-nil means, lines starting with \":\" will be in fixed width font.
3485 This can be used to have pre-formatted text, fragments of code etc. For
3486 example:
3487 : ;; Some Lisp examples
3488 : (while (defc cnt)
3489 : (ding))
3490 will be looking just like this in also HTML. See also the QUOTE keyword.
3491 Not all export backends support this.
3493 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
3494 :group 'org-export-translation
3495 :type 'boolean)
3497 (defcustom org-match-sexp-depth 3
3498 "Number of stacked braces for sub/superscript matching.
3499 This has to be set before loading org.el to be effective."
3500 :group 'org-export-translation
3501 :type 'integer)
3503 (defgroup org-export-tables nil
3504 "Options for exporting tables in Org-mode."
3505 :tag "Org Export Tables"
3506 :group 'org-export)
3508 (defcustom org-export-with-tables t
3509 "If non-nil, lines starting with \"|\" define a table.
3510 For example:
3512 | Name | Address | Birthday |
3513 |-------------+----------+-----------|
3514 | Arthur Dent | England | 29.2.2100 |
3516 Not all export backends support this.
3518 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
3519 :group 'org-export-tables
3520 :type 'boolean)
3522 (defcustom org-export-highlight-first-table-line t
3523 "Non-nil means, highlight the first table line.
3524 In HTML export, this means use <th> instead of <td>.
3525 In tables created with table.el, this applies to the first table line.
3526 In Org-mode tables, all lines before the first horizontal separator
3527 line will be formatted with <th> tags."
3528 :group 'org-export-tables
3529 :type 'boolean)
3531 (defcustom org-export-table-remove-special-lines t
3532 "Remove special lines and marking characters in calculating tables.
3533 This removes the special marking character column from tables that are set
3534 up for spreadsheet calculations. It also removes the entire lines
3535 marked with `!', `_', or `^'. The lines with `$' are kept, because
3536 the values of constants may be useful to have."
3537 :group 'org-export-tables
3538 :type 'boolean)
3540 (defcustom org-export-prefer-native-exporter-for-tables nil
3541 "Non-nil means, always export tables created with table.el natively.
3542 Natively means, use the HTML code generator in table.el.
3543 When nil, Org-mode's own HTML generator is used when possible (i.e. if
3544 the table does not use row- or column-spanning). This has the
3545 advantage, that the automatic HTML conversions for math symbols and
3546 sub/superscripts can be applied. Org-mode's HTML generator is also
3547 much faster."
3548 :group 'org-export-tables
3549 :type 'boolean)
3551 (defgroup org-export-ascii nil
3552 "Options specific for ASCII export of Org-mode files."
3553 :tag "Org Export ASCII"
3554 :group 'org-export)
3556 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
3557 "Characters for underlining headings in ASCII export.
3558 In the given sequence, these characters will be used for level 1, 2, ..."
3559 :group 'org-export-ascii
3560 :type '(repeat character))
3562 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
3563 "Bullet characters for headlines converted to lists in ASCII export.
3564 The first character is used for the first lest level generated in this
3565 way, and so on. If there are more levels than characters given here,
3566 the list will be repeated.
3567 Note that plain lists will keep the same bullets as the have in the
3568 Org-mode file."
3569 :group 'org-export-ascii
3570 :type '(repeat character))
3572 (defgroup org-export-xml nil
3573 "Options specific for XML export of Org-mode files."
3574 :tag "Org Export XML"
3575 :group 'org-export)
3577 (defgroup org-export-html nil
3578 "Options specific for HTML export of Org-mode files."
3579 :tag "Org Export HTML"
3580 :group 'org-export)
3582 (defcustom org-export-html-coding-system nil
3584 :group 'org-export-html
3585 :type 'coding-system)
3587 (defcustom org-export-html-extension "html"
3588 "The extension for exported HTML files."
3589 :group 'org-export-html
3590 :type 'string)
3592 (defcustom org-export-html-style
3593 "<style type=\"text/css\">
3594 html {
3595 font-family: Times, serif;
3596 font-size: 12pt;
3598 .title { text-align: center; }
3599 .todo { color: red; }
3600 .done { color: green; }
3601 .timestamp { color: grey }
3602 .timestamp-kwd { color: CadetBlue }
3603 .tag { background-color:lightblue; font-weight:normal }
3604 .target { background-color: lavender; }
3605 pre {
3606 border: 1pt solid #AEBDCC;
3607 background-color: #F3F5F7;
3608 padding: 5pt;
3609 font-family: courier, monospace;
3611 table { border-collapse: collapse; }
3612 td, th {
3613 vertical-align: top;
3614 <!--border: 1pt solid #ADB9CC;-->
3616 </style>"
3617 "The default style specification for exported HTML files.
3618 Since there are different ways of setting style information, this variable
3619 needs to contain the full HTML structure to provide a style, including the
3620 surrounding HTML tags. The style specifications should include definitions
3621 for new classes todo, done, title, and deadline. For example, valid values
3622 would be:
3624 <style type=\"text/css\">
3625 p { font-weight: normal; color: gray; }
3626 h1 { color: black; }
3627 .title { text-align: center; }
3628 .todo, .deadline { color: red; }
3629 .done { color: green; }
3630 </style>
3632 or, if you want to keep the style in a file,
3634 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
3636 As the value of this option simply gets inserted into the HTML <head> header,
3637 you can \"misuse\" it to add arbitrary text to the header."
3638 :group 'org-export-html
3639 :type 'string)
3642 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
3643 "Format for typesetting the document title in HTML export."
3644 :group 'org-export-html
3645 :type 'string)
3647 (defcustom org-export-html-toplevel-hlevel 2
3648 "The <H> level for level 1 headings in HTML export."
3649 :group 'org-export-html
3650 :type 'string)
3652 (defcustom org-export-html-link-org-files-as-html t
3653 "Non-nil means, make file links to `file.org' point to `file.html'.
3654 When org-mode is exporting an org-mode file to HTML, links to
3655 non-html files are directly put into a href tag in HTML.
3656 However, links to other Org-mode files (recognized by the
3657 extension `.org.) should become links to the corresponding html
3658 file, assuming that the linked org-mode file will also be
3659 converted to HTML.
3660 When nil, the links still point to the plain `.org' file."
3661 :group 'org-export-html
3662 :type 'boolean)
3664 (defcustom org-export-html-inline-images 'maybe
3665 "Non-nil means, inline images into exported HTML pages.
3666 This is done using an <img> tag. When nil, an anchor with href is used to
3667 link to the image. If this option is `maybe', then images in links with
3668 an empty description will be inlined, while images with a description will
3669 be linked only."
3670 :group 'org-export-html
3671 :type '(choice (const :tag "Never" nil)
3672 (const :tag "Always" t)
3673 (const :tag "When there is no description" maybe)))
3675 ;; FIXME: rename
3676 (defcustom org-export-html-expand t
3677 "Non-nil means, for HTML export, treat @<...> as HTML tag.
3678 When nil, these tags will be exported as plain text and therefore
3679 not be interpreted by a browser.
3681 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
3682 :group 'org-export-html
3683 :type 'boolean)
3685 (defcustom org-export-html-table-tag
3686 "<table border=\"2\" cellspacing=\"0\" cellpadding=\"6\" rules=\"groups\" frame=\"hsides\">"
3687 "The HTML tag that is used to start a table.
3688 This must be a <table> tag, but you may change the options like
3689 borders and spacing."
3690 :group 'org-export-html
3691 :type 'string)
3693 (defcustom org-export-table-header-tags '("<th>" . "</th>")
3694 "The opening tag for table header 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-table-data-tags '("<td>" . "</td>")
3700 "The opening tag for table data fields.
3701 This is customizable so that alignment options can be specified."
3702 :group 'org-export-tables
3703 :type '(cons (string :tag "Opening tag") (string :tag "Closing tag")))
3705 (defcustom org-export-html-with-timestamp nil
3706 "If non-nil, write `org-export-html-html-helper-timestamp'
3707 into the exported HTML text. Otherwise, the buffer will just be saved
3708 to a file."
3709 :group 'org-export-html
3710 :type 'boolean)
3712 (defcustom org-export-html-html-helper-timestamp
3713 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
3714 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
3715 :group 'org-export-html
3716 :type 'string)
3718 (defgroup org-export-icalendar nil
3719 "Options specific for iCalendar export of Org-mode files."
3720 :tag "Org Export iCalendar"
3721 :group 'org-export)
3723 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
3724 "The file name for the iCalendar file covering all agenda files.
3725 This file is created with the command \\[org-export-icalendar-all-agenda-files].
3726 The file name should be absolute, the file will be overwritten without warning."
3727 :group 'org-export-icalendar
3728 :type 'file)
3730 (defcustom org-icalendar-include-todo nil
3731 "Non-nil means, export to iCalendar files should also cover TODO items."
3732 :group 'org-export-icalendar
3733 :type '(choice
3734 (const :tag "None" nil)
3735 (const :tag "Unfinished" t)
3736 (const :tag "All" all)))
3738 (defcustom org-icalendar-include-sexps t
3739 "Non-nil means, export to iCalendar files should also cover sexp entries.
3740 These are entries like in the diary, but directly in an Org-mode file."
3741 :group 'org-export-icalendar
3742 :type 'boolean)
3744 (defcustom org-icalendar-include-body 100
3745 "Amount of text below headline to be included in iCalendar export.
3746 This is a number of characters that should maximally be included.
3747 Properties, scheduling and clocking lines will always be removed.
3748 The text will be inserted into the DESCRIPTION field."
3749 :group 'org-export-icalendar
3750 :type '(choice
3751 (const :tag "Nothing" nil)
3752 (const :tag "Everything" t)
3753 (integer :tag "Max characters")))
3755 (defcustom org-icalendar-combined-name "OrgMode"
3756 "Calendar name for the combined iCalendar representing all agenda files."
3757 :group 'org-export-icalendar
3758 :type 'string)
3760 (defgroup org-font-lock nil
3761 "Font-lock settings for highlighting in Org-mode."
3762 :tag "Org Font Lock"
3763 :group 'org)
3765 (defcustom org-level-color-stars-only nil
3766 "Non-nil means fontify only the stars in each headline.
3767 When nil, the entire headline is fontified.
3768 Changing it requires restart of `font-lock-mode' to become effective
3769 also in regions already fontified."
3770 :group 'org-font-lock
3771 :type 'boolean)
3773 (defcustom org-hide-leading-stars nil
3774 "Non-nil means, hide the first N-1 stars in a headline.
3775 This works by using the face `org-hide' for these stars. This
3776 face is white for a light background, and black for a dark
3777 background. You may have to customize the face `org-hide' to
3778 make this work.
3779 Changing it requires restart of `font-lock-mode' to become effective
3780 also in regions already fontified.
3781 You may also set this on a per-file basis by adding one of the following
3782 lines to the buffer:
3784 #+STARTUP: hidestars
3785 #+STARTUP: showstars"
3786 :group 'org-font-lock
3787 :type 'boolean)
3789 (defcustom org-fontify-done-headline nil
3790 "Non-nil means, change the face of a headline if it is marked DONE.
3791 Normally, only the TODO/DONE keyword indicates the state of a headline.
3792 When this is non-nil, the headline after the keyword is set to the
3793 `org-headline-done' as an additional indication."
3794 :group 'org-font-lock
3795 :type 'boolean)
3797 (defcustom org-fontify-emphasized-text t
3798 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3799 Changing this variable requires a restart of Emacs to take effect."
3800 :group 'org-font-lock
3801 :type 'boolean)
3803 (defcustom org-highlight-latex-fragments-and-specials nil
3804 "Non-nil means, fontify what is treated specially by the exporters."
3805 :group 'org-font-lock
3806 :type 'boolean)
3808 (defcustom org-hide-emphasis-markers nil
3809 "Non-nil mean font-lock should hide the emphasis marker characters."
3810 :group 'org-font-lock
3811 :type 'boolean)
3813 (defvar org-emph-re nil
3814 "Regular expression for matching emphasis.")
3815 (defvar org-verbatim-re nil
3816 "Regular expression for matching verbatim text.")
3817 (defvar org-emphasis-regexp-components) ; defined just below
3818 (defvar org-emphasis-alist) ; defined just below
3819 (defun org-set-emph-re (var val)
3820 "Set variable and compute the emphasis regular expression."
3821 (set var val)
3822 (when (and (boundp 'org-emphasis-alist)
3823 (boundp 'org-emphasis-regexp-components)
3824 org-emphasis-alist org-emphasis-regexp-components)
3825 (let* ((e org-emphasis-regexp-components)
3826 (pre (car e))
3827 (post (nth 1 e))
3828 (border (nth 2 e))
3829 (body (nth 3 e))
3830 (nl (nth 4 e))
3831 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
3832 (body1 (concat body "*?"))
3833 (markers (mapconcat 'car org-emphasis-alist ""))
3834 (vmarkers (mapconcat
3835 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3836 org-emphasis-alist "")))
3837 ;; make sure special characters appear at the right position in the class
3838 (if (string-match "\\^" markers)
3839 (setq markers (concat (replace-match "" t t markers) "^")))
3840 (if (string-match "-" markers)
3841 (setq markers (concat (replace-match "" t t markers) "-")))
3842 (if (string-match "\\^" vmarkers)
3843 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3844 (if (string-match "-" vmarkers)
3845 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3846 (if (> nl 0)
3847 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3848 (int-to-string nl) "\\}")))
3849 ;; Make the regexp
3850 (setq org-emph-re
3851 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
3852 "\\("
3853 "\\([" markers "]\\)"
3854 "\\("
3855 "[^" border "]\\|"
3856 "[^" border (if (and nil stacked) markers) "]"
3857 body1
3858 "[^" border (if (and nil stacked) markers) "]"
3859 "\\)"
3860 "\\3\\)"
3861 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
3862 (setq org-verbatim-re
3863 (concat "\\([" pre "]\\|^\\)"
3864 "\\("
3865 "\\([" vmarkers "]\\)"
3866 "\\("
3867 "[^" border "]\\|"
3868 "[^" border "]"
3869 body1
3870 "[^" border "]"
3871 "\\)"
3872 "\\3\\)"
3873 "\\([" post "]\\|$\\)")))))
3875 (defcustom org-emphasis-regexp-components
3876 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
3877 "Components used to build the regular expression for emphasis.
3878 This is a list with 6 entries. Terminology: In an emphasis string
3879 like \" *strong word* \", we call the initial space PREMATCH, the final
3880 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3881 and \"trong wor\" is the body. The different components in this variable
3882 specify what is allowed/forbidden in each part:
3884 pre Chars allowed as prematch. Beginning of line will be allowed too.
3885 post Chars allowed as postmatch. End of line will be allowed too.
3886 border The chars *forbidden* as border characters.
3887 body-regexp A regexp like \".\" to match a body character. Don't use
3888 non-shy groups here, and don't allow newline here.
3889 newline The maximum number of newlines allowed in an emphasis exp.
3891 Use customize to modify this, or restart Emacs after changing it."
3892 :group 'org-font-lock
3893 :set 'org-set-emph-re
3894 :type '(list
3895 (sexp :tag "Allowed chars in pre ")
3896 (sexp :tag "Allowed chars in post ")
3897 (sexp :tag "Forbidden chars in border ")
3898 (sexp :tag "Regexp for body ")
3899 (integer :tag "number of newlines allowed")
3900 (option (boolean :tag "Stacking (DISABLED) "))))
3902 (defcustom org-emphasis-alist
3903 '(("*" bold "<b>" "</b>")
3904 ("/" italic "<i>" "</i>")
3905 ("_" underline "<u>" "</u>")
3906 ("=" org-code "<code>" "</code>" verbatim)
3907 ("~" org-verbatim "" "" verbatim)
3908 ("+" (:strike-through t) "<del>" "</del>")
3910 "Special syntax for emphasized text.
3911 Text starting and ending with a special character will be emphasized, for
3912 example *bold*, _underlined_ and /italic/. This variable sets the marker
3913 characters, the face to be used by font-lock for highlighting in Org-mode
3914 Emacs buffers, and the HTML tags to be used for this.
3915 Use customize to modify this, or restart Emacs after changing it."
3916 :group 'org-font-lock
3917 :set 'org-set-emph-re
3918 :type '(repeat
3919 (list
3920 (string :tag "Marker character")
3921 (choice
3922 (face :tag "Font-lock-face")
3923 (plist :tag "Face property list"))
3924 (string :tag "HTML start tag")
3925 (string :tag "HTML end tag")
3926 (option (const verbatim)))))
3928 ;;; The faces
3930 (defgroup org-faces nil
3931 "Faces in Org-mode."
3932 :tag "Org Faces"
3933 :group 'org-font-lock)
3935 (defun org-compatible-face (inherits specs)
3936 "Make a compatible face specification.
3937 If INHERITS is an existing face and if the Emacs version supports it,
3938 just inherit the face. If not, use SPECS to define the face.
3939 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
3940 For them we convert a (min-colors 8) entry to a `tty' entry and move it
3941 to the top of the list. The `min-colors' attribute will be removed from
3942 any other entries, and any resulting duplicates will be removed entirely."
3943 (cond
3944 ((and inherits (facep inherits)
3945 (not (featurep 'xemacs)) (> emacs-major-version 22))
3946 ;; In Emacs 23, we use inheritance where possible.
3947 ;; We only do this in Emacs 23, because only there the outline
3948 ;; faces have been changed to the original org-mode-level-faces.
3949 (list (list t :inherit inherits)))
3950 ((or (featurep 'xemacs) (< emacs-major-version 22))
3951 ;; These do not understand the `min-colors' attribute.
3952 (let (r e a)
3953 (while (setq e (pop specs))
3954 (cond
3955 ((memq (car e) '(t default)) (push e r))
3956 ((setq a (member '(min-colors 8) (car e)))
3957 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
3958 (cdr e)))))
3959 ((setq a (assq 'min-colors (car e)))
3960 (setq e (cons (delq a (car e)) (cdr e)))
3961 (or (assoc (car e) r) (push e r)))
3962 (t (or (assoc (car e) r) (push e r)))))
3963 (nreverse r)))
3964 (t specs)))
3965 (put 'org-compatible-face 'lisp-indent-function 1)
3967 (defface org-hide
3968 '((((background light)) (:foreground "white"))
3969 (((background dark)) (:foreground "black")))
3970 "Face used to hide leading stars in headlines.
3971 The forground color of this face should be equal to the background
3972 color of the frame."
3973 :group 'org-faces)
3975 (defface org-level-1 ;; font-lock-function-name-face
3976 (org-compatible-face 'outline-1
3977 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
3978 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
3979 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
3980 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
3981 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
3982 (t (:bold t))))
3983 "Face used for level 1 headlines."
3984 :group 'org-faces)
3986 (defface org-level-2 ;; font-lock-variable-name-face
3987 (org-compatible-face 'outline-2
3988 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
3989 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
3990 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
3991 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
3992 (t (:bold t))))
3993 "Face used for level 2 headlines."
3994 :group 'org-faces)
3996 (defface org-level-3 ;; font-lock-keyword-face
3997 (org-compatible-face 'outline-3
3998 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
3999 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
4000 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
4001 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
4002 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
4003 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
4004 (t (:bold t))))
4005 "Face used for level 3 headlines."
4006 :group 'org-faces)
4008 (defface org-level-4 ;; font-lock-comment-face
4009 (org-compatible-face 'outline-4
4010 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4011 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4012 (((class color) (min-colors 16) (background light)) (:foreground "red"))
4013 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
4014 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4015 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4016 (t (:bold t))))
4017 "Face used for level 4 headlines."
4018 :group 'org-faces)
4020 (defface org-level-5 ;; font-lock-type-face
4021 (org-compatible-face 'outline-5
4022 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
4023 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
4024 (((class color) (min-colors 8)) (:foreground "green"))))
4025 "Face used for level 5 headlines."
4026 :group 'org-faces)
4028 (defface org-level-6 ;; font-lock-constant-face
4029 (org-compatible-face 'outline-6
4030 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
4031 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
4032 (((class color) (min-colors 8)) (:foreground "magenta"))))
4033 "Face used for level 6 headlines."
4034 :group 'org-faces)
4036 (defface org-level-7 ;; font-lock-builtin-face
4037 (org-compatible-face 'outline-7
4038 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
4039 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
4040 (((class color) (min-colors 8)) (:foreground "blue"))))
4041 "Face used for level 7 headlines."
4042 :group 'org-faces)
4044 (defface org-level-8 ;; font-lock-string-face
4045 (org-compatible-face 'outline-8
4046 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4047 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4048 (((class color) (min-colors 8)) (:foreground "green"))))
4049 "Face used for level 8 headlines."
4050 :group 'org-faces)
4052 (defface org-special-keyword ;; font-lock-string-face
4053 (org-compatible-face nil
4054 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4055 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4056 (t (:italic t))))
4057 "Face used for special keywords."
4058 :group 'org-faces)
4060 (defface org-drawer ;; font-lock-function-name-face
4061 (org-compatible-face nil
4062 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4063 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4064 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4065 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4066 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4067 (t (:bold t))))
4068 "Face used for drawers."
4069 :group 'org-faces)
4071 (defface org-property-value nil
4072 "Face used for the value of a property."
4073 :group 'org-faces)
4075 (defface org-column
4076 (org-compatible-face nil
4077 '((((class color) (min-colors 16) (background light))
4078 (:background "grey90"))
4079 (((class color) (min-colors 16) (background dark))
4080 (:background "grey30"))
4081 (((class color) (min-colors 8))
4082 (:background "cyan" :foreground "black"))
4083 (t (:inverse-video t))))
4084 "Face for column display of entry properties."
4085 :group 'org-faces)
4087 (when (fboundp 'set-face-attribute)
4088 ;; Make sure that a fixed-width face is used when we have a column table.
4089 (set-face-attribute 'org-column nil
4090 :height (face-attribute 'default :height)
4091 :family (face-attribute 'default :family)))
4093 (defface org-warning
4094 (org-compatible-face 'font-lock-warning-face
4095 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4096 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4097 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4098 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4099 (t (:bold t))))
4100 "Face for deadlines and TODO keywords."
4101 :group 'org-faces)
4103 (defface org-archived ; similar to shadow
4104 (org-compatible-face 'shadow
4105 '((((class color grayscale) (min-colors 88) (background light))
4106 (:foreground "grey50"))
4107 (((class color grayscale) (min-colors 88) (background dark))
4108 (:foreground "grey70"))
4109 (((class color) (min-colors 8) (background light))
4110 (:foreground "green"))
4111 (((class color) (min-colors 8) (background dark))
4112 (:foreground "yellow"))))
4113 "Face for headline with the ARCHIVE tag."
4114 :group 'org-faces)
4116 (defface org-link
4117 '((((class color) (background light)) (:foreground "Purple" :underline t))
4118 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4119 (t (:underline t)))
4120 "Face for links."
4121 :group 'org-faces)
4123 (defface org-ellipsis
4124 '((((class color) (background light)) (:foreground "DarkGoldenrod" :underline t))
4125 (((class color) (background dark)) (:foreground "LightGoldenrod" :underline t))
4126 (t (:strike-through t)))
4127 "Face for the ellipsis in folded text."
4128 :group 'org-faces)
4130 (defface org-target
4131 '((((class color) (background light)) (:underline t))
4132 (((class color) (background dark)) (:underline t))
4133 (t (:underline t)))
4134 "Face for links."
4135 :group 'org-faces)
4137 (defface org-date
4138 '((((class color) (background light)) (:foreground "Purple" :underline t))
4139 (((class color) (background dark)) (:foreground "Cyan" :underline t))
4140 (t (:underline t)))
4141 "Face for links."
4142 :group 'org-faces)
4144 (defface org-sexp-date
4145 '((((class color) (background light)) (:foreground "Purple"))
4146 (((class color) (background dark)) (:foreground "Cyan"))
4147 (t (:underline t)))
4148 "Face for links."
4149 :group 'org-faces)
4151 (defface org-tag
4152 '((t (:bold t)))
4153 "Face for tags."
4154 :group 'org-faces)
4156 (defface org-todo ; font-lock-warning-face
4157 (org-compatible-face nil
4158 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
4159 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
4160 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
4161 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4162 (t (:inverse-video t :bold t))))
4163 "Face for TODO keywords."
4164 :group 'org-faces)
4166 (defface org-done ;; font-lock-type-face
4167 (org-compatible-face nil
4168 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
4169 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
4170 (((class color) (min-colors 8)) (:foreground "green"))
4171 (t (:bold t))))
4172 "Face used for todo keywords that indicate DONE items."
4173 :group 'org-faces)
4175 (defface org-headline-done ;; font-lock-string-face
4176 (org-compatible-face nil
4177 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
4178 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
4179 (((class color) (min-colors 8) (background light)) (:bold nil))))
4180 "Face used to indicate that a headline is DONE.
4181 This face is only used if `org-fontify-done-headline' is set. If applies
4182 to the part of the headline after the DONE keyword."
4183 :group 'org-faces)
4185 (defcustom org-todo-keyword-faces nil
4186 "Faces for specific TODO keywords.
4187 This is a list of cons cells, with TODO keywords in the car
4188 and faces in the cdr. The face can be a symbol, or a property
4189 list of attributes, like (:foreground \"blue\" :weight bold :underline t)."
4190 :group 'org-faces
4191 :group 'org-todo
4192 :type '(repeat
4193 (cons
4194 (string :tag "keyword")
4195 (sexp :tag "face"))))
4197 (defface org-table ;; font-lock-function-name-face
4198 (org-compatible-face nil
4199 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4200 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4201 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4202 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4203 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
4204 (((class color) (min-colors 8) (background dark)))))
4205 "Face used for tables."
4206 :group 'org-faces)
4208 (defface org-formula
4209 (org-compatible-face nil
4210 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4211 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4212 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4213 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
4214 (t (:bold t :italic t))))
4215 "Face for formulas."
4216 :group 'org-faces)
4218 (defface org-code
4219 (org-compatible-face nil
4220 '((((class color grayscale) (min-colors 88) (background light))
4221 (:foreground "grey50"))
4222 (((class color grayscale) (min-colors 88) (background dark))
4223 (:foreground "grey70"))
4224 (((class color) (min-colors 8) (background light))
4225 (:foreground "green"))
4226 (((class color) (min-colors 8) (background dark))
4227 (:foreground "yellow"))))
4228 "Face for fixed-with text like code snippets."
4229 :group 'org-faces
4230 :version "22.1")
4232 (defface org-verbatim
4233 (org-compatible-face nil
4234 '((((class color grayscale) (min-colors 88) (background light))
4235 (:foreground "grey50" :underline t))
4236 (((class color grayscale) (min-colors 88) (background dark))
4237 (:foreground "grey70" :underline t))
4238 (((class color) (min-colors 8) (background light))
4239 (:foreground "green" :underline t))
4240 (((class color) (min-colors 8) (background dark))
4241 (:foreground "yellow" :underline t))))
4242 "Face for fixed-with text like code snippets."
4243 :group 'org-faces
4244 :version "22.1")
4246 (defface org-agenda-structure ;; font-lock-function-name-face
4247 (org-compatible-face nil
4248 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
4249 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
4250 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
4251 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
4252 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
4253 (t (:bold t))))
4254 "Face used in agenda for captions and dates."
4255 :group 'org-faces)
4257 (defface org-scheduled-today
4258 (org-compatible-face nil
4259 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
4260 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
4261 (((class color) (min-colors 8)) (:foreground "green"))
4262 (t (:bold t :italic t))))
4263 "Face for items scheduled for a certain day."
4264 :group 'org-faces)
4266 (defface org-scheduled-previously
4267 (org-compatible-face nil
4268 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4269 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4270 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4271 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4272 (t (:bold t))))
4273 "Face for items scheduled previously, and not yet done."
4274 :group 'org-faces)
4276 (defface org-upcoming-deadline
4277 (org-compatible-face nil
4278 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
4279 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
4280 (((class color) (min-colors 8) (background light)) (:foreground "red"))
4281 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
4282 (t (:bold t))))
4283 "Face for items scheduled previously, and not yet done."
4284 :group 'org-faces)
4286 (defcustom org-agenda-deadline-faces
4287 '((1.0 . org-warning)
4288 (0.5 . org-upcoming-deadline)
4289 (0.0 . default))
4290 "Faces for showing deadlines in the agenda.
4291 This is a list of cons cells. The cdr of each cell is a face to be used,
4292 and it can also just be like '(:foreground \"yellow\").
4293 Each car is a fraction of the head-warning time that must have passed for
4294 this the face in the cdr to be used for display. The numbers must be
4295 given in descending order. The head-warning time is normally taken
4296 from `org-deadline-warning-days', but can also be specified in the deadline
4297 timestamp itself, like this:
4299 DEADLINE: <2007-08-13 Mon -8d>
4301 You may use d for days, w for weeks, m for months and y for years. Months
4302 and years will only be treated in an approximate fashion (30.4 days for a
4303 month and 365.24 days for a year)."
4304 :group 'org-faces
4305 :group 'org-agenda-daily/weekly
4306 :type '(repeat
4307 (cons
4308 (number :tag "Fraction of head-warning time passed")
4309 (sexp :tag "Face"))))
4311 ;; FIXME: this is not a good face yet.
4312 (defface org-agenda-restriction-lock
4313 (org-compatible-face nil
4314 '((((class color) (min-colors 88) (background light)) (:background "yellow1"))
4315 (((class color) (min-colors 88) (background dark)) (:background "skyblue4"))
4316 (((class color) (min-colors 16) (background light)) (:background "yellow1"))
4317 (((class color) (min-colors 16) (background dark)) (:background "skyblue4"))
4318 (((class color) (min-colors 8)) (:background "cyan" :foreground "black"))
4319 (t (:inverse-video t))))
4320 "Face for showing the agenda restriction lock."
4321 :group 'org-faces)
4323 (defface org-time-grid ;; font-lock-variable-name-face
4324 (org-compatible-face nil
4325 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
4326 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
4327 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
4328 "Face used for time grids."
4329 :group 'org-faces)
4331 (defconst org-level-faces
4332 '(org-level-1 org-level-2 org-level-3 org-level-4
4333 org-level-5 org-level-6 org-level-7 org-level-8
4336 (defcustom org-n-level-faces (length org-level-faces)
4337 "The number of different faces to be used for headlines.
4338 Org-mode defines 8 different headline faces, so this can be at most 8.
4339 If it is less than 8, the level-1 face gets re-used for level N+1 etc."
4340 :type 'number
4341 :group 'org-faces)
4343 ;;; Functions and variables from ther packages
4344 ;; Declared here to avoid compiler warnings
4346 (eval-and-compile
4347 (unless (fboundp 'declare-function)
4348 (defmacro declare-function (fn file &optional arglist fileonly))))
4350 ;; XEmacs only
4351 (defvar outline-mode-menu-heading)
4352 (defvar outline-mode-menu-show)
4353 (defvar outline-mode-menu-hide)
4354 (defvar zmacs-regions) ; XEmacs regions
4356 ;; Emacs only
4357 (defvar mark-active)
4359 ;; Various packages
4360 ;; FIXME: get the argument lists for the UNKNOWN stuff
4361 (declare-function add-to-diary-list "diary-lib"
4362 (date string specifier &optional marker globcolor literal))
4363 (declare-function table--at-cell-p "table" (position &optional object at-column))
4364 (declare-function Info-find-node "info" (filename nodename &optional no-going-back))
4365 (declare-function bbdb "ext:bbdb-com" (string elidep))
4366 (declare-function bbdb-company "ext:bbdb-com" (string elidep))
4367 (declare-function bbdb-current-record "ext:bbdb-com" (&optional planning-on-modifying))
4368 (declare-function bbdb-name "ext:bbdb-com" (string elidep))
4369 (declare-function bbdb-record-getprop "ext:bbdb" (record property))
4370 (declare-function bbdb-record-name "ext:bbdb" (record))
4371 (declare-function bibtex-beginning-of-entry "bibtex" ())
4372 (declare-function bibtex-generate-autokey "bibtex" ())
4373 (declare-function bibtex-parse-entry "bibtex" (&optional content))
4374 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
4375 (defvar calc-embedded-close-formula)
4376 (defvar calc-embedded-open-formula)
4377 (declare-function calendar-astro-date-string "cal-julian" (&optional date))
4378 (declare-function calendar-bahai-date-string "cal-bahai" (&optional date))
4379 (declare-function calendar-check-holidays "holidays" (date))
4380 (declare-function calendar-chinese-date-string "cal-china" (&optional date))
4381 (declare-function calendar-coptic-date-string "cal-coptic" (&optional date))
4382 (declare-function calendar-ethiopic-date-string "cal-coptic" (&optional date))
4383 (declare-function calendar-forward-day "cal-move" (arg))
4384 (declare-function calendar-french-date-string "cal-french" (&optional date))
4385 (declare-function calendar-goto-date "cal-move" (date))
4386 (declare-function calendar-goto-today "cal-move" ())
4387 (declare-function calendar-hebrew-date-string "cal-hebrew" (&optional date))
4388 (declare-function calendar-islamic-date-string "cal-islam" (&optional date))
4389 (declare-function calendar-iso-date-string "cal-iso" (&optional date))
4390 (declare-function calendar-julian-date-string "cal-julian" (&optional date))
4391 (declare-function calendar-mayan-date-string "cal-mayan" (&optional date))
4392 (declare-function calendar-persian-date-string "cal-persia" (&optional date))
4393 (defvar calendar-mode-map)
4394 (defvar original-date) ; dynamically scoped in calendar.el does scope this
4395 (declare-function cdlatex-tab "ext:cdlatex" ())
4396 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
4397 (declare-function elmo-folder-exists-p "ext:elmo" (folder) t)
4398 (declare-function elmo-message-entity-field "ext:elmo-msgdb" (entity field &optional type))
4399 (declare-function elmo-message-field "ext:elmo" (folder number field &optional type) t)
4400 (declare-function elmo-msgdb-overview-get-entity "ext:elmo" (&rest unknown) t)
4401 (defvar font-lock-unfontify-region-function)
4402 (declare-function gnus-article-show-summary "gnus-art" ())
4403 (declare-function gnus-summary-last-subject "gnus-sum" ())
4404 (defvar gnus-other-frame-object)
4405 (defvar gnus-group-name)
4406 (defvar gnus-article-current)
4407 (defvar Info-current-file)
4408 (defvar Info-current-node)
4409 (declare-function mh-display-msg "mh-show" (msg-num folder-name))
4410 (declare-function mh-find-path "mh-utils" ())
4411 (declare-function mh-get-header-field "mh-utils" (field))
4412 (declare-function mh-get-msg-num "mh-utils" (error-if-no-message))
4413 (declare-function mh-header-display "mh-show" ())
4414 (declare-function mh-index-previous-folder "mh-search" ())
4415 (declare-function mh-normalize-folder-name "mh-utils" (folder &optional empty-string-okay dont-remove-trailing-slash return-nil-if-folder-empty))
4416 (declare-function mh-search "mh-search" (folder search-regexp &optional redo-search-flag window-config))
4417 (declare-function mh-search-choose "mh-search" (&optional searcher))
4418 (declare-function mh-show "mh-show" (&optional message redisplay-flag))
4419 (declare-function mh-show-buffer-message-number "mh-comp" (&optional buffer))
4420 (declare-function mh-show-header-display "mh-show" t t)
4421 (declare-function mh-show-msg "mh-show" (msg))
4422 (declare-function mh-show-show "mh-show" t t)
4423 (declare-function mh-visit-folder "mh-folder" (folder &optional range index-data))
4424 (defvar mh-progs)
4425 (defvar mh-current-folder)
4426 (defvar mh-show-folder-buffer)
4427 (defvar mh-index-folder)
4428 (defvar mh-searcher)
4429 (declare-function org-export-latex-cleaned-string "org-export-latex" ())
4430 (declare-function parse-time-string "parse-time" (string))
4431 (declare-function remember "remember" (&optional initial))
4432 (declare-function remember-buffer-desc "remember" ())
4433 (declare-function remember-finalize "remember" ())
4434 (defvar remember-save-after-remembering)
4435 (defvar remember-data-file)
4436 (defvar remember-register)
4437 (defvar remember-buffer)
4438 (defvar remember-handler-functions)
4439 (defvar remember-annotation-functions)
4440 (declare-function rmail-narrow-to-non-pruned-header "rmail" ())
4441 (declare-function rmail-show-message "rmail" (&optional n no-summary))
4442 (declare-function rmail-what-message "rmail" ())
4443 (defvar rmail-current-message)
4444 (defvar texmathp-why)
4445 (declare-function vm-beginning-of-message "ext:vm-page" ())
4446 (declare-function vm-follow-summary-cursor "ext:vm-motion" ())
4447 (declare-function vm-get-header-contents "ext:vm-summary" (message header-name-regexp &optional clump-sep))
4448 (declare-function vm-isearch-narrow "ext:vm-search" ())
4449 (declare-function vm-isearch-update "ext:vm-search" ())
4450 (declare-function vm-select-folder-buffer "ext:vm-macro" ())
4451 (declare-function vm-su-message-id "ext:vm-summary" (m))
4452 (declare-function vm-su-subject "ext:vm-summary" (m))
4453 (declare-function vm-summarize "ext:vm-summary" (&optional display raise))
4454 (defvar vm-message-pointer)
4455 (defvar vm-folder-directory)
4456 (defvar w3m-current-url)
4457 (defvar w3m-current-title)
4458 ;; backward compatibility to old version of wl
4459 (declare-function wl-summary-buffer-msgdb "ext:wl-folder" (&rest unknown) t)
4460 (declare-function wl-folder-get-elmo-folder "ext:wl-folder" (entity &optional no-cache))
4461 (declare-function wl-summary-goto-folder-subr "ext:wl-summary" (&optional name scan-type other-window sticky interactive scoring force-exit))
4462 (declare-function wl-summary-jump-to-msg-by-message-id "ext:wl-summary" (&optional id))
4463 (declare-function wl-summary-line-from "ext:wl-summary" ())
4464 (declare-function wl-summary-line-subject "ext:wl-summary" ())
4465 (declare-function wl-summary-message-number "ext:wl-summary" ())
4466 (declare-function wl-summary-redisplay "ext:wl-summary" (&optional arg))
4467 (defvar wl-summary-buffer-elmo-folder)
4468 (defvar wl-summary-buffer-folder-name)
4469 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4471 (defvar org-latex-regexps)
4472 (defvar constants-unit-system)
4474 ;;; Variables for pre-computed regular expressions, all buffer local
4476 (defvar org-drawer-regexp nil
4477 "Matches first line of a hidden block.")
4478 (make-variable-buffer-local 'org-drawer-regexp)
4479 (defvar org-todo-regexp nil
4480 "Matches any of the TODO state keywords.")
4481 (make-variable-buffer-local 'org-todo-regexp)
4482 (defvar org-not-done-regexp nil
4483 "Matches any of the TODO state keywords except the last one.")
4484 (make-variable-buffer-local 'org-not-done-regexp)
4485 (defvar org-todo-line-regexp nil
4486 "Matches a headline and puts TODO state into group 2 if present.")
4487 (make-variable-buffer-local 'org-todo-line-regexp)
4488 (defvar org-complex-heading-regexp nil
4489 "Matches a headline and puts everything into groups:
4490 group 1: the stars
4491 group 2: The todo keyword, maybe
4492 group 3: Priority cookie
4493 group 4: True headline
4494 group 5: Tags")
4495 (make-variable-buffer-local 'org-complex-heading-regexp)
4496 (defvar org-todo-line-tags-regexp nil
4497 "Matches a headline and puts TODO state into group 2 if present.
4498 Also put tags into group 4 if tags are present.")
4499 (make-variable-buffer-local 'org-todo-line-tags-regexp)
4500 (defvar org-nl-done-regexp nil
4501 "Matches newline followed by a headline with the DONE keyword.")
4502 (make-variable-buffer-local 'org-nl-done-regexp)
4503 (defvar org-looking-at-done-regexp nil
4504 "Matches the DONE keyword a point.")
4505 (make-variable-buffer-local 'org-looking-at-done-regexp)
4506 (defvar org-ds-keyword-length 12
4507 "Maximum length of the Deadline and SCHEDULED keywords.")
4508 (make-variable-buffer-local 'org-ds-keyword-length)
4509 (defvar org-deadline-regexp nil
4510 "Matches the DEADLINE keyword.")
4511 (make-variable-buffer-local 'org-deadline-regexp)
4512 (defvar org-deadline-time-regexp nil
4513 "Matches the DEADLINE keyword together with a time stamp.")
4514 (make-variable-buffer-local 'org-deadline-time-regexp)
4515 (defvar org-deadline-line-regexp nil
4516 "Matches the DEADLINE keyword and the rest of the line.")
4517 (make-variable-buffer-local 'org-deadline-line-regexp)
4518 (defvar org-scheduled-regexp nil
4519 "Matches the SCHEDULED keyword.")
4520 (make-variable-buffer-local 'org-scheduled-regexp)
4521 (defvar org-scheduled-time-regexp nil
4522 "Matches the SCHEDULED keyword together with a time stamp.")
4523 (make-variable-buffer-local 'org-scheduled-time-regexp)
4524 (defvar org-closed-time-regexp nil
4525 "Matches the CLOSED keyword together with a time stamp.")
4526 (make-variable-buffer-local 'org-closed-time-regexp)
4528 (defvar org-keyword-time-regexp nil
4529 "Matches any of the 4 keywords, together with the time stamp.")
4530 (make-variable-buffer-local 'org-keyword-time-regexp)
4531 (defvar org-keyword-time-not-clock-regexp nil
4532 "Matches any of the 3 keywords, together with the time stamp.")
4533 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
4534 (defvar org-maybe-keyword-time-regexp nil
4535 "Matches a timestamp, possibly preceeded by a keyword.")
4536 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
4537 (defvar org-planning-or-clock-line-re nil
4538 "Matches a line with planning or clock info.")
4539 (make-variable-buffer-local 'org-planning-or-clock-line-re)
4541 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
4542 rear-nonsticky t mouse-map t fontified t)
4543 "Properties to remove when a string without properties is wanted.")
4545 (defsubst org-match-string-no-properties (num &optional string)
4546 (if (featurep 'xemacs)
4547 (let ((s (match-string num string)))
4548 (remove-text-properties 0 (length s) org-rm-props s)
4550 (match-string-no-properties num string)))
4552 (defsubst org-no-properties (s)
4553 (if (fboundp 'set-text-properties)
4554 (set-text-properties 0 (length s) nil s)
4555 (remove-text-properties 0 (length s) org-rm-props s))
4558 (defsubst org-get-alist-option (option key)
4559 (cond ((eq key t) t)
4560 ((eq option t) t)
4561 ((assoc key option) (cdr (assoc key option)))
4562 (t (cdr (assq 'default option)))))
4564 (defsubst org-inhibit-invisibility ()
4565 "Modified `buffer-invisibility-spec' for Emacs 21.
4566 Some ops with invisible text do not work correctly on Emacs 21. For these
4567 we turn off invisibility temporarily. Use this in a `let' form."
4568 (if (< emacs-major-version 22) nil buffer-invisibility-spec))
4570 (defsubst org-set-local (var value)
4571 "Make VAR local in current buffer and set it to VALUE."
4572 (set (make-variable-buffer-local var) value))
4574 (defsubst org-mode-p ()
4575 "Check if the current buffer is in Org-mode."
4576 (eq major-mode 'org-mode))
4578 (defsubst org-last (list)
4579 "Return the last element of LIST."
4580 (car (last list)))
4582 (defun org-let (list &rest body)
4583 (eval (cons 'let (cons list body))))
4584 (put 'org-let 'lisp-indent-function 1)
4586 (defun org-let2 (list1 list2 &rest body)
4587 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
4588 (put 'org-let2 'lisp-indent-function 2)
4589 (defconst org-startup-options
4590 '(("fold" org-startup-folded t)
4591 ("overview" org-startup-folded t)
4592 ("nofold" org-startup-folded nil)
4593 ("showall" org-startup-folded nil)
4594 ("content" org-startup-folded content)
4595 ("hidestars" org-hide-leading-stars t)
4596 ("showstars" org-hide-leading-stars nil)
4597 ("odd" org-odd-levels-only t)
4598 ("oddeven" org-odd-levels-only nil)
4599 ("align" org-startup-align-all-tables t)
4600 ("noalign" org-startup-align-all-tables nil)
4601 ("customtime" org-display-custom-times t)
4602 ("logdone" org-log-done time)
4603 ("lognotedone" org-log-done note)
4604 ("nologdone" org-log-done nil)
4605 ("lognoteclock-out" org-log-note-clock-out t)
4606 ("nolognoteclock-out" org-log-note-clock-out nil)
4607 ("logrepeat" org-log-repeat state)
4608 ("lognoterepeat" org-log-repeat note)
4609 ("nologrepeat" org-log-repeat nil)
4610 ("constcgs" constants-unit-system cgs)
4611 ("constSI" constants-unit-system SI))
4612 "Variable associated with STARTUP options for org-mode.
4613 Each element is a list of three items: The startup options as written
4614 in the #+STARTUP line, the corresponding variable, and the value to
4615 set this variable to if the option is found. An optional forth element PUSH
4616 means to push this value onto the list in the variable.")
4618 (defun org-set-regexps-and-options ()
4619 "Precompute regular expressions for current buffer."
4620 (when (org-mode-p)
4621 (org-set-local 'org-todo-kwd-alist nil)
4622 (org-set-local 'org-todo-key-alist nil)
4623 (org-set-local 'org-todo-key-trigger nil)
4624 (org-set-local 'org-todo-keywords-1 nil)
4625 (org-set-local 'org-done-keywords nil)
4626 (org-set-local 'org-todo-heads nil)
4627 (org-set-local 'org-todo-sets nil)
4628 (org-set-local 'org-todo-log-states nil)
4629 (let ((re (org-make-options-regexp
4630 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
4631 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
4632 "CONSTANTS" "PROPERTY" "DRAWERS")))
4633 (splitre "[ \t]+")
4634 kwds kws0 kwsa key log value cat arch tags const links hw dws
4635 tail sep kws1 prio props drawers)
4636 (save-excursion
4637 (save-restriction
4638 (widen)
4639 (goto-char (point-min))
4640 (while (re-search-forward re nil t)
4641 (setq key (match-string 1) value (org-match-string-no-properties 2))
4642 (cond
4643 ((equal key "CATEGORY")
4644 (if (string-match "[ \t]+$" value)
4645 (setq value (replace-match "" t t value)))
4646 (setq cat value))
4647 ((member key '("SEQ_TODO" "TODO"))
4648 (push (cons 'sequence (org-split-string value splitre)) kwds))
4649 ((equal key "TYP_TODO")
4650 (push (cons 'type (org-split-string value splitre)) kwds))
4651 ((equal key "TAGS")
4652 (setq tags (append tags (org-split-string value splitre))))
4653 ((equal key "COLUMNS")
4654 (org-set-local 'org-columns-default-format value))
4655 ((equal key "LINK")
4656 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
4657 (push (cons (match-string 1 value)
4658 (org-trim (match-string 2 value)))
4659 links)))
4660 ((equal key "PRIORITIES")
4661 (setq prio (org-split-string value " +")))
4662 ((equal key "PROPERTY")
4663 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
4664 (push (cons (match-string 1 value) (match-string 2 value))
4665 props)))
4666 ((equal key "DRAWERS")
4667 (setq drawers (org-split-string value splitre)))
4668 ((equal key "CONSTANTS")
4669 (setq const (append const (org-split-string value splitre))))
4670 ((equal key "STARTUP")
4671 (let ((opts (org-split-string value splitre))
4672 l var val)
4673 (while (setq l (pop opts))
4674 (when (setq l (assoc l org-startup-options))
4675 (setq var (nth 1 l) val (nth 2 l))
4676 (if (not (nth 3 l))
4677 (set (make-local-variable var) val)
4678 (if (not (listp (symbol-value var)))
4679 (set (make-local-variable var) nil))
4680 (set (make-local-variable var) (symbol-value var))
4681 (add-to-list var val))))))
4682 ((equal key "ARCHIVE")
4683 (string-match " *$" value)
4684 (setq arch (replace-match "" t t value))
4685 (remove-text-properties 0 (length arch)
4686 '(face t fontified t) arch)))
4688 (when cat
4689 (org-set-local 'org-category (intern cat))
4690 (push (cons "CATEGORY" cat) props))
4691 (when prio
4692 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4693 (setq prio (mapcar 'string-to-char prio))
4694 (org-set-local 'org-highest-priority (nth 0 prio))
4695 (org-set-local 'org-lowest-priority (nth 1 prio))
4696 (org-set-local 'org-default-priority (nth 2 prio)))
4697 (and props (org-set-local 'org-local-properties (nreverse props)))
4698 (and drawers (org-set-local 'org-drawers drawers))
4699 (and arch (org-set-local 'org-archive-location arch))
4700 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4701 ;; Process the TODO keywords
4702 (unless kwds
4703 ;; Use the global values as if they had been given locally.
4704 (setq kwds (default-value 'org-todo-keywords))
4705 (if (stringp (car kwds))
4706 (setq kwds (list (cons org-todo-interpretation
4707 (default-value 'org-todo-keywords)))))
4708 (setq kwds (reverse kwds)))
4709 (setq kwds (nreverse kwds))
4710 (let (inter kws kw)
4711 (while (setq kws (pop kwds))
4712 (setq inter (pop kws) sep (member "|" kws)
4713 kws0 (delete "|" (copy-sequence kws))
4714 kwsa nil
4715 kws1 (mapcar
4716 (lambda (x)
4717 ;; 1 2
4718 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4719 (progn
4720 (setq kw (match-string 1 x)
4721 key (and (match-end 2) (match-string 2 x))
4722 log (org-extract-log-state-settings x))
4723 (push (cons kw (and key (string-to-char key))) kwsa)
4724 (and log (push log org-todo-log-states))
4726 (error "Invalid TODO keyword %s" x)))
4727 kws0)
4728 kwsa (if kwsa (append '((:startgroup))
4729 (nreverse kwsa)
4730 '((:endgroup))))
4731 hw (car kws1)
4732 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4733 tail (list inter hw (car dws) (org-last dws)))
4734 (add-to-list 'org-todo-heads hw 'append)
4735 (push kws1 org-todo-sets)
4736 (setq org-done-keywords (append org-done-keywords dws nil))
4737 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4738 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4739 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4740 (setq org-todo-sets (nreverse org-todo-sets)
4741 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4742 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4743 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4744 ;; Process the constants
4745 (when const
4746 (let (e cst)
4747 (while (setq e (pop const))
4748 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4749 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4750 (setq org-table-formula-constants-local cst)))
4752 ;; Process the tags.
4753 (when tags
4754 (let (e tgs)
4755 (while (setq e (pop tags))
4756 (cond
4757 ((equal e "{") (push '(:startgroup) tgs))
4758 ((equal e "}") (push '(:endgroup) tgs))
4759 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4760 (push (cons (match-string 1 e)
4761 (string-to-char (match-string 2 e)))
4762 tgs))
4763 (t (push (list e) tgs))))
4764 (org-set-local 'org-tag-alist nil)
4765 (while (setq e (pop tgs))
4766 (or (and (stringp (car e))
4767 (assoc (car e) org-tag-alist))
4768 (push e org-tag-alist))))))
4770 ;; Compute the regular expressions and other local variables
4771 (if (not org-done-keywords)
4772 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
4773 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4774 (length org-scheduled-string)))
4775 org-drawer-regexp
4776 (concat "^[ \t]*:\\("
4777 (mapconcat 'regexp-quote org-drawers "\\|")
4778 "\\):[ \t]*$")
4779 org-not-done-keywords
4780 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4781 org-todo-regexp
4782 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4783 "\\|") "\\)\\>")
4784 org-not-done-regexp
4785 (concat "\\<\\("
4786 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4787 "\\)\\>")
4788 org-todo-line-regexp
4789 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4790 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4791 "\\)\\>\\)?[ \t]*\\(.*\\)")
4792 org-complex-heading-regexp
4793 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
4794 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4795 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4796 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4797 org-nl-done-regexp
4798 (concat "\n\\*+[ \t]+"
4799 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4800 "\\)" "\\>")
4801 org-todo-line-tags-regexp
4802 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4803 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4804 (org-re
4805 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4806 org-looking-at-done-regexp
4807 (concat "^" "\\(?:"
4808 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4809 "\\>")
4810 org-deadline-regexp (concat "\\<" org-deadline-string)
4811 org-deadline-time-regexp
4812 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4813 org-deadline-line-regexp
4814 (concat "\\<\\(" org-deadline-string "\\).*")
4815 org-scheduled-regexp
4816 (concat "\\<" org-scheduled-string)
4817 org-scheduled-time-regexp
4818 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4819 org-closed-time-regexp
4820 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4821 org-keyword-time-regexp
4822 (concat "\\<\\(" org-scheduled-string
4823 "\\|" org-deadline-string
4824 "\\|" org-closed-string
4825 "\\|" org-clock-string "\\)"
4826 " *[[<]\\([^]>]+\\)[]>]")
4827 org-keyword-time-not-clock-regexp
4828 (concat "\\<\\(" org-scheduled-string
4829 "\\|" org-deadline-string
4830 "\\|" org-closed-string
4831 "\\)"
4832 " *[[<]\\([^]>]+\\)[]>]")
4833 org-maybe-keyword-time-regexp
4834 (concat "\\(\\<\\(" org-scheduled-string
4835 "\\|" org-deadline-string
4836 "\\|" org-closed-string
4837 "\\|" org-clock-string "\\)\\)?"
4838 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4839 org-planning-or-clock-line-re
4840 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4841 "\\|" org-deadline-string
4842 "\\|" org-closed-string "\\|" org-clock-string
4843 "\\)\\>\\)")
4845 (org-compute-latex-and-specials-regexp)
4846 (org-set-font-lock-defaults)))
4848 (defun org-extract-log-state-settings (x)
4849 "Extract the log state setting from a TODO keyword string.
4850 This will extract info from a string like \"WAIT(w@/!)\"."
4851 (let (kw key log1 log2)
4852 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4853 (setq kw (match-string 1 x)
4854 key (and (match-end 2) (match-string 2 x))
4855 log1 (and (match-end 3) (match-string 3 x))
4856 log2 (and (match-end 4) (match-string 4 x)))
4857 (and (or log1 log2)
4858 (list kw
4859 (and log1 (if (equal log1 "!") 'time 'note))
4860 (and log2 (if (equal log2 "!") 'time 'note)))))))
4862 (defun org-remove-keyword-keys (list)
4863 "Remove a pair of parenthesis at the end of each string in LIST."
4864 (mapcar (lambda (x)
4865 (if (string-match "(.*)$" x)
4866 (substring x 0 (match-beginning 0))
4868 list))
4870 ;; FIXME: this could be done much better, using second characters etc.
4871 (defun org-assign-fast-keys (alist)
4872 "Assign fast keys to a keyword-key alist.
4873 Respect keys that are already there."
4874 (let (new e k c c1 c2 (char ?a))
4875 (while (setq e (pop alist))
4876 (cond
4877 ((equal e '(:startgroup)) (push e new))
4878 ((equal e '(:endgroup)) (push e new))
4880 (setq k (car e) c2 nil)
4881 (if (cdr e)
4882 (setq c (cdr e))
4883 ;; automatically assign a character.
4884 (setq c1 (string-to-char
4885 (downcase (substring
4886 k (if (= (string-to-char k) ?@) 1 0)))))
4887 (if (or (rassoc c1 new) (rassoc c1 alist))
4888 (while (or (rassoc char new) (rassoc char alist))
4889 (setq char (1+ char)))
4890 (setq c2 c1))
4891 (setq c (or c2 char)))
4892 (push (cons k c) new))))
4893 (nreverse new)))
4895 ;;; Some variables ujsed in various places
4897 (defvar org-window-configuration nil
4898 "Used in various places to store a window configuration.")
4899 (defvar org-finish-function nil
4900 "Function to be called when `C-c C-c' is used.
4901 This is for getting out of special buffers like remember.")
4904 ;; FIXME: Occasionally check by commenting these, to make sure
4905 ;; no other functions uses these, forgetting to let-bind them.
4906 (defvar entry)
4907 (defvar state)
4908 (defvar last-state)
4909 (defvar date)
4910 (defvar description)
4912 ;; Defined somewhere in this file, but used before definition.
4913 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
4914 (defvar org-agenda-buffer-name)
4915 (defvar org-agenda-undo-list)
4916 (defvar org-agenda-pending-undo-list)
4917 (defvar org-agenda-overriding-header)
4918 (defvar orgtbl-mode)
4919 (defvar org-html-entities)
4920 (defvar org-struct-menu)
4921 (defvar org-org-menu)
4922 (defvar org-tbl-menu)
4923 (defvar org-agenda-keymap)
4925 ;;;; Emacs/XEmacs compatibility
4927 ;; Overlay compatibility functions
4928 (defun org-make-overlay (beg end &optional buffer)
4929 (if (featurep 'xemacs)
4930 (make-extent beg end buffer)
4931 (make-overlay beg end buffer)))
4932 (defun org-delete-overlay (ovl)
4933 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4934 (defun org-detach-overlay (ovl)
4935 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4936 (defun org-move-overlay (ovl beg end &optional buffer)
4937 (if (featurep 'xemacs)
4938 (set-extent-endpoints ovl beg end (or buffer (current-buffer)))
4939 (move-overlay ovl beg end buffer)))
4940 (defun org-overlay-put (ovl prop value)
4941 (if (featurep 'xemacs)
4942 (set-extent-property ovl prop value)
4943 (overlay-put ovl prop value)))
4944 (defun org-overlay-display (ovl text &optional face evap)
4945 "Make overlay OVL display TEXT with face FACE."
4946 (if (featurep 'xemacs)
4947 (let ((gl (make-glyph text)))
4948 (and face (set-glyph-face gl face))
4949 (set-extent-property ovl 'invisible t)
4950 (set-extent-property ovl 'end-glyph gl))
4951 (overlay-put ovl 'display text)
4952 (if face (overlay-put ovl 'face face))
4953 (if evap (overlay-put ovl 'evaporate t))))
4954 (defun org-overlay-before-string (ovl text &optional face evap)
4955 "Make overlay OVL display TEXT with face FACE."
4956 (if (featurep 'xemacs)
4957 (let ((gl (make-glyph text)))
4958 (and face (set-glyph-face gl face))
4959 (set-extent-property ovl 'begin-glyph gl))
4960 (if face (org-add-props text nil 'face face))
4961 (overlay-put ovl 'before-string text)
4962 (if evap (overlay-put ovl 'evaporate t))))
4963 (defun org-overlay-get (ovl prop)
4964 (if (featurep 'xemacs)
4965 (extent-property ovl prop)
4966 (overlay-get ovl prop)))
4967 (defun org-overlays-at (pos)
4968 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
4969 (defun org-overlays-in (&optional start end)
4970 (if (featurep 'xemacs)
4971 (extent-list nil start end)
4972 (overlays-in start end)))
4973 (defun org-overlay-start (o)
4974 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
4975 (defun org-overlay-end (o)
4976 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
4977 (defun org-find-overlays (prop &optional pos delete)
4978 "Find all overlays specifying PROP at POS or point.
4979 If DELETE is non-nil, delete all those overlays."
4980 (let ((overlays (org-overlays-at (or pos (point))))
4981 ov found)
4982 (while (setq ov (pop overlays))
4983 (if (org-overlay-get ov prop)
4984 (if delete (org-delete-overlay ov) (push ov found))))
4985 found))
4987 ;; Region compatibility
4989 (defun org-add-hook (hook function &optional append local)
4990 "Add-hook, compatible with both Emacsen."
4991 (if (and local (featurep 'xemacs))
4992 (add-local-hook hook function append)
4993 (add-hook hook function append local)))
4995 (defvar org-ignore-region nil
4996 "To temporarily disable the active region.")
4998 (defun org-region-active-p ()
4999 "Is `transient-mark-mode' on and the region active?
5000 Works on both Emacs and XEmacs."
5001 (if org-ignore-region
5003 (if (featurep 'xemacs)
5004 (and zmacs-regions (region-active-p))
5005 (if (fboundp 'use-region-p)
5006 (use-region-p)
5007 (and transient-mark-mode mark-active))))) ; Emacs 22 and before
5009 ;; Invisibility compatibility
5011 (defun org-add-to-invisibility-spec (arg)
5012 "Add elements to `buffer-invisibility-spec'.
5013 See documentation for `buffer-invisibility-spec' for the kind of elements
5014 that can be added."
5015 (cond
5016 ((fboundp 'add-to-invisibility-spec)
5017 (add-to-invisibility-spec arg))
5018 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
5019 (setq buffer-invisibility-spec (list arg)))
5021 (setq buffer-invisibility-spec
5022 (cons arg buffer-invisibility-spec)))))
5024 (defun org-remove-from-invisibility-spec (arg)
5025 "Remove elements from `buffer-invisibility-spec'."
5026 (if (fboundp 'remove-from-invisibility-spec)
5027 (remove-from-invisibility-spec arg)
5028 (if (consp buffer-invisibility-spec)
5029 (setq buffer-invisibility-spec
5030 (delete arg buffer-invisibility-spec)))))
5032 (defun org-in-invisibility-spec-p (arg)
5033 "Is ARG a member of `buffer-invisibility-spec'?"
5034 (if (consp buffer-invisibility-spec)
5035 (member arg buffer-invisibility-spec)
5036 nil))
5038 ;;;; Define the Org-mode
5040 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
5041 (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."))
5044 ;; We use a before-change function to check if a table might need
5045 ;; an update.
5046 (defvar org-table-may-need-update t
5047 "Indicates that a table might need an update.
5048 This variable is set by `org-before-change-function'.
5049 `org-table-align' sets it back to nil.")
5050 (defvar org-mode-map)
5051 (defvar org-mode-hook nil)
5052 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
5053 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5054 (defvar org-table-buffer-is-an nil)
5055 (defconst org-outline-regexp "\\*+ ")
5057 ;;;###autoload
5058 (define-derived-mode org-mode outline-mode "Org"
5059 "Outline-based notes management and organizer, alias
5060 \"Carsten's outline-mode for keeping track of everything.\"
5062 Org-mode develops organizational tasks around a NOTES file which
5063 contains information about projects as plain text. Org-mode is
5064 implemented on top of outline-mode, which is ideal to keep the content
5065 of large files well structured. It supports ToDo items, deadlines and
5066 time stamps, which magically appear in the diary listing of the Emacs
5067 calendar. Tables are easily created with a built-in table editor.
5068 Plain text URL-like links connect to websites, emails (VM), Usenet
5069 messages (Gnus), BBDB entries, and any files related to the project.
5070 For printing and sharing of notes, an Org-mode file (or a part of it)
5071 can be exported as a structured ASCII or HTML file.
5073 The following commands are available:
5075 \\{org-mode-map}"
5077 ;; Get rid of Outline menus, they are not needed
5078 ;; Need to do this here because define-derived-mode sets up
5079 ;; the keymap so late. Still, it is a waste to call this each time
5080 ;; we switch another buffer into org-mode.
5081 (if (featurep 'xemacs)
5082 (when (boundp 'outline-mode-menu-heading)
5083 ;; Assume this is Greg's port, it used easymenu
5084 (easy-menu-remove outline-mode-menu-heading)
5085 (easy-menu-remove outline-mode-menu-show)
5086 (easy-menu-remove outline-mode-menu-hide))
5087 (define-key org-mode-map [menu-bar headings] 'undefined)
5088 (define-key org-mode-map [menu-bar hide] 'undefined)
5089 (define-key org-mode-map [menu-bar show] 'undefined))
5091 (easy-menu-add org-org-menu)
5092 (easy-menu-add org-tbl-menu)
5093 (org-install-agenda-files-menu)
5094 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
5095 (org-add-to-invisibility-spec '(org-cwidth))
5096 (when (featurep 'xemacs)
5097 (org-set-local 'line-move-ignore-invisible t))
5098 (org-set-local 'outline-regexp org-outline-regexp)
5099 (org-set-local 'outline-level 'org-outline-level)
5100 (when (and org-ellipsis
5101 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5102 (fboundp 'make-glyph-code))
5103 (unless org-display-table
5104 (setq org-display-table (make-display-table)))
5105 (set-display-table-slot
5106 org-display-table 4
5107 (vconcat (mapcar
5108 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5109 org-ellipsis)))
5110 (if (stringp org-ellipsis) org-ellipsis "..."))))
5111 (setq buffer-display-table org-display-table))
5112 (org-set-regexps-and-options)
5113 ;; Calc embedded
5114 (org-set-local 'calc-embedded-open-mode "# ")
5115 (modify-syntax-entry ?# "<")
5116 (modify-syntax-entry ?@ "w")
5117 (if org-startup-truncated (setq truncate-lines t))
5118 (org-set-local 'font-lock-unfontify-region-function
5119 'org-unfontify-region)
5120 ;; Activate before-change-function
5121 (org-set-local 'org-table-may-need-update t)
5122 (org-add-hook 'before-change-functions 'org-before-change-function nil
5123 'local)
5124 ;; Check for running clock before killing a buffer
5125 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5126 ;; Paragraphs and auto-filling
5127 (org-set-autofill-regexps)
5128 (setq indent-line-function 'org-indent-line-function)
5129 (org-update-radio-target-regexp)
5131 ;; Comment characters
5132 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
5133 (org-set-local 'comment-padding " ")
5135 ;; Align options lines
5136 (org-set-local
5137 'align-mode-rules-list
5138 '((org-in-buffer-settings
5139 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5140 (modes . '(org-mode)))))
5142 ;; Imenu
5143 (org-set-local 'imenu-create-index-function
5144 'org-imenu-get-tree)
5146 ;; Make isearch reveal context
5147 (if (or (featurep 'xemacs)
5148 (not (boundp 'outline-isearch-open-invisible-function)))
5149 ;; Emacs 21 and XEmacs make use of the hook
5150 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
5151 ;; Emacs 22 deals with this through a special variable
5152 (org-set-local 'outline-isearch-open-invisible-function
5153 (lambda (&rest ignore) (org-show-context 'isearch))))
5155 ;; If empty file that did not turn on org-mode automatically, make it to.
5156 (if (and org-insert-mode-line-in-empty-file
5157 (interactive-p)
5158 (= (point-min) (point-max)))
5159 (insert "# -*- mode: org -*-\n\n"))
5161 (unless org-inhibit-startup
5162 (when org-startup-align-all-tables
5163 (let ((bmp (buffer-modified-p)))
5164 (org-table-map-tables 'org-table-align)
5165 (set-buffer-modified-p bmp)))
5166 (org-cycle-hide-drawers 'all)
5167 (cond
5168 ((eq org-startup-folded t)
5169 (org-cycle '(4)))
5170 ((eq org-startup-folded 'content)
5171 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5172 (org-cycle '(4)) (org-cycle '(4)))))))
5174 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
5176 (defsubst org-call-with-arg (command arg)
5177 "Call COMMAND interactively, but pretend prefix are was ARG."
5178 (let ((current-prefix-arg arg)) (call-interactively command)))
5180 (defsubst org-current-line (&optional pos)
5181 (save-excursion
5182 (and pos (goto-char pos))
5183 ;; works also in narrowed buffer, because we start at 1, not point-min
5184 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
5186 (defun org-current-time ()
5187 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
5188 (if (> (car org-time-stamp-rounding-minutes) 1)
5189 (let ((r (car org-time-stamp-rounding-minutes))
5190 (time (decode-time)))
5191 (apply 'encode-time
5192 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5193 (nthcdr 2 time))))
5194 (current-time)))
5196 (defun org-add-props (string plist &rest props)
5197 "Add text properties to entire string, from beginning to end.
5198 PLIST may be a list of properties, PROPS are individual properties and values
5199 that will be added to PLIST. Returns the string that was modified."
5200 (add-text-properties
5201 0 (length string) (if props (append plist props) plist) string)
5202 string)
5203 (put 'org-add-props 'lisp-indent-function 2)
5206 ;;;; Font-Lock stuff, including the activators
5208 (defvar org-mouse-map (make-sparse-keymap))
5209 (org-defkey org-mouse-map
5210 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
5211 (org-defkey org-mouse-map
5212 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
5213 (when org-mouse-1-follows-link
5214 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5215 (when org-tab-follows-link
5216 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5217 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5218 (when org-return-follows-link
5219 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
5220 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
5222 (require 'font-lock)
5224 (defconst org-non-link-chars "]\t\n\r<>")
5225 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news" "bbdb" "vm"
5226 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp" "message"))
5227 (defvar org-link-re-with-space nil
5228 "Matches a link with spaces, optional angular brackets around it.")
5229 (defvar org-link-re-with-space2 nil
5230 "Matches a link with spaces, optional angular brackets around it.")
5231 (defvar org-angle-link-re nil
5232 "Matches link with angular brackets, spaces are allowed.")
5233 (defvar org-plain-link-re nil
5234 "Matches plain link, without spaces.")
5235 (defvar org-bracket-link-regexp nil
5236 "Matches a link in double brackets.")
5237 (defvar org-bracket-link-analytic-regexp nil
5238 "Regular expression used to analyze links.
5239 Here is what the match groups contain after a match:
5240 1: http:
5241 2: http
5242 3: path
5243 4: [desc]
5244 5: desc")
5245 (defvar org-any-link-re nil
5246 "Regular expression matching any link.")
5248 (defun org-make-link-regexps ()
5249 "Update the link regular expressions.
5250 This should be called after the variable `org-link-types' has changed."
5251 (setq org-link-re-with-space
5252 (concat
5253 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5254 "\\([^" org-non-link-chars " ]"
5255 "[^" org-non-link-chars "]*"
5256 "[^" org-non-link-chars " ]\\)>?")
5257 org-link-re-with-space2
5258 (concat
5259 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5260 "\\([^" org-non-link-chars " ]"
5261 "[^]\t\n\r]*"
5262 "[^" org-non-link-chars " ]\\)>?")
5263 org-angle-link-re
5264 (concat
5265 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5266 "\\([^" org-non-link-chars " ]"
5267 "[^" org-non-link-chars "]*"
5268 "\\)>")
5269 org-plain-link-re
5270 (concat
5271 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
5272 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5273 org-bracket-link-regexp
5274 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5275 org-bracket-link-analytic-regexp
5276 (concat
5277 "\\[\\["
5278 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
5279 "\\([^]]+\\)"
5280 "\\]"
5281 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5282 "\\]")
5283 org-any-link-re
5284 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5285 org-angle-link-re "\\)\\|\\("
5286 org-plain-link-re "\\)")))
5288 (org-make-link-regexps)
5290 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
5291 "Regular expression for fast time stamp matching.")
5292 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
5293 "Regular expression for fast time stamp matching.")
5294 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5295 "Regular expression matching time strings for analysis.
5296 This one does not require the space after the date, so it can be used
5297 on a string that terminates immediately after the date.")
5298 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
5299 "Regular expression matching time strings for analysis.")
5300 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
5301 "Regular expression matching time stamps, with groups.")
5302 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
5303 "Regular expression matching time stamps (also [..]), with groups.")
5304 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
5305 "Regular expression matching a time stamp range.")
5306 (defconst org-tr-regexp-both
5307 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
5308 "Regular expression matching a time stamp range.")
5309 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
5310 org-ts-regexp "\\)?")
5311 "Regular expression matching a time stamp or time stamp range.")
5312 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
5313 org-ts-regexp-both "\\)?")
5314 "Regular expression matching a time stamp or time stamp range.
5315 The time stamps may be either active or inactive.")
5317 (defvar org-emph-face nil)
5319 (defun org-do-emphasis-faces (limit)
5320 "Run through the buffer and add overlays to links."
5321 (let (rtn)
5322 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5323 (if (not (= (char-after (match-beginning 3))
5324 (char-after (match-beginning 4))))
5325 (progn
5326 (setq rtn t)
5327 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5328 'face
5329 (nth 1 (assoc (match-string 3)
5330 org-emphasis-alist)))
5331 (add-text-properties (match-beginning 2) (match-end 2)
5332 '(font-lock-multiline t))
5333 (when org-hide-emphasis-markers
5334 (add-text-properties (match-end 4) (match-beginning 5)
5335 '(invisible org-link))
5336 (add-text-properties (match-beginning 3) (match-end 3)
5337 '(invisible org-link)))))
5338 (backward-char 1))
5339 rtn))
5341 (defun org-emphasize (&optional char)
5342 "Insert or change an emphasis, i.e. a font like bold or italic.
5343 If there is an active region, change that region to a new emphasis.
5344 If there is no region, just insert the marker characters and position
5345 the cursor between them.
5346 CHAR should be either the marker character, or the first character of the
5347 HTML tag associated with that emphasis. If CHAR is a space, the means
5348 to remove the emphasis of the selected region.
5349 If char is not given (for example in an interactive call) it
5350 will be prompted for."
5351 (interactive)
5352 (let ((eal org-emphasis-alist) e det
5353 (erc org-emphasis-regexp-components)
5354 (prompt "")
5355 (string "") beg end move tag c s)
5356 (if (org-region-active-p)
5357 (setq beg (region-beginning) end (region-end)
5358 string (buffer-substring beg end))
5359 (setq move t))
5361 (while (setq e (pop eal))
5362 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
5363 c (aref tag 0))
5364 (push (cons c (string-to-char (car e))) det)
5365 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
5366 (substring tag 1)))))
5367 (unless char
5368 (message "%s" (concat "Emphasis marker or tag:" prompt))
5369 (setq char (read-char-exclusive)))
5370 (setq char (or (cdr (assoc char det)) char))
5371 (if (equal char ?\ )
5372 (setq s "" move nil)
5373 (unless (assoc (char-to-string char) org-emphasis-alist)
5374 (error "No such emphasis marker: \"%c\"" char))
5375 (setq s (char-to-string char)))
5376 (while (and (> (length string) 1)
5377 (equal (substring string 0 1) (substring string -1))
5378 (assoc (substring string 0 1) org-emphasis-alist))
5379 (setq string (substring string 1 -1)))
5380 (setq string (concat s string s))
5381 (if beg (delete-region beg end))
5382 (unless (or (bolp)
5383 (string-match (concat "[" (nth 0 erc) "\n]")
5384 (char-to-string (char-before (point)))))
5385 (insert " "))
5386 (unless (string-match (concat "[" (nth 1 erc) "\n]")
5387 (char-to-string (char-after (point))))
5388 (insert " ") (backward-char 1))
5389 (insert string)
5390 (and move (backward-char 1))))
5392 (defconst org-nonsticky-props
5393 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
5396 (defun org-activate-plain-links (limit)
5397 "Run through the buffer and add overlays to links."
5398 (catch 'exit
5399 (let (f)
5400 (while (re-search-forward org-plain-link-re limit t)
5401 (setq f (get-text-property (match-beginning 0) 'face))
5402 (if (or (eq f 'org-tag)
5403 (and (listp f) (memq 'org-tag f)))
5405 (add-text-properties (match-beginning 0) (match-end 0)
5406 (list 'mouse-face 'highlight
5407 'rear-nonsticky org-nonsticky-props
5408 'keymap org-mouse-map
5410 (throw 'exit t))))))
5412 (defun org-activate-code (limit)
5413 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
5414 (unless (get-text-property (match-beginning 1) 'face)
5415 (remove-text-properties (match-beginning 0) (match-end 0)
5416 '(display t invisible t intangible t))
5417 t)))
5419 (defun org-activate-angle-links (limit)
5420 "Run through the buffer and add overlays to links."
5421 (if (re-search-forward org-angle-link-re limit t)
5422 (progn
5423 (add-text-properties (match-beginning 0) (match-end 0)
5424 (list 'mouse-face 'highlight
5425 'rear-nonsticky org-nonsticky-props
5426 'keymap org-mouse-map
5428 t)))
5430 (defmacro org-maybe-intangible (props)
5431 "Add '(intangigble t) to PROPS if Emacs version is earlier than Emacs 22.
5432 In emacs 21, invisible text is not avoided by the command loop, so the
5433 intangible property is needed to make sure point skips this text.
5434 In Emacs 22, this is not necessary. The intangible text property has
5435 led to problems with flyspell. These problems are fixed in flyspell.el,
5436 but we still avoid setting the property in Emacs 22 and later.
5437 We use a macro so that the test can happen at compilation time."
5438 (if (< emacs-major-version 22)
5439 `(append '(intangible t) ,props)
5440 props))
5442 (defun org-activate-bracket-links (limit)
5443 "Run through the buffer and add overlays to bracketed links."
5444 (if (re-search-forward org-bracket-link-regexp limit t)
5445 (let* ((help (concat "LINK: "
5446 (org-match-string-no-properties 1)))
5447 ;; FIXME: above we should remove the escapes.
5448 ;; but that requires another match, protecting match data,
5449 ;; a lot of overhead for font-lock.
5450 (ip (org-maybe-intangible
5451 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
5452 'keymap org-mouse-map 'mouse-face 'highlight
5453 'font-lock-multiline t 'help-echo help)))
5454 (vp (list 'rear-nonsticky org-nonsticky-props
5455 'keymap org-mouse-map 'mouse-face 'highlight
5456 ' font-lock-multiline t 'help-echo help)))
5457 ;; We need to remove the invisible property here. Table narrowing
5458 ;; may have made some of this invisible.
5459 (remove-text-properties (match-beginning 0) (match-end 0)
5460 '(invisible nil))
5461 (if (match-end 3)
5462 (progn
5463 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5464 (add-text-properties (match-beginning 3) (match-end 3) vp)
5465 (add-text-properties (match-end 3) (match-end 0) ip))
5466 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5467 (add-text-properties (match-beginning 1) (match-end 1) vp)
5468 (add-text-properties (match-end 1) (match-end 0) ip))
5469 t)))
5471 (defun org-activate-dates (limit)
5472 "Run through the buffer and add overlays to dates."
5473 (if (re-search-forward org-tsr-regexp-both limit t)
5474 (progn
5475 (add-text-properties (match-beginning 0) (match-end 0)
5476 (list 'mouse-face 'highlight
5477 'rear-nonsticky org-nonsticky-props
5478 'keymap org-mouse-map))
5479 (when org-display-custom-times
5480 (if (match-end 3)
5481 (org-display-custom-time (match-beginning 3) (match-end 3)))
5482 (org-display-custom-time (match-beginning 1) (match-end 1)))
5483 t)))
5485 (defvar org-target-link-regexp nil
5486 "Regular expression matching radio targets in plain text.")
5487 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
5488 "Regular expression matching a link target.")
5489 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
5490 "Regular expression matching a radio target.")
5491 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
5492 "Regular expression matching any target.")
5494 (defun org-activate-target-links (limit)
5495 "Run through the buffer and add overlays to target matches."
5496 (when org-target-link-regexp
5497 (let ((case-fold-search t))
5498 (if (re-search-forward org-target-link-regexp limit t)
5499 (progn
5500 (add-text-properties (match-beginning 0) (match-end 0)
5501 (list 'mouse-face 'highlight
5502 'rear-nonsticky org-nonsticky-props
5503 'keymap org-mouse-map
5504 'help-echo "Radio target link"
5505 'org-linked-text t))
5506 t)))))
5508 (defun org-update-radio-target-regexp ()
5509 "Find all radio targets in this file and update the regular expression."
5510 (interactive)
5511 (when (memq 'radio org-activate-links)
5512 (setq org-target-link-regexp
5513 (org-make-target-link-regexp (org-all-targets 'radio)))
5514 (org-restart-font-lock)))
5516 (defun org-hide-wide-columns (limit)
5517 (let (s e)
5518 (setq s (text-property-any (point) (or limit (point-max))
5519 'org-cwidth t))
5520 (when s
5521 (setq e (next-single-property-change s 'org-cwidth))
5522 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
5523 (goto-char e)
5524 t)))
5526 (defvar org-latex-and-specials-regexp nil
5527 "Regular expression for highlighting export special stuff.")
5528 (defvar org-match-substring-regexp)
5529 (defvar org-match-substring-with-braces-regexp)
5530 (defvar org-export-html-special-string-regexps)
5532 (defun org-compute-latex-and-specials-regexp ()
5533 "Compute regular expression for stuff treated specially by exporters."
5534 (if (not org-highlight-latex-fragments-and-specials)
5535 (org-set-local 'org-latex-and-specials-regexp nil)
5536 (let*
5537 ((matchers (plist-get org-format-latex-options :matchers))
5538 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
5539 org-latex-regexps)))
5540 (options (org-combine-plists (org-default-export-plist)
5541 (org-infile-export-plist)))
5542 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
5543 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
5544 (org-export-with-TeX-macros (plist-get options :TeX-macros))
5545 (org-export-html-expand (plist-get options :expand-quoted-html))
5546 (org-export-with-special-strings (plist-get options :special-strings))
5547 (re-sub
5548 (cond
5549 ((equal org-export-with-sub-superscripts '{})
5550 (list org-match-substring-with-braces-regexp))
5551 (org-export-with-sub-superscripts
5552 (list org-match-substring-regexp))
5553 (t nil)))
5554 (re-latex
5555 (if org-export-with-LaTeX-fragments
5556 (mapcar (lambda (x) (nth 1 x)) latexs)))
5557 (re-macros
5558 (if org-export-with-TeX-macros
5559 (list (concat "\\\\"
5560 (regexp-opt
5561 (append (mapcar 'car org-html-entities)
5562 (if (boundp 'org-latex-entities)
5563 org-latex-entities nil))
5564 'words))) ; FIXME
5566 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
5567 (re-special (if org-export-with-special-strings
5568 (mapcar (lambda (x) (car x))
5569 org-export-html-special-string-regexps)))
5570 (re-rest
5571 (delq nil
5572 (list
5573 (if org-export-html-expand "@<[^>\n]+>")
5574 ))))
5575 (org-set-local
5576 'org-latex-and-specials-regexp
5577 (mapconcat 'identity (append re-latex re-sub re-macros re-special
5578 re-rest) "\\|")))))
5580 (defface org-latex-and-export-specials
5581 (let ((font (cond ((assq :inherit custom-face-attributes)
5582 '(:inherit underline))
5583 (t '(:underline t)))))
5584 `((((class grayscale) (background light))
5585 (:foreground "DimGray" ,@font))
5586 (((class grayscale) (background dark))
5587 (:foreground "LightGray" ,@font))
5588 (((class color) (background light))
5589 (:foreground "SaddleBrown"))
5590 (((class color) (background dark))
5591 (:foreground "burlywood"))
5592 (t (,@font))))
5593 "Face used to highlight math latex and other special exporter stuff."
5594 :group 'org-faces)
5596 (defun org-do-latex-and-special-faces (limit)
5597 "Run through the buffer and add overlays to links."
5598 (when org-latex-and-specials-regexp
5599 (let (rtn d)
5600 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
5601 limit t))
5602 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
5603 'face))
5604 '(org-code org-verbatim underline)))
5605 (progn
5606 (setq rtn t
5607 d (cond ((member (char-after (1+ (match-beginning 0)))
5608 '(?_ ?^)) 1)
5609 (t 0)))
5610 (font-lock-prepend-text-property
5611 (+ d (match-beginning 0)) (match-end 0)
5612 'face 'org-latex-and-export-specials)
5613 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
5614 '(font-lock-multiline t)))))
5615 rtn)))
5617 (defun org-restart-font-lock ()
5618 "Restart font-lock-mode, to force refontification."
5619 (when (and (boundp 'font-lock-mode) font-lock-mode)
5620 (font-lock-mode -1)
5621 (font-lock-mode 1)))
5623 (defun org-all-targets (&optional radio)
5624 "Return a list of all targets in this file.
5625 With optional argument RADIO, only find radio targets."
5626 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5627 rtn)
5628 (save-excursion
5629 (goto-char (point-min))
5630 (while (re-search-forward re nil t)
5631 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5632 rtn)))
5634 (defun org-make-target-link-regexp (targets)
5635 "Make regular expression matching all strings in TARGETS.
5636 The regular expression finds the targets also if there is a line break
5637 between words."
5638 (and targets
5639 (concat
5640 "\\<\\("
5641 (mapconcat
5642 (lambda (x)
5643 (while (string-match " +" x)
5644 (setq x (replace-match "\\s-+" t t x)))
5646 targets
5647 "\\|")
5648 "\\)\\>")))
5650 (defun org-activate-tags (limit)
5651 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5652 (progn
5653 (add-text-properties (match-beginning 1) (match-end 1)
5654 (list 'mouse-face 'highlight
5655 'rear-nonsticky org-nonsticky-props
5656 'keymap org-mouse-map))
5657 t)))
5659 (defun org-outline-level ()
5660 (save-excursion
5661 (looking-at outline-regexp)
5662 (if (match-beginning 1)
5663 (+ (org-get-string-indentation (match-string 1)) 1000)
5664 (1- (- (match-end 0) (match-beginning 0))))))
5666 (defvar org-font-lock-keywords nil)
5668 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
5669 "Regular expression matching a property line.")
5671 (defun org-set-font-lock-defaults ()
5672 (let* ((em org-fontify-emphasized-text)
5673 (lk org-activate-links)
5674 (org-font-lock-extra-keywords
5675 (list
5676 ;; Headlines
5677 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
5678 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
5679 ;; Table lines
5680 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5681 (1 'org-table t))
5682 ;; Table internals
5683 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5684 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5685 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5686 ;; Drawers
5687 (list org-drawer-regexp '(0 'org-special-keyword t))
5688 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5689 ;; Properties
5690 (list org-property-re
5691 '(1 'org-special-keyword t)
5692 '(3 'org-property-value t))
5693 (if org-format-transports-properties-p
5694 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
5695 ;; Links
5696 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5697 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5698 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
5699 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5700 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5701 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5702 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5703 '(org-hide-wide-columns (0 nil append))
5704 ;; TODO lines
5705 (list (concat "^\\*+[ \t]+" org-todo-regexp)
5706 '(1 (org-get-todo-face 1) t))
5707 ;; DONE
5708 (if org-fontify-done-headline
5709 (list (concat "^[*]+ +\\<\\("
5710 (mapconcat 'regexp-quote org-done-keywords "\\|")
5711 "\\)\\(.*\\)")
5712 '(2 'org-headline-done t))
5713 nil)
5714 ;; Priorities
5715 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
5716 ;; Special keywords
5717 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5718 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5719 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5720 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5721 ;; Emphasis
5722 (if em
5723 (if (featurep 'xemacs)
5724 '(org-do-emphasis-faces (0 nil append))
5725 '(org-do-emphasis-faces)))
5726 ;; Checkboxes
5727 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5728 2 'bold prepend)
5729 (if org-provide-checkbox-statistics
5730 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5731 (0 (org-get-checkbox-statistics-face) t)))
5732 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5733 '(1 'org-archived prepend))
5734 ;; Specials
5735 '(org-do-latex-and-special-faces)
5736 ;; Code
5737 '(org-activate-code (1 'org-code t))
5738 ;; COMMENT
5739 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5740 "\\|" org-quote-string "\\)\\>")
5741 '(1 'org-special-keyword t))
5742 '("^#.*" (0 'font-lock-comment-face t))
5744 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5745 ;; Now set the full font-lock-keywords
5746 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5747 (org-set-local 'font-lock-defaults
5748 '(org-font-lock-keywords t nil nil backward-paragraph))
5749 (kill-local-variable 'font-lock-keywords) nil))
5751 (defvar org-m nil)
5752 (defvar org-l nil)
5753 (defvar org-f nil)
5754 (defun org-get-level-face (n)
5755 "Get the right face for match N in font-lock matching of healdines."
5756 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5757 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5758 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5759 (cond
5760 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5761 ((eq n 2) org-f)
5762 (t (if org-level-color-stars-only nil org-f))))
5764 (defun org-get-todo-face (kwd)
5765 "Get the right face for a TODO keyword KWD.
5766 If KWD is a number, get the corresponding match group."
5767 (if (numberp kwd) (setq kwd (match-string kwd)))
5768 (or (cdr (assoc kwd org-todo-keyword-faces))
5769 (and (member kwd org-done-keywords) 'org-done)
5770 'org-todo))
5772 (defun org-unfontify-region (beg end &optional maybe_loudly)
5773 "Remove fontification and activation overlays from links."
5774 (font-lock-default-unfontify-region beg end)
5775 (let* ((buffer-undo-list t)
5776 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5777 (inhibit-modification-hooks t)
5778 deactivate-mark buffer-file-name buffer-file-truename)
5779 (remove-text-properties beg end
5780 '(mouse-face t keymap t org-linked-text t
5781 invisible t intangible t))))
5783 ;;;; Visibility cycling, including org-goto and indirect buffer
5785 ;;; Cycling
5787 (defvar org-cycle-global-status nil)
5788 (make-variable-buffer-local 'org-cycle-global-status)
5789 (defvar org-cycle-subtree-status nil)
5790 (make-variable-buffer-local 'org-cycle-subtree-status)
5792 ;;;###autoload
5793 (defun org-cycle (&optional arg)
5794 "Visibility cycling for Org-mode.
5796 - When this function is called with a prefix argument, rotate the entire
5797 buffer through 3 states (global cycling)
5798 1. OVERVIEW: Show only top-level headlines.
5799 2. CONTENTS: Show all headlines of all levels, but no body text.
5800 3. SHOW ALL: Show everything.
5802 - When point is at the beginning of a headline, rotate the subtree started
5803 by this line through 3 different states (local cycling)
5804 1. FOLDED: Only the main headline is shown.
5805 2. CHILDREN: The main headline and the direct children are shown.
5806 From this state, you can move to one of the children
5807 and zoom in further.
5808 3. SUBTREE: Show the entire subtree, including body text.
5810 - When there is a numeric prefix, go up to a heading with level ARG, do
5811 a `show-subtree' and return to the previous cursor position. If ARG
5812 is negative, go up that many levels.
5814 - When point is not at the beginning of a headline, execute
5815 `indent-relative', like TAB normally does. See the option
5816 `org-cycle-emulate-tab' for details.
5818 - Special case: if point is at the beginning of the buffer and there is
5819 no headline in line 1, this function will act as if called with prefix arg.
5820 But only if also the variable `org-cycle-global-at-bob' is t."
5821 (interactive "P")
5822 (let* ((outline-regexp
5823 (if (and (org-mode-p) org-cycle-include-plain-lists)
5824 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
5825 outline-regexp))
5826 (bob-special (and org-cycle-global-at-bob (bobp)
5827 (not (looking-at outline-regexp))))
5828 (org-cycle-hook
5829 (if bob-special
5830 (delq 'org-optimize-window-after-visibility-change
5831 (copy-sequence org-cycle-hook))
5832 org-cycle-hook))
5833 (pos (point)))
5835 (if (or bob-special (equal arg '(4)))
5836 ;; special case: use global cycling
5837 (setq arg t))
5839 (cond
5841 ((org-at-table-p 'any)
5842 ;; Enter the table or move to the next field in the table
5843 (or (org-table-recognize-table.el)
5844 (progn
5845 (if arg (org-table-edit-field t)
5846 (org-table-justify-field-maybe)
5847 (call-interactively 'org-table-next-field)))))
5849 ((eq arg t) ;; Global cycling
5851 (cond
5852 ((and (eq last-command this-command)
5853 (eq org-cycle-global-status 'overview))
5854 ;; We just created the overview - now do table of contents
5855 ;; This can be slow in very large buffers, so indicate action
5856 (message "CONTENTS...")
5857 (org-content)
5858 (message "CONTENTS...done")
5859 (setq org-cycle-global-status 'contents)
5860 (run-hook-with-args 'org-cycle-hook 'contents))
5862 ((and (eq last-command this-command)
5863 (eq org-cycle-global-status 'contents))
5864 ;; We just showed the table of contents - now show everything
5865 (show-all)
5866 (message "SHOW ALL")
5867 (setq org-cycle-global-status 'all)
5868 (run-hook-with-args 'org-cycle-hook 'all))
5871 ;; Default action: go to overview
5872 (org-overview)
5873 (message "OVERVIEW")
5874 (setq org-cycle-global-status 'overview)
5875 (run-hook-with-args 'org-cycle-hook 'overview))))
5877 ((and org-drawers org-drawer-regexp
5878 (save-excursion
5879 (beginning-of-line 1)
5880 (looking-at org-drawer-regexp)))
5881 ;; Toggle block visibility
5882 (org-flag-drawer
5883 (not (get-char-property (match-end 0) 'invisible))))
5885 ((integerp arg)
5886 ;; Show-subtree, ARG levels up from here.
5887 (save-excursion
5888 (org-back-to-heading)
5889 (outline-up-heading (if (< arg 0) (- arg)
5890 (- (funcall outline-level) arg)))
5891 (org-show-subtree)))
5893 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5894 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5895 ;; At a heading: rotate between three different views
5896 (org-back-to-heading)
5897 (let ((goal-column 0) eoh eol eos)
5898 ;; First, some boundaries
5899 (save-excursion
5900 (org-back-to-heading)
5901 (save-excursion
5902 (beginning-of-line 2)
5903 (while (and (not (eobp)) ;; this is like `next-line'
5904 (get-char-property (1- (point)) 'invisible))
5905 (beginning-of-line 2)) (setq eol (point)))
5906 (outline-end-of-heading) (setq eoh (point))
5907 (org-end-of-subtree t)
5908 (unless (eobp)
5909 (skip-chars-forward " \t\n")
5910 (beginning-of-line 1) ; in case this is an item
5912 (setq eos (1- (point))))
5913 ;; Find out what to do next and set `this-command'
5914 (cond
5915 ((= eos eoh)
5916 ;; Nothing is hidden behind this heading
5917 (message "EMPTY ENTRY")
5918 (setq org-cycle-subtree-status nil)
5919 (save-excursion
5920 (goto-char eos)
5921 (outline-next-heading)
5922 (if (org-invisible-p) (org-flag-heading nil))))
5923 ((or (>= eol eos)
5924 (not (string-match "\\S-" (buffer-substring eol eos))))
5925 ;; Entire subtree is hidden in one line: open it
5926 (org-show-entry)
5927 (show-children)
5928 (message "CHILDREN")
5929 (save-excursion
5930 (goto-char eos)
5931 (outline-next-heading)
5932 (if (org-invisible-p) (org-flag-heading nil)))
5933 (setq org-cycle-subtree-status 'children)
5934 (run-hook-with-args 'org-cycle-hook 'children))
5935 ((and (eq last-command this-command)
5936 (eq org-cycle-subtree-status 'children))
5937 ;; We just showed the children, now show everything.
5938 (org-show-subtree)
5939 (message "SUBTREE")
5940 (setq org-cycle-subtree-status 'subtree)
5941 (run-hook-with-args 'org-cycle-hook 'subtree))
5943 ;; Default action: hide the subtree.
5944 (hide-subtree)
5945 (message "FOLDED")
5946 (setq org-cycle-subtree-status 'folded)
5947 (run-hook-with-args 'org-cycle-hook 'folded)))))
5949 ;; TAB emulation
5950 (buffer-read-only (org-back-to-heading))
5952 ((org-try-cdlatex-tab))
5954 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5955 (or (not (bolp))
5956 (not (looking-at outline-regexp))))
5957 (call-interactively (global-key-binding "\t")))
5959 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5960 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5961 (or (and (eq org-cycle-emulate-tab 'white)
5962 (= (match-end 0) (point-at-eol)))
5963 (and (eq org-cycle-emulate-tab 'whitestart)
5964 (>= (match-end 0) pos))))
5966 (eq org-cycle-emulate-tab t))
5967 ; (if (and (looking-at "[ \n\r\t]")
5968 ; (string-match "^[ \t]*$" (buffer-substring
5969 ; (point-at-bol) (point))))
5970 ; (progn
5971 ; (beginning-of-line 1)
5972 ; (and (looking-at "[ \t]+") (replace-match ""))))
5973 (call-interactively (global-key-binding "\t")))
5975 (t (save-excursion
5976 (org-back-to-heading)
5977 (org-cycle))))))
5979 ;;;###autoload
5980 (defun org-global-cycle (&optional arg)
5981 "Cycle the global visibility. For details see `org-cycle'."
5982 (interactive "P")
5983 (let ((org-cycle-include-plain-lists
5984 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5985 (if (integerp arg)
5986 (progn
5987 (show-all)
5988 (hide-sublevels arg)
5989 (setq org-cycle-global-status 'contents))
5990 (org-cycle '(4)))))
5992 (defun org-overview ()
5993 "Switch to overview mode, shoing only top-level headlines.
5994 Really, this shows all headlines with level equal or greater than the level
5995 of the first headline in the buffer. This is important, because if the
5996 first headline is not level one, then (hide-sublevels 1) gives confusing
5997 results."
5998 (interactive)
5999 (let ((level (save-excursion
6000 (goto-char (point-min))
6001 (if (re-search-forward (concat "^" outline-regexp) nil t)
6002 (progn
6003 (goto-char (match-beginning 0))
6004 (funcall outline-level))))))
6005 (and level (hide-sublevels level))))
6007 (defun org-content (&optional arg)
6008 "Show all headlines in the buffer, like a table of contents.
6009 With numerical argument N, show content up to level N."
6010 (interactive "P")
6011 (save-excursion
6012 ;; Visit all headings and show their offspring
6013 (and (integerp arg) (org-overview))
6014 (goto-char (point-max))
6015 (catch 'exit
6016 (while (and (progn (condition-case nil
6017 (outline-previous-visible-heading 1)
6018 (error (goto-char (point-min))))
6020 (looking-at outline-regexp))
6021 (if (integerp arg)
6022 (show-children (1- arg))
6023 (show-branches))
6024 (if (bobp) (throw 'exit nil))))))
6027 (defun org-optimize-window-after-visibility-change (state)
6028 "Adjust the window after a change in outline visibility.
6029 This function is the default value of the hook `org-cycle-hook'."
6030 (when (get-buffer-window (current-buffer))
6031 (cond
6032 ; ((eq state 'overview) (org-first-headline-recenter 1))
6033 ; ((eq state 'overview) (org-beginning-of-line))
6034 ((eq state 'content) nil)
6035 ((eq state 'all) nil)
6036 ((eq state 'folded) nil)
6037 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6038 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6040 (defun org-compact-display-after-subtree-move ()
6041 (let (beg end)
6042 (save-excursion
6043 (if (org-up-heading-safe)
6044 (progn
6045 (hide-subtree)
6046 (show-entry)
6047 (show-children)
6048 (org-cycle-show-empty-lines 'children)
6049 (org-cycle-hide-drawers 'children))
6050 (org-overview)))))
6052 (defun org-cycle-show-empty-lines (state)
6053 "Show empty lines above all visible headlines.
6054 The region to be covered depends on STATE when called through
6055 `org-cycle-hook'. Lisp program can use t for STATE to get the
6056 entire buffer covered. Note that an empty line is only shown if there
6057 are at least `org-cycle-separator-lines' empty lines before the headeline."
6058 (when (> org-cycle-separator-lines 0)
6059 (save-excursion
6060 (let* ((n org-cycle-separator-lines)
6061 (re (cond
6062 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
6063 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
6064 (t (let ((ns (number-to-string (- n 2))))
6065 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
6066 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
6067 beg end)
6068 (cond
6069 ((memq state '(overview contents t))
6070 (setq beg (point-min) end (point-max)))
6071 ((memq state '(children folded))
6072 (setq beg (point) end (progn (org-end-of-subtree t t)
6073 (beginning-of-line 2)
6074 (point)))))
6075 (when beg
6076 (goto-char beg)
6077 (while (re-search-forward re end t)
6078 (if (not (get-char-property (match-end 1) 'invisible))
6079 (outline-flag-region
6080 (match-beginning 1) (match-end 1) nil)))))))
6081 ;; Never hide empty lines at the end of the file.
6082 (save-excursion
6083 (goto-char (point-max))
6084 (outline-previous-heading)
6085 (outline-end-of-heading)
6086 (if (and (looking-at "[ \t\n]+")
6087 (= (match-end 0) (point-max)))
6088 (outline-flag-region (point) (match-end 0) nil))))
6090 (defun org-subtree-end-visible-p ()
6091 "Is the end of the current subtree visible?"
6092 (pos-visible-in-window-p
6093 (save-excursion (org-end-of-subtree t) (point))))
6095 (defun org-first-headline-recenter (&optional N)
6096 "Move cursor to the first headline and recenter the headline.
6097 Optional argument N means, put the headline into the Nth line of the window."
6098 (goto-char (point-min))
6099 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
6100 (beginning-of-line)
6101 (recenter (prefix-numeric-value N))))
6103 ;;; Org-goto
6105 (defvar org-goto-window-configuration nil)
6106 (defvar org-goto-marker nil)
6107 (defvar org-goto-map
6108 (let ((map (make-sparse-keymap)))
6109 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
6110 (while (setq cmd (pop cmds))
6111 (substitute-key-definition cmd cmd map global-map)))
6112 (suppress-keymap map)
6113 (org-defkey map "\C-m" 'org-goto-ret)
6114 (org-defkey map [(return)] 'org-goto-ret)
6115 (org-defkey map [(left)] 'org-goto-left)
6116 (org-defkey map [(right)] 'org-goto-right)
6117 (org-defkey map [(control ?g)] 'org-goto-quit)
6118 (org-defkey map "\C-i" 'org-cycle)
6119 (org-defkey map [(tab)] 'org-cycle)
6120 (org-defkey map [(down)] 'outline-next-visible-heading)
6121 (org-defkey map [(up)] 'outline-previous-visible-heading)
6122 (if org-goto-auto-isearch
6123 (if (fboundp 'define-key-after)
6124 (define-key-after map [t] 'org-goto-local-auto-isearch)
6125 nil)
6126 (org-defkey map "q" 'org-goto-quit)
6127 (org-defkey map "n" 'outline-next-visible-heading)
6128 (org-defkey map "p" 'outline-previous-visible-heading)
6129 (org-defkey map "f" 'outline-forward-same-level)
6130 (org-defkey map "b" 'outline-backward-same-level)
6131 (org-defkey map "u" 'outline-up-heading))
6132 (org-defkey map "/" 'org-occur)
6133 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
6134 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
6135 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
6136 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
6137 (org-defkey map "\C-c\C-u" 'outline-up-heading)
6138 map))
6140 (defconst org-goto-help
6141 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
6142 RET=jump to location [Q]uit and return to previous location
6143 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
6145 (defvar org-goto-start-pos) ; dynamically scoped parameter
6147 (defun org-goto (&optional alternative-interface)
6148 "Look up a different location in the current file, keeping current visibility.
6150 When you want look-up or go to a different location in a document, the
6151 fastest way is often to fold the entire buffer and then dive into the tree.
6152 This method has the disadvantage, that the previous location will be folded,
6153 which may not be what you want.
6155 This command works around this by showing a copy of the current buffer
6156 in an indirect buffer, in overview mode. You can dive into the tree in
6157 that copy, use org-occur and incremental search to find a location.
6158 When pressing RET or `Q', the command returns to the original buffer in
6159 which the visibility is still unchanged. After RET is will also jump to
6160 the location selected in the indirect buffer and expose the
6161 the headline hierarchy above."
6162 (interactive "P")
6163 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
6164 (org-refile-use-outline-path t)
6165 (interface
6166 (if (not alternative-interface)
6167 org-goto-interface
6168 (if (eq org-goto-interface 'outline)
6169 'outline-path-completion
6170 'outline)))
6171 (org-goto-start-pos (point))
6172 (selected-point
6173 (if (eq interface 'outline)
6174 (car (org-get-location (current-buffer) org-goto-help))
6175 (nth 3 (org-refile-get-location "Goto: ")))))
6176 (if selected-point
6177 (progn
6178 (org-mark-ring-push org-goto-start-pos)
6179 (goto-char selected-point)
6180 (if (or (org-invisible-p) (org-invisible-p2))
6181 (org-show-context 'org-goto)))
6182 (message "Quit"))))
6184 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6185 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6186 (defvar org-goto-local-auto-isearch-map) ; defined below
6188 (defun org-get-location (buf help)
6189 "Let the user select a location in the Org-mode buffer BUF.
6190 This function uses a recursive edit. It returns the selected position
6191 or nil."
6192 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6193 (isearch-hide-immediately nil)
6194 (isearch-search-fun-function
6195 (lambda () 'org-goto-local-search-forward-headings))
6196 (org-goto-selected-point org-goto-exit-command))
6197 (save-excursion
6198 (save-window-excursion
6199 (delete-other-windows)
6200 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6201 (switch-to-buffer
6202 (condition-case nil
6203 (make-indirect-buffer (current-buffer) "*org-goto*")
6204 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6205 (with-output-to-temp-buffer "*Help*"
6206 (princ help))
6207 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
6208 (setq buffer-read-only nil)
6209 (let ((org-startup-truncated t)
6210 (org-startup-folded nil)
6211 (org-startup-align-all-tables nil))
6212 (org-mode)
6213 (org-overview))
6214 (setq buffer-read-only t)
6215 (if (and (boundp 'org-goto-start-pos)
6216 (integer-or-marker-p org-goto-start-pos))
6217 (let ((org-show-hierarchy-above t)
6218 (org-show-siblings t)
6219 (org-show-following-heading t))
6220 (goto-char org-goto-start-pos)
6221 (and (org-invisible-p) (org-show-context)))
6222 (goto-char (point-min)))
6223 (org-beginning-of-line)
6224 (message "Select location and press RET")
6225 (use-local-map org-goto-map)
6226 (recursive-edit)
6228 (kill-buffer "*org-goto*")
6229 (cons org-goto-selected-point org-goto-exit-command)))
6231 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6232 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6233 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6234 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6236 (defun org-goto-local-search-forward-headings (string bound noerror)
6237 "Search and make sure that anu matches are in headlines."
6238 (catch 'return
6239 (while (search-forward string bound noerror)
6240 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6241 (and (member :headline context)
6242 (not (member :tags context))))
6243 (throw 'return (point))))))
6245 (defun org-goto-local-auto-isearch ()
6246 "Start isearch."
6247 (interactive)
6248 (goto-char (point-min))
6249 (let ((keys (this-command-keys)))
6250 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6251 (isearch-mode t)
6252 (isearch-process-search-char (string-to-char keys)))))
6254 (defun org-goto-ret (&optional arg)
6255 "Finish `org-goto' by going to the new location."
6256 (interactive "P")
6257 (setq org-goto-selected-point (point)
6258 org-goto-exit-command 'return)
6259 (throw 'exit nil))
6261 (defun org-goto-left ()
6262 "Finish `org-goto' by going to the new location."
6263 (interactive)
6264 (if (org-on-heading-p)
6265 (progn
6266 (beginning-of-line 1)
6267 (setq org-goto-selected-point (point)
6268 org-goto-exit-command 'left)
6269 (throw 'exit nil))
6270 (error "Not on a heading")))
6272 (defun org-goto-right ()
6273 "Finish `org-goto' by going to the new location."
6274 (interactive)
6275 (if (org-on-heading-p)
6276 (progn
6277 (setq org-goto-selected-point (point)
6278 org-goto-exit-command 'right)
6279 (throw 'exit nil))
6280 (error "Not on a heading")))
6282 (defun org-goto-quit ()
6283 "Finish `org-goto' without cursor motion."
6284 (interactive)
6285 (setq org-goto-selected-point nil)
6286 (setq org-goto-exit-command 'quit)
6287 (throw 'exit nil))
6289 ;;; Indirect buffer display of subtrees
6291 (defvar org-indirect-dedicated-frame nil
6292 "This is the frame being used for indirect tree display.")
6293 (defvar org-last-indirect-buffer nil)
6295 (defun org-tree-to-indirect-buffer (&optional arg)
6296 "Create indirect buffer and narrow it to current subtree.
6297 With numerical prefix ARG, go up to this level and then take that tree.
6298 If ARG is negative, go up that many levels.
6299 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6300 indirect buffer previously made with this command, to avoid proliferation of
6301 indirect buffers. However, when you call the command with a `C-u' prefix, or
6302 when `org-indirect-buffer-display' is `new-frame', the last buffer
6303 is kept so that you can work with several indirect buffers at the same time.
6304 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6305 requests that a new frame be made for the new buffer, so that the dedicated
6306 frame is not changed."
6307 (interactive "P")
6308 (let ((cbuf (current-buffer))
6309 (cwin (selected-window))
6310 (pos (point))
6311 beg end level heading ibuf)
6312 (save-excursion
6313 (org-back-to-heading t)
6314 (when (numberp arg)
6315 (setq level (org-outline-level))
6316 (if (< arg 0) (setq arg (+ level arg)))
6317 (while (> (setq level (org-outline-level)) arg)
6318 (outline-up-heading 1 t)))
6319 (setq beg (point)
6320 heading (org-get-heading))
6321 (org-end-of-subtree t) (setq end (point)))
6322 (if (and (buffer-live-p org-last-indirect-buffer)
6323 (not (eq org-indirect-buffer-display 'new-frame))
6324 (not arg))
6325 (kill-buffer org-last-indirect-buffer))
6326 (setq ibuf (org-get-indirect-buffer cbuf)
6327 org-last-indirect-buffer ibuf)
6328 (cond
6329 ((or (eq org-indirect-buffer-display 'new-frame)
6330 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6331 (select-frame (make-frame))
6332 (delete-other-windows)
6333 (switch-to-buffer ibuf)
6334 (org-set-frame-title heading))
6335 ((eq org-indirect-buffer-display 'dedicated-frame)
6336 (raise-frame
6337 (select-frame (or (and org-indirect-dedicated-frame
6338 (frame-live-p org-indirect-dedicated-frame)
6339 org-indirect-dedicated-frame)
6340 (setq org-indirect-dedicated-frame (make-frame)))))
6341 (delete-other-windows)
6342 (switch-to-buffer ibuf)
6343 (org-set-frame-title (concat "Indirect: " heading)))
6344 ((eq org-indirect-buffer-display 'current-window)
6345 (switch-to-buffer ibuf))
6346 ((eq org-indirect-buffer-display 'other-window)
6347 (pop-to-buffer ibuf))
6348 (t (error "Invalid value.")))
6349 (if (featurep 'xemacs)
6350 (save-excursion (org-mode) (turn-on-font-lock)))
6351 (narrow-to-region beg end)
6352 (show-all)
6353 (goto-char pos)
6354 (and (window-live-p cwin) (select-window cwin))))
6356 (defun org-get-indirect-buffer (&optional buffer)
6357 (setq buffer (or buffer (current-buffer)))
6358 (let ((n 1) (base (buffer-name buffer)) bname)
6359 (while (buffer-live-p
6360 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6361 (setq n (1+ n)))
6362 (condition-case nil
6363 (make-indirect-buffer buffer bname 'clone)
6364 (error (make-indirect-buffer buffer bname)))))
6366 (defun org-set-frame-title (title)
6367 "Set the title of the current frame to the string TITLE."
6368 ;; FIXME: how to name a single frame in XEmacs???
6369 (unless (featurep 'xemacs)
6370 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6372 ;;;; Structure editing
6374 ;;; Inserting headlines
6376 (defun org-insert-heading (&optional force-heading)
6377 "Insert a new heading or item with same depth at point.
6378 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6379 If point is at the beginning of a headline, insert a sibling before the
6380 current headline. If point is not at the beginning, do not split the line,
6381 but create the new hedline after the current line."
6382 (interactive "P")
6383 (if (= (buffer-size) 0)
6384 (insert "\n* ")
6385 (when (or force-heading (not (org-insert-item)))
6386 (let* ((head (save-excursion
6387 (condition-case nil
6388 (progn
6389 (org-back-to-heading)
6390 (match-string 0))
6391 (error "*"))))
6392 (blank (cdr (assq 'heading org-blank-before-new-entry)))
6393 pos)
6394 (cond
6395 ((and (org-on-heading-p) (bolp)
6396 (or (bobp)
6397 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6398 ;; insert before the current line
6399 (open-line (if blank 2 1)))
6400 ((and (bolp)
6401 (or (bobp)
6402 (save-excursion
6403 (backward-char 1) (not (org-invisible-p)))))
6404 ;; insert right here
6405 nil)
6407 ; ;; in the middle of the line
6408 ; (org-show-entry)
6409 ; (if (org-get-alist-option org-M-RET-may-split-line 'headline)
6410 ; (if (and
6411 ; (org-on-heading-p)
6412 ; (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \r\n]"))
6413 ; ;; protect the tags
6414 ;; (let ((tags (match-string 2)) pos)
6415 ; (delete-region (match-beginning 1) (match-end 1))
6416 ; (setq pos (point-at-bol))
6417 ; (newline (if blank 2 1))
6418 ; (save-excursion
6419 ; (goto-char pos)
6420 ; (end-of-line 1)
6421 ; (insert " " tags)
6422 ; (org-set-tags nil 'align)))
6423 ; (newline (if blank 2 1)))
6424 ; (newline (if blank 2 1))))
6427 ;; in the middle of the line
6428 (org-show-entry)
6429 (let ((split
6430 (org-get-alist-option org-M-RET-may-split-line 'headline))
6431 tags pos)
6432 (if (org-on-heading-p)
6433 (progn
6434 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6435 (setq tags (and (match-end 2) (match-string 2)))
6436 (and (match-end 1)
6437 (delete-region (match-beginning 1) (match-end 1)))
6438 (setq pos (point-at-bol))
6439 (or split (end-of-line 1))
6440 (delete-horizontal-space)
6441 (newline (if blank 2 1))
6442 (when tags
6443 (save-excursion
6444 (goto-char pos)
6445 (end-of-line 1)
6446 (insert " " tags)
6447 (org-set-tags nil 'align))))
6448 (or split (end-of-line 1))
6449 (newline (if blank 2 1))))))
6450 (insert head) (just-one-space)
6451 (setq pos (point))
6452 (end-of-line 1)
6453 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6454 (run-hooks 'org-insert-heading-hook)))))
6456 (defun org-insert-heading-after-current ()
6457 "Insert a new heading with same level as current, after current subtree."
6458 (interactive)
6459 (org-back-to-heading)
6460 (org-insert-heading)
6461 (org-move-subtree-down)
6462 (end-of-line 1))
6464 (defun org-insert-todo-heading (arg)
6465 "Insert a new heading with the same level and TODO state as current heading.
6466 If the heading has no TODO state, or if the state is DONE, use the first
6467 state (TODO by default). Also with prefix arg, force first state."
6468 (interactive "P")
6469 (when (not (org-insert-item 'checkbox))
6470 (org-insert-heading)
6471 (save-excursion
6472 (org-back-to-heading)
6473 (outline-previous-heading)
6474 (looking-at org-todo-line-regexp))
6475 (if (or arg
6476 (not (match-beginning 2))
6477 (member (match-string 2) org-done-keywords))
6478 (insert (car org-todo-keywords-1) " ")
6479 (insert (match-string 2) " "))))
6481 (defun org-insert-subheading (arg)
6482 "Insert a new subheading and demote it.
6483 Works for outline headings and for plain lists alike."
6484 (interactive "P")
6485 (org-insert-heading arg)
6486 (cond
6487 ((org-on-heading-p) (org-do-demote))
6488 ((org-at-item-p) (org-indent-item 1))))
6490 (defun org-insert-todo-subheading (arg)
6491 "Insert a new subheading with TODO keyword or checkbox and demote it.
6492 Works for outline headings and for plain lists alike."
6493 (interactive "P")
6494 (org-insert-todo-heading arg)
6495 (cond
6496 ((org-on-heading-p) (org-do-demote))
6497 ((org-at-item-p) (org-indent-item 1))))
6499 ;;; Promotion and Demotion
6501 (defun org-promote-subtree ()
6502 "Promote the entire subtree.
6503 See also `org-promote'."
6504 (interactive)
6505 (save-excursion
6506 (org-map-tree 'org-promote))
6507 (org-fix-position-after-promote))
6509 (defun org-demote-subtree ()
6510 "Demote the entire subtree. See `org-demote'.
6511 See also `org-promote'."
6512 (interactive)
6513 (save-excursion
6514 (org-map-tree 'org-demote))
6515 (org-fix-position-after-promote))
6518 (defun org-do-promote ()
6519 "Promote the current heading higher up the tree.
6520 If the region is active in `transient-mark-mode', promote all headings
6521 in the region."
6522 (interactive)
6523 (save-excursion
6524 (if (org-region-active-p)
6525 (org-map-region 'org-promote (region-beginning) (region-end))
6526 (org-promote)))
6527 (org-fix-position-after-promote))
6529 (defun org-do-demote ()
6530 "Demote the current heading lower down the tree.
6531 If the region is active in `transient-mark-mode', demote all headings
6532 in the region."
6533 (interactive)
6534 (save-excursion
6535 (if (org-region-active-p)
6536 (org-map-region 'org-demote (region-beginning) (region-end))
6537 (org-demote)))
6538 (org-fix-position-after-promote))
6540 (defun org-fix-position-after-promote ()
6541 "Make sure that after pro/demotion cursor position is right."
6542 (let ((pos (point)))
6543 (when (save-excursion
6544 (beginning-of-line 1)
6545 (looking-at org-todo-line-regexp)
6546 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6547 (cond ((eobp) (insert " "))
6548 ((eolp) (insert " "))
6549 ((equal (char-after) ?\ ) (forward-char 1))))))
6551 (defun org-reduced-level (l)
6552 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6554 (defun org-get-valid-level (level &optional change)
6555 "Rectify a level change under the influence of `org-odd-levels-only'
6556 LEVEL is a current level, CHANGE is by how much the level should be
6557 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6558 even level numbers will become the next higher odd number."
6559 (if org-odd-levels-only
6560 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6561 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6562 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6563 (max 1 (+ level change))))
6565 (define-obsolete-function-alias 'org-get-legal-level
6566 'org-get-valid-level "23.1")
6568 (defun org-promote ()
6569 "Promote the current heading higher up the tree.
6570 If the region is active in `transient-mark-mode', promote all headings
6571 in the region."
6572 (org-back-to-heading t)
6573 (let* ((level (save-match-data (funcall outline-level)))
6574 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6575 (diff (abs (- level (length up-head) -1))))
6576 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6577 (replace-match up-head nil t)
6578 ;; Fixup tag positioning
6579 (and org-auto-align-tags (org-set-tags nil t))
6580 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
6582 (defun org-demote ()
6583 "Demote the current heading lower down the tree.
6584 If the region is active in `transient-mark-mode', demote all headings
6585 in the region."
6586 (org-back-to-heading t)
6587 (let* ((level (save-match-data (funcall outline-level)))
6588 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6589 (diff (abs (- level (length down-head) -1))))
6590 (replace-match down-head nil t)
6591 ;; Fixup tag positioning
6592 (and org-auto-align-tags (org-set-tags nil t))
6593 (if org-adapt-indentation (org-fixup-indentation diff))))
6595 (defun org-map-tree (fun)
6596 "Call FUN for every heading underneath the current one."
6597 (org-back-to-heading)
6598 (let ((level (funcall outline-level)))
6599 (save-excursion
6600 (funcall fun)
6601 (while (and (progn
6602 (outline-next-heading)
6603 (> (funcall outline-level) level))
6604 (not (eobp)))
6605 (funcall fun)))))
6607 (defun org-map-region (fun beg end)
6608 "Call FUN for every heading between BEG and END."
6609 (let ((org-ignore-region t))
6610 (save-excursion
6611 (setq end (copy-marker end))
6612 (goto-char beg)
6613 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6614 (< (point) end))
6615 (funcall fun))
6616 (while (and (progn
6617 (outline-next-heading)
6618 (< (point) end))
6619 (not (eobp)))
6620 (funcall fun)))))
6622 (defun org-fixup-indentation (diff)
6623 "Change the indentation in the current entry by DIFF
6624 However, if any line in the current entry has no indentation, or if it
6625 would end up with no indentation after the change, nothing at all is done."
6626 (save-excursion
6627 (let ((end (save-excursion (outline-next-heading)
6628 (point-marker)))
6629 (prohibit (if (> diff 0)
6630 "^\\S-"
6631 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6632 col)
6633 (unless (save-excursion (end-of-line 1)
6634 (re-search-forward prohibit end t))
6635 (while (and (< (point) end)
6636 (re-search-forward "^[ \t]+" end t))
6637 (goto-char (match-end 0))
6638 (setq col (current-column))
6639 (if (< diff 0) (replace-match ""))
6640 (indent-to (+ diff col))))
6641 (move-marker end nil))))
6643 (defun org-convert-to-odd-levels ()
6644 "Convert an org-mode file with all levels allowed to one with odd levels.
6645 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6646 level 5 etc."
6647 (interactive)
6648 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6649 (let ((org-odd-levels-only nil) n)
6650 (save-excursion
6651 (goto-char (point-min))
6652 (while (re-search-forward "^\\*\\*+ " nil t)
6653 (setq n (- (length (match-string 0)) 2))
6654 (while (>= (setq n (1- n)) 0)
6655 (org-demote))
6656 (end-of-line 1))))))
6659 (defun org-convert-to-oddeven-levels ()
6660 "Convert an org-mode file with only odd levels to one with odd and even levels.
6661 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6662 section with an even level, conversion would destroy the structure of the file. An error
6663 is signaled in this case."
6664 (interactive)
6665 (goto-char (point-min))
6666 ;; First check if there are no even levels
6667 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6668 (org-show-context t)
6669 (error "Not all levels are odd in this file. Conversion not possible."))
6670 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6671 (let ((org-odd-levels-only nil) n)
6672 (save-excursion
6673 (goto-char (point-min))
6674 (while (re-search-forward "^\\*\\*+ " nil t)
6675 (setq n (/ (1- (length (match-string 0))) 2))
6676 (while (>= (setq n (1- n)) 0)
6677 (org-promote))
6678 (end-of-line 1))))))
6680 (defun org-tr-level (n)
6681 "Make N odd if required."
6682 (if org-odd-levels-only (1+ (/ n 2)) n))
6684 ;;; Vertical tree motion, cutting and pasting of subtrees
6686 (defun org-move-subtree-up (&optional arg)
6687 "Move the current subtree up past ARG headlines of the same level."
6688 (interactive "p")
6689 (org-move-subtree-down (- (prefix-numeric-value arg))))
6691 (defun org-move-subtree-down (&optional arg)
6692 "Move the current subtree down past ARG headlines of the same level."
6693 (interactive "p")
6694 (setq arg (prefix-numeric-value arg))
6695 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6696 'outline-get-last-sibling))
6697 (ins-point (make-marker))
6698 (cnt (abs arg))
6699 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6700 ;; Select the tree
6701 (org-back-to-heading)
6702 (setq beg0 (point))
6703 (save-excursion
6704 (setq ne-beg (org-back-over-empty-lines))
6705 (setq beg (point)))
6706 (save-match-data
6707 (save-excursion (outline-end-of-heading)
6708 (setq folded (org-invisible-p)))
6709 (outline-end-of-subtree))
6710 (outline-next-heading)
6711 (setq ne-end (org-back-over-empty-lines))
6712 (setq end (point))
6713 (goto-char beg0)
6714 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6715 ;; include less whitespace
6716 (save-excursion
6717 (goto-char beg)
6718 (forward-line (- ne-beg ne-end))
6719 (setq beg (point))))
6720 ;; Find insertion point, with error handling
6721 (while (> cnt 0)
6722 (or (and (funcall movfunc) (looking-at outline-regexp))
6723 (progn (goto-char beg0)
6724 (error "Cannot move past superior level or buffer limit")))
6725 (setq cnt (1- cnt)))
6726 (if (> arg 0)
6727 ;; Moving forward - still need to move over subtree
6728 (progn (org-end-of-subtree t t)
6729 (save-excursion
6730 (org-back-over-empty-lines)
6731 (or (bolp) (newline)))))
6732 (setq ne-ins (org-back-over-empty-lines))
6733 (move-marker ins-point (point))
6734 (setq txt (buffer-substring beg end))
6735 (delete-region beg end)
6736 (outline-flag-region (1- beg) beg nil)
6737 (outline-flag-region (1- (point)) (point) nil)
6738 (insert txt)
6739 (or (bolp) (insert "\n"))
6740 (setq ins-end (point))
6741 (goto-char ins-point)
6742 (org-skip-whitespace)
6743 (when (and (< arg 0)
6744 (org-first-sibling-p)
6745 (> ne-ins ne-beg))
6746 ;; Move whitespace back to beginning
6747 (save-excursion
6748 (goto-char ins-end)
6749 (let ((kill-whole-line t))
6750 (kill-line (- ne-ins ne-beg)) (point)))
6751 (insert (make-string (- ne-ins ne-beg) ?\n)))
6752 (move-marker ins-point nil)
6753 (org-compact-display-after-subtree-move)
6754 (unless folded
6755 (org-show-entry)
6756 (show-children)
6757 (org-cycle-hide-drawers 'children))))
6759 (defvar org-subtree-clip ""
6760 "Clipboard for cut and paste of subtrees.
6761 This is actually only a copy of the kill, because we use the normal kill
6762 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6764 (defvar org-subtree-clip-folded nil
6765 "Was the last copied subtree folded?
6766 This is used to fold the tree back after pasting.")
6768 (defun org-cut-subtree (&optional n)
6769 "Cut the current subtree into the clipboard.
6770 With prefix arg N, cut this many sequential subtrees.
6771 This is a short-hand for marking the subtree and then cutting it."
6772 (interactive "p")
6773 (org-copy-subtree n 'cut))
6775 (defun org-copy-subtree (&optional n cut)
6776 "Cut the current subtree into the clipboard.
6777 With prefix arg N, cut this many sequential subtrees.
6778 This is a short-hand for marking the subtree and then copying it.
6779 If CUT is non-nil, actually cut the subtree."
6780 (interactive "p")
6781 (let (beg end folded (beg0 (point)))
6782 (if (interactive-p)
6783 (org-back-to-heading nil) ; take what looks like a subtree
6784 (org-back-to-heading t)) ; take what is really there
6785 (org-back-over-empty-lines)
6786 (setq beg (point))
6787 (skip-chars-forward " \t\r\n")
6788 (save-match-data
6789 (save-excursion (outline-end-of-heading)
6790 (setq folded (org-invisible-p)))
6791 (condition-case nil
6792 (outline-forward-same-level (1- n))
6793 (error nil))
6794 (org-end-of-subtree t t))
6795 (org-back-over-empty-lines)
6796 (setq end (point))
6797 (goto-char beg0)
6798 (when (> end beg)
6799 (setq org-subtree-clip-folded folded)
6800 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6801 (setq org-subtree-clip (current-kill 0))
6802 (message "%s: Subtree(s) with %d characters"
6803 (if cut "Cut" "Copied")
6804 (length org-subtree-clip)))))
6806 (defun org-paste-subtree (&optional level tree)
6807 "Paste the clipboard as a subtree, with modification of headline level.
6808 The entire subtree is promoted or demoted in order to match a new headline
6809 level. By default, the new level is derived from the visible headings
6810 before and after the insertion point, and taken to be the inferior headline
6811 level of the two. So if the previous visible heading is level 3 and the
6812 next is level 4 (or vice versa), level 4 will be used for insertion.
6813 This makes sure that the subtree remains an independent subtree and does
6814 not swallow low level entries.
6816 You can also force a different level, either by using a numeric prefix
6817 argument, or by inserting the heading marker by hand. For example, if the
6818 cursor is after \"*****\", then the tree will be shifted to level 5.
6820 If you want to insert the tree as is, just use \\[yank].
6822 If optional TREE is given, use this text instead of the kill ring."
6823 (interactive "P")
6824 (unless (org-kill-is-subtree-p tree)
6825 (error "%s"
6826 (substitute-command-keys
6827 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6828 (let* ((txt (or tree (and kill-ring (current-kill 0))))
6829 (^re (concat "^\\(" outline-regexp "\\)"))
6830 (re (concat "\\(" outline-regexp "\\)"))
6831 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6833 (old-level (if (string-match ^re txt)
6834 (- (match-end 0) (match-beginning 0) 1)
6835 -1))
6836 (force-level (cond (level (prefix-numeric-value level))
6837 ((string-match
6838 ^re_ (buffer-substring (point-at-bol) (point)))
6839 (- (match-end 1) (match-beginning 1)))
6840 (t nil)))
6841 (previous-level (save-excursion
6842 (condition-case nil
6843 (progn
6844 (outline-previous-visible-heading 1)
6845 (if (looking-at re)
6846 (- (match-end 0) (match-beginning 0) 1)
6848 (error 1))))
6849 (next-level (save-excursion
6850 (condition-case nil
6851 (progn
6852 (or (looking-at outline-regexp)
6853 (outline-next-visible-heading 1))
6854 (if (looking-at re)
6855 (- (match-end 0) (match-beginning 0) 1)
6857 (error 1))))
6858 (new-level (or force-level (max previous-level next-level)))
6859 (shift (if (or (= old-level -1)
6860 (= new-level -1)
6861 (= old-level new-level))
6863 (- new-level old-level)))
6864 (delta (if (> shift 0) -1 1))
6865 (func (if (> shift 0) 'org-demote 'org-promote))
6866 (org-odd-levels-only nil)
6867 beg end)
6868 ;; Remove the forced level indicator
6869 (if force-level
6870 (delete-region (point-at-bol) (point)))
6871 ;; Paste
6872 (beginning-of-line 1)
6873 (org-back-over-empty-lines) ;; FIXME: correct fix????
6874 (setq beg (point))
6875 (insert-before-markers txt) ;; FIXME: correct fix????
6876 (unless (string-match "\n\\'" txt) (insert "\n"))
6877 (setq end (point))
6878 (goto-char beg)
6879 (skip-chars-forward " \t\n\r")
6880 (setq beg (point))
6881 ;; Shift if necessary
6882 (unless (= shift 0)
6883 (save-restriction
6884 (narrow-to-region beg end)
6885 (while (not (= shift 0))
6886 (org-map-region func (point-min) (point-max))
6887 (setq shift (+ delta shift)))
6888 (goto-char (point-min))))
6889 (when (interactive-p)
6890 (message "Clipboard pasted as level %d subtree" new-level))
6891 (if (and kill-ring
6892 (eq org-subtree-clip (current-kill 0))
6893 org-subtree-clip-folded)
6894 ;; The tree was folded before it was killed/copied
6895 (hide-subtree))))
6897 (defun org-kill-is-subtree-p (&optional txt)
6898 "Check if the current kill is an outline subtree, or a set of trees.
6899 Returns nil if kill does not start with a headline, or if the first
6900 headline level is not the largest headline level in the tree.
6901 So this will actually accept several entries of equal levels as well,
6902 which is OK for `org-paste-subtree'.
6903 If optional TXT is given, check this string instead of the current kill."
6904 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6905 (start-level (and kill
6906 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6907 org-outline-regexp "\\)")
6908 kill)
6909 (- (match-end 2) (match-beginning 2) 1)))
6910 (re (concat "^" org-outline-regexp))
6911 (start (1+ (match-beginning 2))))
6912 (if (not start-level)
6913 (progn
6914 nil) ;; does not even start with a heading
6915 (catch 'exit
6916 (while (setq start (string-match re kill (1+ start)))
6917 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6918 (throw 'exit nil)))
6919 t))))
6921 (defun org-narrow-to-subtree ()
6922 "Narrow buffer to the current subtree."
6923 (interactive)
6924 (save-excursion
6925 (save-match-data
6926 (narrow-to-region
6927 (progn (org-back-to-heading) (point))
6928 (progn (org-end-of-subtree t t) (point))))))
6931 ;;; Outline Sorting
6933 (defun org-sort (with-case)
6934 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6935 Optional argument WITH-CASE means sort case-sensitively."
6936 (interactive "P")
6937 (if (org-at-table-p)
6938 (org-call-with-arg 'org-table-sort-lines with-case)
6939 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6941 (defvar org-priority-regexp) ; defined later in the file
6943 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
6944 "Sort entries on a certain level of an outline tree.
6945 If there is an active region, the entries in the region are sorted.
6946 Else, if the cursor is before the first entry, sort the top-level items.
6947 Else, the children of the entry at point are sorted.
6949 Sorting can be alphabetically, numerically, and by date/time as given by
6950 the first time stamp in the entry. The command prompts for the sorting
6951 type unless it has been given to the function through the SORTING-TYPE
6952 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6953 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6954 called with point at the beginning of the record. It must return either
6955 a string or a number that should serve as the sorting key for that record.
6957 Comparing entries ignores case by default. However, with an optional argument
6958 WITH-CASE, the sorting considers case as well."
6959 (interactive "P")
6960 (let ((case-func (if with-case 'identity 'downcase))
6961 start beg end stars re re2
6962 txt what tmp plain-list-p)
6963 ;; Find beginning and end of region to sort
6964 (cond
6965 ((org-region-active-p)
6966 ;; we will sort the region
6967 (setq end (region-end)
6968 what "region")
6969 (goto-char (region-beginning))
6970 (if (not (org-on-heading-p)) (outline-next-heading))
6971 (setq start (point)))
6972 ((org-at-item-p)
6973 ;; we will sort this plain list
6974 (org-beginning-of-item-list) (setq start (point))
6975 (org-end-of-item-list) (setq end (point))
6976 (goto-char start)
6977 (setq plain-list-p t
6978 what "plain list"))
6979 ((or (org-on-heading-p)
6980 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6981 ;; we will sort the children of the current headline
6982 (org-back-to-heading)
6983 (setq start (point)
6984 end (progn (org-end-of-subtree t t)
6985 (org-back-over-empty-lines)
6986 (point))
6987 what "children")
6988 (goto-char start)
6989 (show-subtree)
6990 (outline-next-heading))
6992 ;; we will sort the top-level entries in this file
6993 (goto-char (point-min))
6994 (or (org-on-heading-p) (outline-next-heading))
6995 (setq start (point) end (point-max) what "top-level")
6996 (goto-char start)
6997 (show-all)))
6999 (setq beg (point))
7000 (if (>= beg end) (error "Nothing to sort"))
7002 (unless plain-list-p
7003 (looking-at "\\(\\*+\\)")
7004 (setq stars (match-string 1)
7005 re (concat "^" (regexp-quote stars) " +")
7006 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7007 txt (buffer-substring beg end))
7008 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7009 (if (and (not (equal stars "*")) (string-match re2 txt))
7010 (error "Region to sort contains a level above the first entry")))
7012 (unless sorting-type
7013 (message
7014 (if plain-list-p
7015 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7016 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty [f]unc A/N/T/P/F means reversed:")
7017 what)
7018 (setq sorting-type (read-char-exclusive))
7020 (and (= (downcase sorting-type) ?f)
7021 (setq getkey-func
7022 (completing-read "Sort using function: "
7023 obarray 'fboundp t nil nil))
7024 (setq getkey-func (intern getkey-func)))
7026 (and (= (downcase sorting-type) ?r)
7027 (setq property
7028 (completing-read "Property: "
7029 (mapcar 'list (org-buffer-property-keys t))
7030 nil t))))
7032 (message "Sorting entries...")
7034 (save-restriction
7035 (narrow-to-region start end)
7037 (let ((dcst (downcase sorting-type))
7038 (now (current-time)))
7039 (sort-subr
7040 (/= dcst sorting-type)
7041 ;; This function moves to the beginning character of the "record" to
7042 ;; be sorted.
7043 (if plain-list-p
7044 (lambda nil
7045 (if (org-at-item-p) t (goto-char (point-max))))
7046 (lambda nil
7047 (if (re-search-forward re nil t)
7048 (goto-char (match-beginning 0))
7049 (goto-char (point-max)))))
7050 ;; This function moves to the last character of the "record" being
7051 ;; sorted.
7052 (if plain-list-p
7053 'org-end-of-item
7054 (lambda nil
7055 (save-match-data
7056 (condition-case nil
7057 (outline-forward-same-level 1)
7058 (error
7059 (goto-char (point-max)))))))
7061 ;; This function returns the value that gets sorted against.
7062 (if plain-list-p
7063 (lambda nil
7064 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7065 (cond
7066 ((= dcst ?n)
7067 (string-to-number (buffer-substring (match-end 0)
7068 (point-at-eol))))
7069 ((= dcst ?a)
7070 (buffer-substring (match-end 0) (point-at-eol)))
7071 ((= dcst ?t)
7072 (if (re-search-forward org-ts-regexp
7073 (point-at-eol) t)
7074 (org-time-string-to-time (match-string 0))
7075 now))
7076 ((= dcst ?f)
7077 (if getkey-func
7078 (progn
7079 (setq tmp (funcall getkey-func))
7080 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7081 tmp)
7082 (error "Invalid key function `%s'" getkey-func)))
7083 (t (error "Invalid sorting type `%c'" sorting-type)))))
7084 (lambda nil
7085 (cond
7086 ((= dcst ?n)
7087 (if (looking-at outline-regexp)
7088 (string-to-number (buffer-substring (match-end 0)
7089 (point-at-eol)))
7090 nil))
7091 ((= dcst ?a)
7092 (funcall case-func (buffer-substring (point-at-bol)
7093 (point-at-eol))))
7094 ((= dcst ?t)
7095 (if (re-search-forward org-ts-regexp
7096 (save-excursion
7097 (forward-line 2)
7098 (point)) t)
7099 (org-time-string-to-time (match-string 0))
7100 now))
7101 ((= dcst ?p)
7102 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7103 (string-to-char (match-string 2))
7104 org-default-priority))
7105 ((= dcst ?r)
7106 (or (org-entry-get nil property) ""))
7107 ((= dcst ?f)
7108 (if getkey-func
7109 (progn
7110 (setq tmp (funcall getkey-func))
7111 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7112 tmp)
7113 (error "Invalid key function `%s'" getkey-func)))
7114 (t (error "Invalid sorting type `%c'" sorting-type)))))
7116 (cond
7117 ((= dcst ?a) 'string<)
7118 ((= dcst ?t) 'time-less-p)
7119 (t nil)))))
7120 (message "Sorting entries...done")))
7122 (defun org-do-sort (table what &optional with-case sorting-type)
7123 "Sort TABLE of WHAT according to SORTING-TYPE.
7124 The user will be prompted for the SORTING-TYPE if the call to this
7125 function does not specify it. WHAT is only for the prompt, to indicate
7126 what is being sorted. The sorting key will be extracted from
7127 the car of the elements of the table.
7128 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7129 (unless sorting-type
7130 (message
7131 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7132 what)
7133 (setq sorting-type (read-char-exclusive)))
7134 (let ((dcst (downcase sorting-type))
7135 extractfun comparefun)
7136 ;; Define the appropriate functions
7137 (cond
7138 ((= dcst ?n)
7139 (setq extractfun 'string-to-number
7140 comparefun (if (= dcst sorting-type) '< '>)))
7141 ((= dcst ?a)
7142 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7143 (lambda(x) (downcase (org-sort-remove-invisible x))))
7144 comparefun (if (= dcst sorting-type)
7145 'string<
7146 (lambda (a b) (and (not (string< a b))
7147 (not (string= a b)))))))
7148 ((= dcst ?t)
7149 (setq extractfun
7150 (lambda (x)
7151 (if (string-match org-ts-regexp x)
7152 (time-to-seconds
7153 (org-time-string-to-time (match-string 0 x)))
7155 comparefun (if (= dcst sorting-type) '< '>)))
7156 (t (error "Invalid sorting type `%c'" sorting-type)))
7158 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7159 table)
7160 (lambda (a b) (funcall comparefun (car a) (car b))))))
7162 ;;;; Plain list items, including checkboxes
7164 ;;; Plain list items
7166 (defun org-at-item-p ()
7167 "Is point in a line starting a hand-formatted item?"
7168 (let ((llt org-plain-list-ordered-item-terminator))
7169 (save-excursion
7170 (goto-char (point-at-bol))
7171 (looking-at
7172 (cond
7173 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7174 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7175 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
7176 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
7178 (defun org-in-item-p ()
7179 "It the cursor inside a plain list item.
7180 Does not have to be the first line."
7181 (save-excursion
7182 (condition-case nil
7183 (progn
7184 (org-beginning-of-item)
7185 (org-at-item-p)
7187 (error nil))))
7189 (defun org-insert-item (&optional checkbox)
7190 "Insert a new item at the current level.
7191 Return t when things worked, nil when we are not in an item."
7192 (when (save-excursion
7193 (condition-case nil
7194 (progn
7195 (org-beginning-of-item)
7196 (org-at-item-p)
7197 (if (org-invisible-p) (error "Invisible item"))
7199 (error nil)))
7200 (let* ((bul (match-string 0))
7201 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
7202 (match-end 0)))
7203 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
7204 pos)
7205 (cond
7206 ((and (org-at-item-p) (<= (point) eow))
7207 ;; before the bullet
7208 (beginning-of-line 1)
7209 (open-line (if blank 2 1)))
7210 ((<= (point) eow)
7211 (beginning-of-line 1))
7213 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
7214 (end-of-line 1)
7215 (delete-horizontal-space))
7216 (newline (if blank 2 1))))
7217 (insert bul (if checkbox "[ ]" ""))
7218 (just-one-space)
7219 (setq pos (point))
7220 (end-of-line 1)
7221 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
7222 (org-maybe-renumber-ordered-list)
7223 (and checkbox (org-update-checkbox-count-maybe))
7226 ;;; Checkboxes
7228 (defun org-at-item-checkbox-p ()
7229 "Is point at a line starting a plain-list item with a checklet?"
7230 (and (org-at-item-p)
7231 (save-excursion
7232 (goto-char (match-end 0))
7233 (skip-chars-forward " \t")
7234 (looking-at "\\[[- X]\\]"))))
7236 (defun org-toggle-checkbox (&optional arg)
7237 "Toggle the checkbox in the current line."
7238 (interactive "P")
7239 (catch 'exit
7240 (let (beg end status (firstnew 'unknown))
7241 (cond
7242 ((org-region-active-p)
7243 (setq beg (region-beginning) end (region-end)))
7244 ((org-on-heading-p)
7245 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
7246 ((org-at-item-checkbox-p)
7247 (let ((pos (point)))
7248 (replace-match
7249 (cond (arg "[-]")
7250 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
7251 (t "[ ]"))
7252 t t)
7253 (goto-char pos))
7254 (throw 'exit t))
7255 (t (error "Not at a checkbox or heading, and no active region")))
7256 (save-excursion
7257 (goto-char beg)
7258 (while (< (point) end)
7259 (when (org-at-item-checkbox-p)
7260 (setq status (equal (match-string 0) "[X]"))
7261 (when (eq firstnew 'unknown)
7262 (setq firstnew (not status)))
7263 (replace-match
7264 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
7265 (beginning-of-line 2)))))
7266 (org-update-checkbox-count-maybe))
7268 (defun org-update-checkbox-count-maybe ()
7269 "Update checkbox statistics unless turned off by user."
7270 (when org-provide-checkbox-statistics
7271 (org-update-checkbox-count)))
7273 (defun org-update-checkbox-count (&optional all)
7274 "Update the checkbox statistics in the current section.
7275 This will find all statistic cookies like [57%] and [6/12] and update them
7276 with the current numbers. With optional prefix argument ALL, do this for
7277 the whole buffer."
7278 (interactive "P")
7279 (save-excursion
7280 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
7281 (beg (condition-case nil
7282 (progn (outline-back-to-heading) (point))
7283 (error (point-min))))
7284 (end (move-marker (make-marker)
7285 (progn (outline-next-heading) (point))))
7286 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7287 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
7288 (re-find (concat re "\\|" re-box))
7289 beg-cookie end-cookie is-percent c-on c-off lim
7290 eline curr-ind next-ind continue-from startsearch
7291 (cstat 0)
7293 (when all
7294 (goto-char (point-min))
7295 (outline-next-heading)
7296 (setq beg (point) end (point-max)))
7297 (goto-char end)
7298 ;; find each statistic cookie
7299 (while (re-search-backward re-find beg t)
7300 (setq beg-cookie (match-beginning 1)
7301 end-cookie (match-end 1)
7302 cstat (+ cstat (if end-cookie 1 0))
7303 startsearch (point-at-eol)
7304 continue-from (point-at-bol)
7305 is-percent (match-beginning 2)
7306 lim (cond
7307 ((org-on-heading-p) (outline-next-heading) (point))
7308 ((org-at-item-p) (org-end-of-item) (point))
7309 (t nil))
7310 c-on 0
7311 c-off 0)
7312 (when lim
7313 ;; find first checkbox for this cookie and gather
7314 ;; statistics from all that are at this indentation level
7315 (goto-char startsearch)
7316 (if (re-search-forward re-box lim t)
7317 (progn
7318 (org-beginning-of-item)
7319 (setq curr-ind (org-get-indentation))
7320 (setq next-ind curr-ind)
7321 (while (= curr-ind next-ind)
7322 (save-excursion (end-of-line) (setq eline (point)))
7323 (if (re-search-forward re-box eline t)
7324 (if (member (match-string 2) '("[ ]" "[-]"))
7325 (setq c-off (1+ c-off))
7326 (setq c-on (1+ c-on))
7329 (org-end-of-item)
7330 (setq next-ind (org-get-indentation))
7332 (goto-char continue-from)
7333 ;; update cookie
7334 (when end-cookie
7335 (delete-region beg-cookie end-cookie)
7336 (goto-char beg-cookie)
7337 (insert
7338 (if is-percent
7339 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
7340 (format "[%d/%d]" c-on (+ c-on c-off)))))
7341 ;; update items checkbox if it has one
7342 (when (org-at-item-p)
7343 (org-beginning-of-item)
7344 (when (and (> (+ c-on c-off) 0)
7345 (re-search-forward re-box (point-at-eol) t))
7346 (setq beg-cookie (match-beginning 2)
7347 end-cookie (match-end 2))
7348 (delete-region beg-cookie end-cookie)
7349 (goto-char beg-cookie)
7350 (cond ((= c-off 0) (insert "[X]"))
7351 ((= c-on 0) (insert "[ ]"))
7352 (t (insert "[-]")))
7354 (goto-char continue-from))
7355 (when (interactive-p)
7356 (message "Checkbox satistics updated %s (%d places)"
7357 (if all "in entire file" "in current outline entry") cstat)))))
7359 (defun org-get-checkbox-statistics-face ()
7360 "Select the face for checkbox statistics.
7361 The face will be `org-done' when all relevant boxes are checked. Otherwise
7362 it will be `org-todo'."
7363 (if (match-end 1)
7364 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
7365 (if (and (> (match-end 2) (match-beginning 2))
7366 (equal (match-string 2) (match-string 3)))
7367 'org-done
7368 'org-todo)))
7370 (defun org-get-indentation (&optional line)
7371 "Get the indentation of the current line, interpreting tabs.
7372 When LINE is given, assume it represents a line and compute its indentation."
7373 (if line
7374 (if (string-match "^ *" (org-remove-tabs line))
7375 (match-end 0))
7376 (save-excursion
7377 (beginning-of-line 1)
7378 (skip-chars-forward " \t")
7379 (current-column))))
7381 (defun org-remove-tabs (s &optional width)
7382 "Replace tabulators in S with spaces.
7383 Assumes that s is a single line, starting in column 0."
7384 (setq width (or width tab-width))
7385 (while (string-match "\t" s)
7386 (setq s (replace-match
7387 (make-string
7388 (- (* width (/ (+ (match-beginning 0) width) width))
7389 (match-beginning 0)) ?\ )
7390 t t s)))
7393 (defun org-fix-indentation (line ind)
7394 "Fix indentation in LINE.
7395 IND is a cons cell with target and minimum indentation.
7396 If the current indenation in LINE is smaller than the minimum,
7397 leave it alone. If it is larger than ind, set it to the target."
7398 (let* ((l (org-remove-tabs line))
7399 (i (org-get-indentation l))
7400 (i1 (car ind)) (i2 (cdr ind)))
7401 (if (>= i i2) (setq l (substring line i2)))
7402 (if (> i1 0)
7403 (concat (make-string i1 ?\ ) l)
7404 l)))
7406 (defcustom org-empty-line-terminates-plain-lists nil
7407 "Non-nil means, an empty line ends all plain list levels.
7408 When nil, empty lines are part of the preceeding item."
7409 :group 'org-plain-lists
7410 :type 'boolean)
7412 (defun org-beginning-of-item ()
7413 "Go to the beginning of the current hand-formatted item.
7414 If the cursor is not in an item, throw an error."
7415 (interactive)
7416 (let ((pos (point))
7417 (limit (save-excursion
7418 (condition-case nil
7419 (progn
7420 (org-back-to-heading)
7421 (beginning-of-line 2) (point))
7422 (error (point-min)))))
7423 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7424 ind ind1)
7425 (if (org-at-item-p)
7426 (beginning-of-line 1)
7427 (beginning-of-line 1)
7428 (skip-chars-forward " \t")
7429 (setq ind (current-column))
7430 (if (catch 'exit
7431 (while t
7432 (beginning-of-line 0)
7433 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
7435 (if (looking-at "[ \t]*$")
7436 (setq ind1 ind-empty)
7437 (skip-chars-forward " \t")
7438 (setq ind1 (current-column)))
7439 (if (< ind1 ind)
7440 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
7442 (goto-char pos)
7443 (error "Not in an item")))))
7445 (defun org-end-of-item ()
7446 "Go to the end of the current hand-formatted item.
7447 If the cursor is not in an item, throw an error."
7448 (interactive)
7449 (let* ((pos (point))
7450 ind1
7451 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
7452 (limit (save-excursion (outline-next-heading) (point)))
7453 (ind (save-excursion
7454 (org-beginning-of-item)
7455 (skip-chars-forward " \t")
7456 (current-column)))
7457 (end (catch 'exit
7458 (while t
7459 (beginning-of-line 2)
7460 (if (eobp) (throw 'exit (point)))
7461 (if (>= (point) limit) (throw 'exit (point-at-bol)))
7462 (if (looking-at "[ \t]*$")
7463 (setq ind1 ind-empty)
7464 (skip-chars-forward " \t")
7465 (setq ind1 (current-column)))
7466 (if (<= ind1 ind)
7467 (throw 'exit (point-at-bol)))))))
7468 (if end
7469 (goto-char end)
7470 (goto-char pos)
7471 (error "Not in an item"))))
7473 (defun org-next-item ()
7474 "Move to the beginning of the next item in the current plain list.
7475 Error if not at a plain list, or if this is the last item in the list."
7476 (interactive)
7477 (let (ind ind1 (pos (point)))
7478 (org-beginning-of-item)
7479 (setq ind (org-get-indentation))
7480 (org-end-of-item)
7481 (setq ind1 (org-get-indentation))
7482 (unless (and (org-at-item-p) (= ind ind1))
7483 (goto-char pos)
7484 (error "On last item"))))
7486 (defun org-previous-item ()
7487 "Move to the beginning of the previous item in the current plain list.
7488 Error if not at a plain list, or if this is the first item in the list."
7489 (interactive)
7490 (let (beg ind ind1 (pos (point)))
7491 (org-beginning-of-item)
7492 (setq beg (point))
7493 (setq ind (org-get-indentation))
7494 (goto-char beg)
7495 (catch 'exit
7496 (while t
7497 (beginning-of-line 0)
7498 (if (looking-at "[ \t]*$")
7500 (if (<= (setq ind1 (org-get-indentation)) ind)
7501 (throw 'exit t)))))
7502 (condition-case nil
7503 (if (or (not (org-at-item-p))
7504 (< ind1 (1- ind)))
7505 (error "")
7506 (org-beginning-of-item))
7507 (error (goto-char pos)
7508 (error "On first item")))))
7510 (defun org-first-list-item-p ()
7511 "Is this heading the item in a plain list?"
7512 (unless (org-at-item-p)
7513 (error "Not at a plain list item"))
7514 (org-beginning-of-item)
7515 (= (point) (save-excursion (org-beginning-of-item-list))))
7517 (defun org-move-item-down ()
7518 "Move the plain list item at point down, i.e. swap with following item.
7519 Subitems (items with larger indentation) are considered part of the item,
7520 so this really moves item trees."
7521 (interactive)
7522 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
7523 (org-beginning-of-item)
7524 (setq beg0 (point))
7525 (save-excursion
7526 (setq ne-beg (org-back-over-empty-lines))
7527 (setq beg (point)))
7528 (goto-char beg0)
7529 (setq ind (org-get-indentation))
7530 (org-end-of-item)
7531 (setq end0 (point))
7532 (setq ind1 (org-get-indentation))
7533 (setq ne-end (org-back-over-empty-lines))
7534 (setq end (point))
7535 (goto-char beg0)
7536 (when (and (org-first-list-item-p) (< ne-end ne-beg))
7537 ;; include less whitespace
7538 (save-excursion
7539 (goto-char beg)
7540 (forward-line (- ne-beg ne-end))
7541 (setq beg (point))))
7542 (goto-char end0)
7543 (if (and (org-at-item-p) (= ind ind1))
7544 (progn
7545 (org-end-of-item)
7546 (org-back-over-empty-lines)
7547 (setq txt (buffer-substring beg end))
7548 (save-excursion
7549 (delete-region beg end))
7550 (setq pos (point))
7551 (insert txt)
7552 (goto-char pos) (org-skip-whitespace)
7553 (org-maybe-renumber-ordered-list))
7554 (goto-char pos)
7555 (error "Cannot move this item further down"))))
7557 (defun org-move-item-up (arg)
7558 "Move the plain list item at point up, i.e. swap with previous item.
7559 Subitems (items with larger indentation) are considered part of the item,
7560 so this really moves item trees."
7561 (interactive "p")
7562 (let (beg beg0 end ind ind1 (pos (point)) txt
7563 ne-beg ne-ins ins-end)
7564 (org-beginning-of-item)
7565 (setq beg0 (point))
7566 (setq ind (org-get-indentation))
7567 (save-excursion
7568 (setq ne-beg (org-back-over-empty-lines))
7569 (setq beg (point)))
7570 (goto-char beg0)
7571 (org-end-of-item)
7572 (setq end (point))
7573 (goto-char beg0)
7574 (catch 'exit
7575 (while t
7576 (beginning-of-line 0)
7577 (if (looking-at "[ \t]*$")
7578 (if org-empty-line-terminates-plain-lists
7579 (progn
7580 (goto-char pos)
7581 (error "Cannot move this item further up"))
7582 nil)
7583 (if (<= (setq ind1 (org-get-indentation)) ind)
7584 (throw 'exit t)))))
7585 (condition-case nil
7586 (org-beginning-of-item)
7587 (error (goto-char beg)
7588 (error "Cannot move this item further up")))
7589 (setq ind1 (org-get-indentation))
7590 (if (and (org-at-item-p) (= ind ind1))
7591 (progn
7592 (setq ne-ins (org-back-over-empty-lines))
7593 (setq txt (buffer-substring beg end))
7594 (save-excursion
7595 (delete-region beg end))
7596 (setq pos (point))
7597 (insert txt)
7598 (setq ins-end (point))
7599 (goto-char pos) (org-skip-whitespace)
7601 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
7602 ;; Move whitespace back to beginning
7603 (save-excursion
7604 (goto-char ins-end)
7605 (let ((kill-whole-line t))
7606 (kill-line (- ne-ins ne-beg)) (point)))
7607 (insert (make-string (- ne-ins ne-beg) ?\n)))
7609 (org-maybe-renumber-ordered-list))
7610 (goto-char pos)
7611 (error "Cannot move this item further up"))))
7613 (defun org-maybe-renumber-ordered-list ()
7614 "Renumber the ordered list at point if setup allows it.
7615 This tests the user option `org-auto-renumber-ordered-lists' before
7616 doing the renumbering."
7617 (interactive)
7618 (when (and org-auto-renumber-ordered-lists
7619 (org-at-item-p))
7620 (if (match-beginning 3)
7621 (org-renumber-ordered-list 1)
7622 (org-fix-bullet-type))))
7624 (defun org-maybe-renumber-ordered-list-safe ()
7625 (condition-case nil
7626 (save-excursion
7627 (org-maybe-renumber-ordered-list))
7628 (error nil)))
7630 (defun org-cycle-list-bullet (&optional which)
7631 "Cycle through the different itemize/enumerate bullets.
7632 This cycle the entire list level through the sequence:
7634 `-' -> `+' -> `*' -> `1.' -> `1)'
7636 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
7637 0 meand `-', 1 means `+' etc."
7638 (interactive "P")
7639 (org-preserve-lc
7640 (org-beginning-of-item-list)
7641 (org-at-item-p)
7642 (beginning-of-line 1)
7643 (let ((current (match-string 0))
7644 (prevp (eq which 'previous))
7645 new)
7646 (setq new (cond
7647 ((and (numberp which)
7648 (nth (1- which) '("-" "+" "*" "1." "1)"))))
7649 ((string-match "-" current) (if prevp "1)" "+"))
7650 ((string-match "\\+" current)
7651 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
7652 ((string-match "\\*" current) (if prevp "+" "1."))
7653 ((string-match "\\." current) (if prevp "*" "1)"))
7654 ((string-match ")" current) (if prevp "1." "-"))
7655 (t (error "This should not happen"))))
7656 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
7657 (org-fix-bullet-type)
7658 (org-maybe-renumber-ordered-list))))
7660 (defun org-get-string-indentation (s)
7661 "What indentation has S due to SPACE and TAB at the beginning of the string?"
7662 (let ((n -1) (i 0) (w tab-width) c)
7663 (catch 'exit
7664 (while (< (setq n (1+ n)) (length s))
7665 (setq c (aref s n))
7666 (cond ((= c ?\ ) (setq i (1+ i)))
7667 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
7668 (t (throw 'exit t)))))
7671 (defun org-renumber-ordered-list (arg)
7672 "Renumber an ordered plain list.
7673 Cursor needs to be in the first line of an item, the line that starts
7674 with something like \"1.\" or \"2)\"."
7675 (interactive "p")
7676 (unless (and (org-at-item-p)
7677 (match-beginning 3))
7678 (error "This is not an ordered list"))
7679 (let ((line (org-current-line))
7680 (col (current-column))
7681 (ind (org-get-string-indentation
7682 (buffer-substring (point-at-bol) (match-beginning 3))))
7683 ;; (term (substring (match-string 3) -1))
7684 ind1 (n (1- arg))
7685 fmt)
7686 ;; find where this list begins
7687 (org-beginning-of-item-list)
7688 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
7689 (setq fmt (concat "%d" (match-string 1)))
7690 (beginning-of-line 0)
7691 ;; walk forward and replace these numbers
7692 (catch 'exit
7693 (while t
7694 (catch 'next
7695 (beginning-of-line 2)
7696 (if (eobp) (throw 'exit nil))
7697 (if (looking-at "[ \t]*$") (throw 'next nil))
7698 (skip-chars-forward " \t") (setq ind1 (current-column))
7699 (if (> ind1 ind) (throw 'next t))
7700 (if (< ind1 ind) (throw 'exit t))
7701 (if (not (org-at-item-p)) (throw 'exit nil))
7702 (delete-region (match-beginning 2) (match-end 2))
7703 (goto-char (match-beginning 2))
7704 (insert (format fmt (setq n (1+ n)))))))
7705 (goto-line line)
7706 (move-to-column col)))
7708 (defun org-fix-bullet-type ()
7709 "Make sure all items in this list have the same bullet as the firsst item."
7710 (interactive)
7711 (unless (org-at-item-p) (error "This is not a list"))
7712 (let ((line (org-current-line))
7713 (col (current-column))
7714 (ind (current-indentation))
7715 ind1 bullet)
7716 ;; find where this list begins
7717 (org-beginning-of-item-list)
7718 (beginning-of-line 1)
7719 ;; find out what the bullet type is
7720 (looking-at "[ \t]*\\(\\S-+\\)")
7721 (setq bullet (match-string 1))
7722 ;; walk forward and replace these numbers
7723 (beginning-of-line 0)
7724 (catch 'exit
7725 (while t
7726 (catch 'next
7727 (beginning-of-line 2)
7728 (if (eobp) (throw 'exit nil))
7729 (if (looking-at "[ \t]*$") (throw 'next nil))
7730 (skip-chars-forward " \t") (setq ind1 (current-column))
7731 (if (> ind1 ind) (throw 'next t))
7732 (if (< ind1 ind) (throw 'exit t))
7733 (if (not (org-at-item-p)) (throw 'exit nil))
7734 (skip-chars-forward " \t")
7735 (looking-at "\\S-+")
7736 (replace-match bullet))))
7737 (goto-line line)
7738 (move-to-column col)
7739 (if (string-match "[0-9]" bullet)
7740 (org-renumber-ordered-list 1))))
7742 (defun org-beginning-of-item-list ()
7743 "Go to the beginning of the current item list.
7744 I.e. to the first item in this list."
7745 (interactive)
7746 (org-beginning-of-item)
7747 (let ((pos (point-at-bol))
7748 (ind (org-get-indentation))
7749 ind1)
7750 ;; find where this list begins
7751 (catch 'exit
7752 (while t
7753 (catch 'next
7754 (beginning-of-line 0)
7755 (if (looking-at "[ \t]*$")
7756 (throw (if (bobp) 'exit 'next) t))
7757 (skip-chars-forward " \t") (setq ind1 (current-column))
7758 (if (or (< ind1 ind)
7759 (and (= ind1 ind)
7760 (not (org-at-item-p)))
7761 (bobp))
7762 (throw 'exit t)
7763 (when (org-at-item-p) (setq pos (point-at-bol)))))))
7764 (goto-char pos)))
7767 (defun org-end-of-item-list ()
7768 "Go to the end of the current item list.
7769 I.e. to the text after the last item."
7770 (interactive)
7771 (org-beginning-of-item)
7772 (let ((pos (point-at-bol))
7773 (ind (org-get-indentation))
7774 ind1)
7775 ;; find where this list begins
7776 (catch 'exit
7777 (while t
7778 (catch 'next
7779 (beginning-of-line 2)
7780 (if (looking-at "[ \t]*$")
7781 (throw (if (eobp) 'exit 'next) t))
7782 (skip-chars-forward " \t") (setq ind1 (current-column))
7783 (if (or (< ind1 ind)
7784 (and (= ind1 ind)
7785 (not (org-at-item-p)))
7786 (eobp))
7787 (progn
7788 (setq pos (point-at-bol))
7789 (throw 'exit t))))))
7790 (goto-char pos)))
7793 (defvar org-last-indent-begin-marker (make-marker))
7794 (defvar org-last-indent-end-marker (make-marker))
7796 (defun org-outdent-item (arg)
7797 "Outdent a local list item."
7798 (interactive "p")
7799 (org-indent-item (- arg)))
7801 (defun org-indent-item (arg)
7802 "Indent a local list item."
7803 (interactive "p")
7804 (unless (org-at-item-p)
7805 (error "Not on an item"))
7806 (save-excursion
7807 (let (beg end ind ind1 tmp delta ind-down ind-up)
7808 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
7809 (setq beg org-last-indent-begin-marker
7810 end org-last-indent-end-marker)
7811 (org-beginning-of-item)
7812 (setq beg (move-marker org-last-indent-begin-marker (point)))
7813 (org-end-of-item)
7814 (setq end (move-marker org-last-indent-end-marker (point))))
7815 (goto-char beg)
7816 (setq tmp (org-item-indent-positions)
7817 ind (car tmp)
7818 ind-down (nth 2 tmp)
7819 ind-up (nth 1 tmp)
7820 delta (if (> arg 0)
7821 (if ind-down (- ind-down ind) 2)
7822 (if ind-up (- ind-up ind) -2)))
7823 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
7824 (while (< (point) end)
7825 (beginning-of-line 1)
7826 (skip-chars-forward " \t") (setq ind1 (current-column))
7827 (delete-region (point-at-bol) (point))
7828 (or (eolp) (indent-to-column (+ ind1 delta)))
7829 (beginning-of-line 2))))
7830 (org-fix-bullet-type)
7831 (org-maybe-renumber-ordered-list-safe)
7832 (save-excursion
7833 (beginning-of-line 0)
7834 (condition-case nil (org-beginning-of-item) (error nil))
7835 (org-maybe-renumber-ordered-list-safe)))
7837 (defun org-item-indent-positions ()
7838 "Return indentation for plain list items.
7839 This returns a list with three values: The current indentation, the
7840 parent indentation and the indentation a child should habe.
7841 Assumes cursor in item line."
7842 (let* ((bolpos (point-at-bol))
7843 (ind (org-get-indentation))
7844 ind-down ind-up pos)
7845 (save-excursion
7846 (org-beginning-of-item-list)
7847 (skip-chars-backward "\n\r \t")
7848 (when (org-in-item-p)
7849 (org-beginning-of-item)
7850 (setq ind-up (org-get-indentation))))
7851 (setq pos (point))
7852 (save-excursion
7853 (cond
7854 ((and (condition-case nil (progn (org-previous-item) t)
7855 (error nil))
7856 (or (forward-char 1) t)
7857 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
7858 (setq ind-down (org-get-indentation)))
7859 ((and (goto-char pos)
7860 (org-at-item-p))
7861 (goto-char (match-end 0))
7862 (skip-chars-forward " \t")
7863 (setq ind-down (current-column)))))
7864 (list ind ind-up ind-down)))
7866 ;;; The orgstruct minor mode
7868 ;; Define a minor mode which can be used in other modes in order to
7869 ;; integrate the org-mode structure editing commands.
7871 ;; This is really a hack, because the org-mode structure commands use
7872 ;; keys which normally belong to the major mode. Here is how it
7873 ;; works: The minor mode defines all the keys necessary to operate the
7874 ;; structure commands, but wraps the commands into a function which
7875 ;; tests if the cursor is currently at a headline or a plain list
7876 ;; item. If that is the case, the structure command is used,
7877 ;; temporarily setting many Org-mode variables like regular
7878 ;; expressions for filling etc. However, when any of those keys is
7879 ;; used at a different location, function uses `key-binding' to look
7880 ;; up if the key has an associated command in another currently active
7881 ;; keymap (minor modes, major mode, global), and executes that
7882 ;; command. There might be problems if any of the keys is otherwise
7883 ;; used as a prefix key.
7885 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7886 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7887 ;; addresses this by checking explicitly for both bindings.
7889 (defvar orgstruct-mode-map (make-sparse-keymap)
7890 "Keymap for the minor `orgstruct-mode'.")
7892 (defvar org-local-vars nil
7893 "List of local variables, for use by `orgstruct-mode'")
7895 ;;;###autoload
7896 (define-minor-mode orgstruct-mode
7897 "Toggle the minor more `orgstruct-mode'.
7898 This mode is for using Org-mode structure commands in other modes.
7899 The following key behave as if Org-mode was active, if the cursor
7900 is on a headline, or on a plain list item (both in the definition
7901 of Org-mode).
7903 M-up Move entry/item up
7904 M-down Move entry/item down
7905 M-left Promote
7906 M-right Demote
7907 M-S-up Move entry/item up
7908 M-S-down Move entry/item down
7909 M-S-left Promote subtree
7910 M-S-right Demote subtree
7911 M-q Fill paragraph and items like in Org-mode
7912 C-c ^ Sort entries
7913 C-c - Cycle list bullet
7914 TAB Cycle item visibility
7915 M-RET Insert new heading/item
7916 S-M-RET Insert new TODO heading / Chekbox item
7917 C-c C-c Set tags / toggle checkbox"
7918 nil " OrgStruct" nil
7919 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7921 ;;;###autoload
7922 (defun turn-on-orgstruct ()
7923 "Unconditionally turn on `orgstruct-mode'."
7924 (orgstruct-mode 1))
7926 ;;;###autoload
7927 (defun turn-on-orgstruct++ ()
7928 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
7929 In addition to setting orgstruct-mode, this also exports all indentation and
7930 autofilling variables from org-mode into the buffer. Note that turning
7931 off orgstruct-mode will *not* remove these additional settings."
7932 (orgstruct-mode 1)
7933 (let (var val)
7934 (mapc
7935 (lambda (x)
7936 (when (string-match
7937 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7938 (symbol-name (car x)))
7939 (setq var (car x) val (nth 1 x))
7940 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7941 org-local-vars)))
7943 (defun orgstruct-error ()
7944 "Error when there is no default binding for a structure key."
7945 (interactive)
7946 (error "This key has no function outside structure elements"))
7948 (defun orgstruct-setup ()
7949 "Setup orgstruct keymaps."
7950 (let ((nfunc 0)
7951 (bindings
7952 (list
7953 '([(meta up)] org-metaup)
7954 '([(meta down)] org-metadown)
7955 '([(meta left)] org-metaleft)
7956 '([(meta right)] org-metaright)
7957 '([(meta shift up)] org-shiftmetaup)
7958 '([(meta shift down)] org-shiftmetadown)
7959 '([(meta shift left)] org-shiftmetaleft)
7960 '([(meta shift right)] org-shiftmetaright)
7961 '([(shift up)] org-shiftup)
7962 '([(shift down)] org-shiftdown)
7963 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7964 '("\M-q" fill-paragraph)
7965 '("\C-c^" org-sort)
7966 '("\C-c-" org-cycle-list-bullet)))
7967 elt key fun cmd)
7968 (while (setq elt (pop bindings))
7969 (setq nfunc (1+ nfunc))
7970 (setq key (org-key (car elt))
7971 fun (nth 1 elt)
7972 cmd (orgstruct-make-binding fun nfunc key))
7973 (org-defkey orgstruct-mode-map key cmd))
7975 ;; Special treatment needed for TAB and RET
7976 (org-defkey orgstruct-mode-map [(tab)]
7977 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7978 (org-defkey orgstruct-mode-map "\C-i"
7979 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7981 (org-defkey orgstruct-mode-map "\M-\C-m"
7982 (orgstruct-make-binding 'org-insert-heading 105
7983 "\M-\C-m" [(meta return)]))
7984 (org-defkey orgstruct-mode-map [(meta return)]
7985 (orgstruct-make-binding 'org-insert-heading 106
7986 [(meta return)] "\M-\C-m"))
7988 (org-defkey orgstruct-mode-map [(shift meta return)]
7989 (orgstruct-make-binding 'org-insert-todo-heading 107
7990 [(meta return)] "\M-\C-m"))
7992 (unless org-local-vars
7993 (setq org-local-vars (org-get-local-variables)))
7997 (defun orgstruct-make-binding (fun n &rest keys)
7998 "Create a function for binding in the structure minor mode.
7999 FUN is the command to call inside a table. N is used to create a unique
8000 command name. KEYS are keys that should be checked in for a command
8001 to execute outside of tables."
8002 (eval
8003 (list 'defun
8004 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
8005 '(arg)
8006 (concat "In Structure, run `" (symbol-name fun) "'.\n"
8007 "Outside of structure, run the binding of `"
8008 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
8009 "'.")
8010 '(interactive "p")
8011 (list 'if
8012 '(org-context-p 'headline 'item)
8013 (list 'org-run-like-in-org-mode (list 'quote fun))
8014 (list 'let '(orgstruct-mode)
8015 (list 'call-interactively
8016 (append '(or)
8017 (mapcar (lambda (k)
8018 (list 'key-binding k))
8019 keys)
8020 '('orgstruct-error))))))))
8022 (defun org-context-p (&rest contexts)
8023 "Check if local context is and of CONTEXTS.
8024 Possible values in the list of contexts are `table', `headline', and `item'."
8025 (let ((pos (point)))
8026 (goto-char (point-at-bol))
8027 (prog1 (or (and (memq 'table contexts)
8028 (looking-at "[ \t]*|"))
8029 (and (memq 'headline contexts)
8030 (looking-at "\\*+"))
8031 (and (memq 'item contexts)
8032 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
8033 (goto-char pos))))
8035 (defun org-get-local-variables ()
8036 "Return a list of all local variables in an org-mode buffer."
8037 (let (varlist)
8038 (with-current-buffer (get-buffer-create "*Org tmp*")
8039 (erase-buffer)
8040 (org-mode)
8041 (setq varlist (buffer-local-variables)))
8042 (kill-buffer "*Org tmp*")
8043 (delq nil
8044 (mapcar
8045 (lambda (x)
8046 (setq x
8047 (if (symbolp x)
8048 (list x)
8049 (list (car x) (list 'quote (cdr x)))))
8050 (if (string-match
8051 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
8052 (symbol-name (car x)))
8053 x nil))
8054 varlist))))
8056 ;;;###autoload
8057 (defun org-run-like-in-org-mode (cmd)
8058 (unless org-local-vars
8059 (setq org-local-vars (org-get-local-variables)))
8060 (eval (list 'let org-local-vars
8061 (list 'call-interactively (list 'quote cmd)))))
8063 ;;;; Archiving
8065 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
8067 (defun org-archive-subtree (&optional find-done)
8068 "Move the current subtree to the archive.
8069 The archive can be a certain top-level heading in the current file, or in
8070 a different file. The tree will be moved to that location, the subtree
8071 heading be marked DONE, and the current time will be added.
8073 When called with prefix argument FIND-DONE, find whole trees without any
8074 open TODO items and archive them (after getting confirmation from the user).
8075 If the cursor is not at a headline when this comand is called, try all level
8076 1 trees. If the cursor is on a headline, only try the direct children of
8077 this heading."
8078 (interactive "P")
8079 (if find-done
8080 (org-archive-all-done)
8081 ;; Save all relevant TODO keyword-relatex variables
8083 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
8084 (tr-org-todo-keywords-1 org-todo-keywords-1)
8085 (tr-org-todo-kwd-alist org-todo-kwd-alist)
8086 (tr-org-done-keywords org-done-keywords)
8087 (tr-org-todo-regexp org-todo-regexp)
8088 (tr-org-todo-line-regexp org-todo-line-regexp)
8089 (tr-org-odd-levels-only org-odd-levels-only)
8090 (this-buffer (current-buffer))
8091 (org-archive-location org-archive-location)
8092 (re "^#\\+ARCHIVE:[ \t]+\\(\\S-.*\\S-\\)[ \t]*$")
8093 ;; start of variables that will be used for saving context
8094 ;; The compiler complains about them - keep them anyway!
8095 (file (abbreviate-file-name (buffer-file-name)))
8096 (olpath (mapconcat 'identity (org-get-outline-path) "/"))
8097 (time (format-time-string
8098 (substring (cdr org-time-stamp-formats) 1 -1)
8099 (current-time)))
8100 afile heading buffer level newfile-p
8101 category todo priority
8102 ;; start of variables that will be used for savind context
8103 ltags itags prop)
8105 ;; Try to find a local archive location
8106 (save-excursion
8107 (save-restriction
8108 (widen)
8109 (setq prop (org-entry-get nil "ARCHIVE" 'inherit))
8110 (if (and prop (string-match "\\S-" prop))
8111 (setq org-archive-location prop)
8112 (if (or (re-search-backward re nil t)
8113 (re-search-forward re nil t))
8114 (setq org-archive-location (match-string 1))))))
8116 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
8117 (progn
8118 (setq afile (format (match-string 1 org-archive-location)
8119 (file-name-nondirectory buffer-file-name))
8120 heading (match-string 2 org-archive-location)))
8121 (error "Invalid `org-archive-location'"))
8122 (if (> (length afile) 0)
8123 (setq newfile-p (not (file-exists-p afile))
8124 buffer (find-file-noselect afile))
8125 (setq buffer (current-buffer)))
8126 (unless buffer
8127 (error "Cannot access file \"%s\"" afile))
8128 (if (and (> (length heading) 0)
8129 (string-match "^\\*+" heading))
8130 (setq level (match-end 0))
8131 (setq heading nil level 0))
8132 (save-excursion
8133 (org-back-to-heading t)
8134 ;; Get context information that will be lost by moving the tree
8135 (org-refresh-category-properties)
8136 (setq category (org-get-category)
8137 todo (and (looking-at org-todo-line-regexp)
8138 (match-string 2))
8139 priority (org-get-priority (if (match-end 3) (match-string 3) ""))
8140 ltags (org-get-tags)
8141 itags (org-delete-all ltags (org-get-tags-at)))
8142 (setq ltags (mapconcat 'identity ltags " ")
8143 itags (mapconcat 'identity itags " "))
8144 ;; We first only copy, in case something goes wrong
8145 ;; we need to protect this-command, to avoid kill-region sets it,
8146 ;; which would lead to duplication of subtrees
8147 (let (this-command) (org-copy-subtree))
8148 (set-buffer buffer)
8149 ;; Enforce org-mode for the archive buffer
8150 (if (not (org-mode-p))
8151 ;; Force the mode for future visits.
8152 (let ((org-insert-mode-line-in-empty-file t)
8153 (org-inhibit-startup t))
8154 (call-interactively 'org-mode)))
8155 (when newfile-p
8156 (goto-char (point-max))
8157 (insert (format "\nArchived entries from file %s\n\n"
8158 (buffer-file-name this-buffer))))
8159 ;; Force the TODO keywords of the original buffer
8160 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
8161 (org-todo-keywords-1 tr-org-todo-keywords-1)
8162 (org-todo-kwd-alist tr-org-todo-kwd-alist)
8163 (org-done-keywords tr-org-done-keywords)
8164 (org-todo-regexp tr-org-todo-regexp)
8165 (org-todo-line-regexp tr-org-todo-line-regexp)
8166 (org-odd-levels-only
8167 (if (local-variable-p 'org-odd-levels-only (current-buffer))
8168 org-odd-levels-only
8169 tr-org-odd-levels-only)))
8170 (goto-char (point-min))
8171 (show-all)
8172 (if heading
8173 (progn
8174 (if (re-search-forward
8175 (concat "^" (regexp-quote heading)
8176 (org-re "[ \t]*\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\($\\|\r\\)"))
8177 nil t)
8178 (goto-char (match-end 0))
8179 ;; Heading not found, just insert it at the end
8180 (goto-char (point-max))
8181 (or (bolp) (insert "\n"))
8182 (insert "\n" heading "\n")
8183 (end-of-line 0))
8184 ;; Make the subtree visible
8185 (show-subtree)
8186 (org-end-of-subtree t)
8187 (skip-chars-backward " \t\r\n")
8188 (and (looking-at "[ \t\r\n]*")
8189 (replace-match "\n\n")))
8190 ;; No specific heading, just go to end of file.
8191 (goto-char (point-max)) (insert "\n"))
8192 ;; Paste
8193 (org-paste-subtree (org-get-valid-level level 1))
8195 ;; Mark the entry as done
8196 (when (and org-archive-mark-done
8197 (looking-at org-todo-line-regexp)
8198 (or (not (match-end 2))
8199 (not (member (match-string 2) org-done-keywords))))
8200 (let (org-log-done org-todo-log-states)
8201 (org-todo
8202 (car (or (member org-archive-mark-done org-done-keywords)
8203 org-done-keywords)))))
8205 ;; Add the context info
8206 (when org-archive-save-context-info
8207 (let ((l org-archive-save-context-info) e n v)
8208 (while (setq e (pop l))
8209 (when (and (setq v (symbol-value e))
8210 (stringp v) (string-match "\\S-" v))
8211 (setq n (concat "ARCHIVE_" (upcase (symbol-name e))))
8212 (org-entry-put (point) n v)))))
8214 ;; Save and kill the buffer, if it is not the same buffer.
8215 (if (not (eq this-buffer buffer))
8216 (progn (save-buffer) (kill-buffer buffer)))))
8217 ;; Here we are back in the original buffer. Everything seems to have
8218 ;; worked. So now cut the tree and finish up.
8219 (let (this-command) (org-cut-subtree))
8220 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
8221 (message "Subtree archived %s"
8222 (if (eq this-buffer buffer)
8223 (concat "under heading: " heading)
8224 (concat "in file: " (abbreviate-file-name afile)))))))
8226 (defun org-refresh-category-properties ()
8227 "Refresh category text properties in teh buffer."
8228 (let ((def-cat (cond
8229 ((null org-category)
8230 (if buffer-file-name
8231 (file-name-sans-extension
8232 (file-name-nondirectory buffer-file-name))
8233 "???"))
8234 ((symbolp org-category) (symbol-name org-category))
8235 (t org-category)))
8236 beg end cat pos optionp)
8237 (org-unmodified
8238 (save-excursion
8239 (save-restriction
8240 (widen)
8241 (goto-char (point-min))
8242 (put-text-property (point) (point-max) 'org-category def-cat)
8243 (while (re-search-forward
8244 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
8245 (setq pos (match-end 0)
8246 optionp (equal (char-after (match-beginning 0)) ?#)
8247 cat (org-trim (match-string 2)))
8248 (if optionp
8249 (setq beg (point-at-bol) end (point-max))
8250 (org-back-to-heading t)
8251 (setq beg (point) end (org-end-of-subtree t t)))
8252 (put-text-property beg end 'org-category cat)
8253 (goto-char pos)))))))
8255 (defun org-archive-all-done (&optional tag)
8256 "Archive sublevels of the current tree without open TODO items.
8257 If the cursor is not on a headline, try all level 1 trees. If
8258 it is on a headline, try all direct children.
8259 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
8260 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
8261 (rea (concat ".*:" org-archive-tag ":"))
8262 (begm (make-marker))
8263 (endm (make-marker))
8264 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
8265 "Move subtree to archive (no open TODO items)? "))
8266 beg end (cntarch 0))
8267 (if (org-on-heading-p)
8268 (progn
8269 (setq re1 (concat "^" (regexp-quote
8270 (make-string
8271 (1+ (- (match-end 0) (match-beginning 0) 1))
8272 ?*))
8273 " "))
8274 (move-marker begm (point))
8275 (move-marker endm (org-end-of-subtree t)))
8276 (setq re1 "^* ")
8277 (move-marker begm (point-min))
8278 (move-marker endm (point-max)))
8279 (save-excursion
8280 (goto-char begm)
8281 (while (re-search-forward re1 endm t)
8282 (setq beg (match-beginning 0)
8283 end (save-excursion (org-end-of-subtree t) (point)))
8284 (goto-char beg)
8285 (if (re-search-forward re end t)
8286 (goto-char end)
8287 (goto-char beg)
8288 (if (and (or (not tag) (not (looking-at rea)))
8289 (y-or-n-p question))
8290 (progn
8291 (if tag
8292 (org-toggle-tag org-archive-tag 'on)
8293 (org-archive-subtree))
8294 (setq cntarch (1+ cntarch)))
8295 (goto-char end)))))
8296 (message "%d trees archived" cntarch)))
8298 (defun org-cycle-hide-drawers (state)
8299 "Re-hide all drawers after a visibility state change."
8300 (when (and (org-mode-p)
8301 (not (memq state '(overview folded))))
8302 (save-excursion
8303 (let* ((globalp (memq state '(contents all)))
8304 (beg (if globalp (point-min) (point)))
8305 (end (if globalp (point-max) (org-end-of-subtree t))))
8306 (goto-char beg)
8307 (while (re-search-forward org-drawer-regexp end t)
8308 (org-flag-drawer t))))))
8310 (defun org-flag-drawer (flag)
8311 (save-excursion
8312 (beginning-of-line 1)
8313 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
8314 (let ((b (match-end 0))
8315 (outline-regexp org-outline-regexp))
8316 (if (re-search-forward
8317 "^[ \t]*:END:"
8318 (save-excursion (outline-next-heading) (point)) t)
8319 (outline-flag-region b (point-at-eol) flag)
8320 (error ":END: line missing"))))))
8322 (defun org-cycle-hide-archived-subtrees (state)
8323 "Re-hide all archived subtrees after a visibility state change."
8324 (when (and (not org-cycle-open-archived-trees)
8325 (not (memq state '(overview folded))))
8326 (save-excursion
8327 (let* ((globalp (memq state '(contents all)))
8328 (beg (if globalp (point-min) (point)))
8329 (end (if globalp (point-max) (org-end-of-subtree t))))
8330 (org-hide-archived-subtrees beg end)
8331 (goto-char beg)
8332 (if (looking-at (concat ".*:" org-archive-tag ":"))
8333 (message "%s" (substitute-command-keys
8334 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
8336 (defun org-force-cycle-archived ()
8337 "Cycle subtree even if it is archived."
8338 (interactive)
8339 (setq this-command 'org-cycle)
8340 (let ((org-cycle-open-archived-trees t))
8341 (call-interactively 'org-cycle)))
8343 (defun org-hide-archived-subtrees (beg end)
8344 "Re-hide all archived subtrees after a visibility state change."
8345 (save-excursion
8346 (let* ((re (concat ":" org-archive-tag ":")))
8347 (goto-char beg)
8348 (while (re-search-forward re end t)
8349 (and (org-on-heading-p) (hide-subtree))
8350 (org-end-of-subtree t)))))
8352 (defun org-toggle-tag (tag &optional onoff)
8353 "Toggle the tag TAG for the current line.
8354 If ONOFF is `on' or `off', don't toggle but set to this state."
8355 (unless (org-on-heading-p t) (error "Not on headling"))
8356 (let (res current)
8357 (save-excursion
8358 (beginning-of-line)
8359 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8360 (point-at-eol) t)
8361 (progn
8362 (setq current (match-string 1))
8363 (replace-match ""))
8364 (setq current ""))
8365 (setq current (nreverse (org-split-string current ":")))
8366 (cond
8367 ((eq onoff 'on)
8368 (setq res t)
8369 (or (member tag current) (push tag current)))
8370 ((eq onoff 'off)
8371 (or (not (member tag current)) (setq current (delete tag current))))
8372 (t (if (member tag current)
8373 (setq current (delete tag current))
8374 (setq res t)
8375 (push tag current))))
8376 (end-of-line 1)
8377 (if current
8378 (progn
8379 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8380 (org-set-tags nil t))
8381 (delete-horizontal-space))
8382 (run-hooks 'org-after-tags-change-hook))
8383 res))
8385 (defun org-toggle-archive-tag (&optional arg)
8386 "Toggle the archive tag for the current headline.
8387 With prefix ARG, check all children of current headline and offer tagging
8388 the children that do not contain any open TODO items."
8389 (interactive "P")
8390 (if arg
8391 (org-archive-all-done 'tag)
8392 (let (set)
8393 (save-excursion
8394 (org-back-to-heading t)
8395 (setq set (org-toggle-tag org-archive-tag))
8396 (when set (hide-subtree)))
8397 (and set (beginning-of-line 1))
8398 (message "Subtree %s" (if set "archived" "unarchived")))))
8401 ;;;; Tables
8403 ;;; The table editor
8405 ;; Watch out: Here we are talking about two different kind of tables.
8406 ;; Most of the code is for the tables created with the Org-mode table editor.
8407 ;; Sometimes, we talk about tables created and edited with the table.el
8408 ;; Emacs package. We call the former org-type tables, and the latter
8409 ;; table.el-type tables.
8411 (defun org-before-change-function (beg end)
8412 "Every change indicates that a table might need an update."
8413 (setq org-table-may-need-update t))
8415 (defconst org-table-line-regexp "^[ \t]*|"
8416 "Detects an org-type table line.")
8417 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8418 "Detects an org-type table line.")
8419 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8420 "Detects a table line marked for automatic recalculation.")
8421 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8422 "Detects a table line marked for automatic recalculation.")
8423 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8424 "Detects a table line marked for automatic recalculation.")
8425 (defconst org-table-hline-regexp "^[ \t]*|-"
8426 "Detects an org-type table hline.")
8427 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8428 "Detects a table-type table hline.")
8429 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8430 "Detects an org-type or table-type table.")
8431 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8432 "Searching from within a table (any type) this finds the first line
8433 outside the table.")
8434 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8435 "Searching from within a table (any type) this finds the first line
8436 outside the table.")
8438 (defvar org-table-last-highlighted-reference nil)
8439 (defvar org-table-formula-history nil)
8441 (defvar org-table-column-names nil
8442 "Alist with column names, derived from the `!' line.")
8443 (defvar org-table-column-name-regexp nil
8444 "Regular expression matching the current column names.")
8445 (defvar org-table-local-parameters nil
8446 "Alist with parameter names, derived from the `$' line.")
8447 (defvar org-table-named-field-locations nil
8448 "Alist with locations of named fields.")
8450 (defvar org-table-current-line-types nil
8451 "Table row types, non-nil only for the duration of a comand.")
8452 (defvar org-table-current-begin-line nil
8453 "Table begin line, non-nil only for the duration of a comand.")
8454 (defvar org-table-current-begin-pos nil
8455 "Table begin position, non-nil only for the duration of a comand.")
8456 (defvar org-table-dlines nil
8457 "Vector of data line line numbers in the current table.")
8458 (defvar org-table-hlines nil
8459 "Vector of hline line numbers in the current table.")
8461 (defconst org-table-range-regexp
8462 "@\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\(\\.\\.@?\\([-+]?I*[-+]?[0-9]*\\)?\\(\\$[-+]?[0-9]+\\)?\\)?"
8463 ;; 1 2 3 4 5
8464 "Regular expression for matching ranges in formulas.")
8466 (defconst org-table-range-regexp2
8467 (concat
8468 "\\(" "@[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)"
8469 "\\.\\."
8470 "\\(" "@?[-0-9I$&]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\|" "\\$[a-zA-Z0-9]+" "\\)")
8471 "Match a range for reference display.")
8473 (defconst org-table-translate-regexp
8474 (concat "\\(" "@[-0-9I$]+" "\\|" "[a-zA-Z]\\{1,2\\}\\([0-9]+\\|&\\)" "\\)")
8475 "Match a reference that needs translation, for reference display.")
8477 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
8479 (defun org-table-create-with-table.el ()
8480 "Use the table.el package to insert a new table.
8481 If there is already a table at point, convert between Org-mode tables
8482 and table.el tables."
8483 (interactive)
8484 (require 'table)
8485 (cond
8486 ((org-at-table.el-p)
8487 (if (y-or-n-p "Convert table to Org-mode table? ")
8488 (org-table-convert)))
8489 ((org-at-table-p)
8490 (if (y-or-n-p "Convert table to table.el table? ")
8491 (org-table-convert)))
8492 (t (call-interactively 'table-insert))))
8494 (defun org-table-create-or-convert-from-region (arg)
8495 "Convert region to table, or create an empty table.
8496 If there is an active region, convert it to a table, using the function
8497 `org-table-convert-region'. See the documentation of that function
8498 to learn how the prefix argument is interpreted to determine the field
8499 separator.
8500 If there is no such region, create an empty table with `org-table-create'."
8501 (interactive "P")
8502 (if (org-region-active-p)
8503 (org-table-convert-region (region-beginning) (region-end) arg)
8504 (org-table-create arg)))
8506 (defun org-table-create (&optional size)
8507 "Query for a size and insert a table skeleton.
8508 SIZE is a string Columns x Rows like for example \"3x2\"."
8509 (interactive "P")
8510 (unless size
8511 (setq size (read-string
8512 (concat "Table size Columns x Rows [e.g. "
8513 org-table-default-size "]: ")
8514 "" nil org-table-default-size)))
8516 (let* ((pos (point))
8517 (indent (make-string (current-column) ?\ ))
8518 (split (org-split-string size " *x *"))
8519 (rows (string-to-number (nth 1 split)))
8520 (columns (string-to-number (car split)))
8521 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8522 "\n")))
8523 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8524 (point-at-bol) (point)))
8525 (beginning-of-line 1)
8526 (newline))
8527 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8528 (dotimes (i rows) (insert line))
8529 (goto-char pos)
8530 (if (> rows 1)
8531 ;; Insert a hline after the first row.
8532 (progn
8533 (end-of-line 1)
8534 (insert "\n|-")
8535 (goto-char pos)))
8536 (org-table-align)))
8538 (defun org-table-convert-region (beg0 end0 &optional separator)
8539 "Convert region to a table.
8540 The region goes from BEG0 to END0, but these borders will be moved
8541 slightly, to make sure a beginning of line in the first line is included.
8543 SEPARATOR specifies the field separator in the lines. It can have the
8544 following values:
8546 '(4) Use the comma as a field separator
8547 '(16) Use a TAB as field separator
8548 integer When a number, use that many spaces as field separator
8549 nil When nil, the command tries to be smart and figure out the
8550 separator in the following way:
8551 - when each line contains a TAB, assume TAB-separated material
8552 - when each line contains a comme, assume CSV material
8553 - else, assume one or more SPACE charcters as separator."
8554 (interactive "rP")
8555 (let* ((beg (min beg0 end0))
8556 (end (max beg0 end0))
8558 (goto-char beg)
8559 (beginning-of-line 1)
8560 (setq beg (move-marker (make-marker) (point)))
8561 (goto-char end)
8562 (if (bolp) (backward-char 1) (end-of-line 1))
8563 (setq end (move-marker (make-marker) (point)))
8564 ;; Get the right field separator
8565 (unless separator
8566 (goto-char beg)
8567 (setq separator
8568 (cond
8569 ((not (re-search-forward "^[^\n\t]+$" end t)) '(16))
8570 ((not (re-search-forward "^[^\n,]+$" end t)) '(4))
8571 (t 1))))
8572 (setq re (cond
8573 ((equal separator '(4)) "^\\|\"?[ \t]*,[ \t]*\"?")
8574 ((equal separator '(16)) "^\\|\t")
8575 ((integerp separator)
8576 (format "^ *\\| *\t *\\| \\{%d,\\}" separator))
8577 (t (error "This should not happen"))))
8578 (goto-char beg)
8579 (while (re-search-forward re end t)
8580 (replace-match "| " t t))
8581 (goto-char beg)
8582 (insert " ")
8583 (org-table-align)))
8585 (defun org-table-import (file arg)
8586 "Import FILE as a table.
8587 The file is assumed to be tab-separated. Such files can be produced by most
8588 spreadsheet and database applications. If no tabs (at least one per line)
8589 are found, lines will be split on whitespace into fields."
8590 (interactive "f\nP")
8591 (or (bolp) (newline))
8592 (let ((beg (point))
8593 (pm (point-max)))
8594 (insert-file-contents file)
8595 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8597 (defun org-table-export ()
8598 "Export table as a tab-separated file.
8599 Such a file can be imported into a spreadsheet program like Excel."
8600 (interactive)
8601 (let* ((beg (org-table-begin))
8602 (end (org-table-end))
8603 (table (buffer-substring beg end))
8604 (file (read-file-name "Export table to: "))
8605 buf)
8606 (unless (or (not (file-exists-p file))
8607 (y-or-n-p (format "Overwrite file %s? " file)))
8608 (error "Abort"))
8609 (with-current-buffer (find-file-noselect file)
8610 (setq buf (current-buffer))
8611 (erase-buffer)
8612 (fundamental-mode)
8613 (insert table)
8614 (goto-char (point-min))
8615 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8616 (replace-match "" t t)
8617 (end-of-line 1))
8618 (goto-char (point-min))
8619 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8620 (replace-match "" t t)
8621 (goto-char (min (1+ (point)) (point-max))))
8622 (goto-char (point-min))
8623 (while (re-search-forward "^-[-+]*$" nil t)
8624 (replace-match "")
8625 (if (looking-at "\n")
8626 (delete-char 1)))
8627 (goto-char (point-min))
8628 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8629 (replace-match "\t" t t))
8630 (save-buffer))
8631 (kill-buffer buf)))
8633 (defvar org-table-aligned-begin-marker (make-marker)
8634 "Marker at the beginning of the table last aligned.
8635 Used to check if cursor still is in that table, to minimize realignment.")
8636 (defvar org-table-aligned-end-marker (make-marker)
8637 "Marker at the end of the table last aligned.
8638 Used to check if cursor still is in that table, to minimize realignment.")
8639 (defvar org-table-last-alignment nil
8640 "List of flags for flushright alignment, from the last re-alignment.
8641 This is being used to correctly align a single field after TAB or RET.")
8642 (defvar org-table-last-column-widths nil
8643 "List of max width of fields in each column.
8644 This is being used to correctly align a single field after TAB or RET.")
8645 (defvar org-table-overlay-coordinates nil
8646 "Overlay coordinates after each align of a table.")
8647 (make-variable-buffer-local 'org-table-overlay-coordinates)
8649 (defvar org-last-recalc-line nil)
8650 (defconst org-narrow-column-arrow "=>"
8651 "Used as display property in narrowed table columns.")
8653 (defun org-table-align ()
8654 "Align the table at point by aligning all vertical bars."
8655 (interactive)
8656 (let* (
8657 ;; Limits of table
8658 (beg (org-table-begin))
8659 (end (org-table-end))
8660 ;; Current cursor position
8661 (linepos (org-current-line))
8662 (colpos (org-table-current-column))
8663 (winstart (window-start))
8664 (winstartline (org-current-line (min winstart (1- (point-max)))))
8665 lines (new "") lengths l typenums ty fields maxfields i
8666 column
8667 (indent "") cnt frac
8668 rfmt hfmt
8669 (spaces '(1 . 1))
8670 (sp1 (car spaces))
8671 (sp2 (cdr spaces))
8672 (rfmt1 (concat
8673 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8674 (hfmt1 (concat
8675 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8676 emptystrings links dates emph narrow fmax f1 len c e)
8677 (untabify beg end)
8678 (remove-text-properties beg end '(org-cwidth t org-dwidth t display t))
8679 ;; Check if we have links or dates
8680 (goto-char beg)
8681 (setq links (re-search-forward org-bracket-link-regexp end t))
8682 (goto-char beg)
8683 (setq emph (and org-hide-emphasis-markers
8684 (re-search-forward org-emph-re end t)))
8685 (goto-char beg)
8686 (setq dates (and org-display-custom-times
8687 (re-search-forward org-ts-regexp-both end t)))
8688 ;; Make sure the link properties are right
8689 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8690 ;; Make sure the date properties are right
8691 (when dates (goto-char beg) (while (org-activate-dates end)))
8692 (when emph (goto-char beg) (while (org-do-emphasis-faces end)))
8694 ;; Check if we are narrowing any columns
8695 (goto-char beg)
8696 (setq narrow (and org-format-transports-properties-p
8697 (re-search-forward "<[0-9]+>" end t)))
8698 ;; Get the rows
8699 (setq lines (org-split-string
8700 (buffer-substring beg end) "\n"))
8701 ;; Store the indentation of the first line
8702 (if (string-match "^ *" (car lines))
8703 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8704 ;; Mark the hlines by setting the corresponding element to nil
8705 ;; At the same time, we remove trailing space.
8706 (setq lines (mapcar (lambda (l)
8707 (if (string-match "^ *|-" l)
8709 (if (string-match "[ \t]+$" l)
8710 (substring l 0 (match-beginning 0))
8711 l)))
8712 lines))
8713 ;; Get the data fields by splitting the lines.
8714 (setq fields (mapcar
8715 (lambda (l)
8716 (org-split-string l " *| *"))
8717 (delq nil (copy-sequence lines))))
8718 ;; How many fields in the longest line?
8719 (condition-case nil
8720 (setq maxfields (apply 'max (mapcar 'length fields)))
8721 (error
8722 (kill-region beg end)
8723 (org-table-create org-table-default-size)
8724 (error "Empty table - created default table")))
8725 ;; A list of empty strings to fill any short rows on output
8726 (setq emptystrings (make-list maxfields ""))
8727 ;; Check for special formatting.
8728 (setq i -1)
8729 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8730 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8731 ;; Check if there is an explicit width specified
8732 (when narrow
8733 (setq c column fmax nil)
8734 (while c
8735 (setq e (pop c))
8736 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8737 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8738 ;; Find fields that are wider than fmax, and shorten them
8739 (when fmax
8740 (loop for xx in column do
8741 (when (and (stringp xx)
8742 (> (org-string-width xx) fmax))
8743 (org-add-props xx nil
8744 'help-echo
8745 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8746 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8747 (unless (> f1 1)
8748 (error "Cannot narrow field starting with wide link \"%s\""
8749 (match-string 0 xx)))
8750 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8751 (add-text-properties (- f1 2) f1
8752 (list 'display org-narrow-column-arrow)
8753 xx)))))
8754 ;; Get the maximum width for each column
8755 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8756 ;; Get the fraction of numbers, to decide about alignment of the column
8757 (setq cnt 0 frac 0.0)
8758 (loop for x in column do
8759 (if (equal x "")
8761 (setq frac ( / (+ (* frac cnt)
8762 (if (string-match org-table-number-regexp x) 1 0))
8763 (setq cnt (1+ cnt))))))
8764 (push (>= frac org-table-number-fraction) typenums))
8765 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8767 ;; Store the alignment of this table, for later editing of single fields
8768 (setq org-table-last-alignment typenums
8769 org-table-last-column-widths lengths)
8771 ;; With invisible characters, `format' does not get the field width right
8772 ;; So we need to make these fields wide by hand.
8773 (when (or links emph)
8774 (loop for i from 0 upto (1- maxfields) do
8775 (setq len (nth i lengths))
8776 (loop for j from 0 upto (1- (length fields)) do
8777 (setq c (nthcdr i (car (nthcdr j fields))))
8778 (if (and (stringp (car c))
8779 (text-property-any 0 (length (car c)) 'invisible 'org-link (car c))
8780 ; (string-match org-bracket-link-regexp (car c))
8781 (< (org-string-width (car c)) len))
8782 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8784 ;; Compute the formats needed for output of the table
8785 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8786 (while (setq l (pop lengths))
8787 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8788 (setq rfmt (concat rfmt (format rfmt1 ty l))
8789 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8790 (setq rfmt (concat rfmt "\n")
8791 hfmt (concat (substring hfmt 0 -1) "|\n"))
8793 (setq new (mapconcat
8794 (lambda (l)
8795 (if l (apply 'format rfmt
8796 (append (pop fields) emptystrings))
8797 hfmt))
8798 lines ""))
8799 ;; Replace the old one
8800 (delete-region beg end)
8801 (move-marker end nil)
8802 (move-marker org-table-aligned-begin-marker (point))
8803 (insert new)
8804 (move-marker org-table-aligned-end-marker (point))
8805 (when (and orgtbl-mode (not (org-mode-p)))
8806 (goto-char org-table-aligned-begin-marker)
8807 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8808 ;; Try to move to the old location
8809 (goto-line winstartline)
8810 (setq winstart (point-at-bol))
8811 (goto-line linepos)
8812 (set-window-start (selected-window) winstart 'noforce)
8813 (org-table-goto-column colpos)
8814 (and org-table-overlay-coordinates (org-table-overlay-coordinates))
8815 (setq org-table-may-need-update nil)
8818 (defun org-string-width (s)
8819 "Compute width of string, ignoring invisible characters.
8820 This ignores character with invisibility property `org-link', and also
8821 characters with property `org-cwidth', because these will become invisible
8822 upon the next fontification round."
8823 (let (b l)
8824 (when (or (eq t buffer-invisibility-spec)
8825 (assq 'org-link buffer-invisibility-spec))
8826 (while (setq b (text-property-any 0 (length s)
8827 'invisible 'org-link s))
8828 (setq s (concat (substring s 0 b)
8829 (substring s (or (next-single-property-change
8830 b 'invisible s) (length s)))))))
8831 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8832 (setq s (concat (substring s 0 b)
8833 (substring s (or (next-single-property-change
8834 b 'org-cwidth s) (length s))))))
8835 (setq l (string-width s) b -1)
8836 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
8837 (setq l (- l (get-text-property b 'org-dwidth-n s))))
8840 (defun org-table-begin (&optional table-type)
8841 "Find the beginning of the table and return its position.
8842 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8843 (save-excursion
8844 (if (not (re-search-backward
8845 (if table-type org-table-any-border-regexp
8846 org-table-border-regexp)
8847 nil t))
8848 (progn (goto-char (point-min)) (point))
8849 (goto-char (match-beginning 0))
8850 (beginning-of-line 2)
8851 (point))))
8853 (defun org-table-end (&optional table-type)
8854 "Find the end of the table and return its position.
8855 With argument TABLE-TYPE, go to the end of a table.el-type table."
8856 (save-excursion
8857 (if (not (re-search-forward
8858 (if table-type org-table-any-border-regexp
8859 org-table-border-regexp)
8860 nil t))
8861 (goto-char (point-max))
8862 (goto-char (match-beginning 0)))
8863 (point-marker)))
8865 (defun org-table-justify-field-maybe (&optional new)
8866 "Justify the current field, text to left, number to right.
8867 Optional argument NEW may specify text to replace the current field content."
8868 (cond
8869 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8870 ((org-at-table-hline-p))
8871 ((and (not new)
8872 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8873 (current-buffer)))
8874 (< (point) org-table-aligned-begin-marker)
8875 (>= (point) org-table-aligned-end-marker)))
8876 ;; This is not the same table, force a full re-align
8877 (setq org-table-may-need-update t))
8878 (t ;; realign the current field, based on previous full realign
8879 (let* ((pos (point)) s
8880 (col (org-table-current-column))
8881 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8882 l f n o e)
8883 (when (> col 0)
8884 (skip-chars-backward "^|\n")
8885 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8886 (progn
8887 (setq s (match-string 1)
8888 o (match-string 0)
8889 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8890 e (not (= (match-beginning 2) (match-end 2))))
8891 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8892 l (if e "|" (setq org-table-may-need-update t) ""))
8893 n (format f s))
8894 (if new
8895 (if (<= (length new) l) ;; FIXME: length -> str-width?
8896 (setq n (format f new))
8897 (setq n (concat new "|") org-table-may-need-update t)))
8898 (or (equal n o)
8899 (let (org-table-may-need-update)
8900 (replace-match n t t))))
8901 (setq org-table-may-need-update t))
8902 (goto-char pos))))))
8904 (defun org-table-next-field ()
8905 "Go to the next field in the current table, creating new lines as needed.
8906 Before doing so, re-align the table if necessary."
8907 (interactive)
8908 (org-table-maybe-eval-formula)
8909 (org-table-maybe-recalculate-line)
8910 (if (and org-table-automatic-realign
8911 org-table-may-need-update)
8912 (org-table-align))
8913 (let ((end (org-table-end)))
8914 (if (org-at-table-hline-p)
8915 (end-of-line 1))
8916 (condition-case nil
8917 (progn
8918 (re-search-forward "|" end)
8919 (if (looking-at "[ \t]*$")
8920 (re-search-forward "|" end))
8921 (if (and (looking-at "-")
8922 org-table-tab-jumps-over-hlines
8923 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8924 (goto-char (match-beginning 1)))
8925 (if (looking-at "-")
8926 (progn
8927 (beginning-of-line 0)
8928 (org-table-insert-row 'below))
8929 (if (looking-at " ") (forward-char 1))))
8930 (error
8931 (org-table-insert-row 'below)))))
8933 (defun org-table-previous-field ()
8934 "Go to the previous field in the table.
8935 Before doing so, re-align the table if necessary."
8936 (interactive)
8937 (org-table-justify-field-maybe)
8938 (org-table-maybe-recalculate-line)
8939 (if (and org-table-automatic-realign
8940 org-table-may-need-update)
8941 (org-table-align))
8942 (if (org-at-table-hline-p)
8943 (end-of-line 1))
8944 (re-search-backward "|" (org-table-begin))
8945 (re-search-backward "|" (org-table-begin))
8946 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8947 (re-search-backward "|" (org-table-begin)))
8948 (if (looking-at "| ?")
8949 (goto-char (match-end 0))))
8951 (defun org-table-next-row ()
8952 "Go to the next row (same column) in the current table.
8953 Before doing so, re-align the table if necessary."
8954 (interactive)
8955 (org-table-maybe-eval-formula)
8956 (org-table-maybe-recalculate-line)
8957 (if (or (looking-at "[ \t]*$")
8958 (save-excursion (skip-chars-backward " \t") (bolp)))
8959 (newline)
8960 (if (and org-table-automatic-realign
8961 org-table-may-need-update)
8962 (org-table-align))
8963 (let ((col (org-table-current-column)))
8964 (beginning-of-line 2)
8965 (if (or (not (org-at-table-p))
8966 (org-at-table-hline-p))
8967 (progn
8968 (beginning-of-line 0)
8969 (org-table-insert-row 'below)))
8970 (org-table-goto-column col)
8971 (skip-chars-backward "^|\n\r")
8972 (if (looking-at " ") (forward-char 1)))))
8974 (defun org-table-copy-down (n)
8975 "Copy a field down in the current column.
8976 If the field at the cursor is empty, copy into it the content of the nearest
8977 non-empty field above. With argument N, use the Nth non-empty field.
8978 If the current field is not empty, it is copied down to the next row, and
8979 the cursor is moved with it. Therefore, repeating this command causes the
8980 column to be filled row-by-row.
8981 If the variable `org-table-copy-increment' is non-nil and the field is an
8982 integer or a timestamp, it will be incremented while copying. In the case of
8983 a timestamp, if the cursor is on the year, change the year. If it is on the
8984 month or the day, change that. Point will stay on the current date field
8985 in order to easily repeat the interval."
8986 (interactive "p")
8987 (let* ((colpos (org-table-current-column))
8988 (col (current-column))
8989 (field (org-table-get-field))
8990 (non-empty (string-match "[^ \t]" field))
8991 (beg (org-table-begin))
8992 txt)
8993 (org-table-check-inside-data-field)
8994 (if non-empty
8995 (progn
8996 (setq txt (org-trim field))
8997 (org-table-next-row)
8998 (org-table-blank-field))
8999 (save-excursion
9000 (setq txt
9001 (catch 'exit
9002 (while (progn (beginning-of-line 1)
9003 (re-search-backward org-table-dataline-regexp
9004 beg t))
9005 (org-table-goto-column colpos t)
9006 (if (and (looking-at
9007 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9008 (= (setq n (1- n)) 0))
9009 (throw 'exit (match-string 1))))))))
9010 (if txt
9011 (progn
9012 (if (and org-table-copy-increment
9013 (string-match "^[0-9]+$" txt))
9014 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9015 (insert txt)
9016 (move-to-column col)
9017 (if (and org-table-copy-increment (org-at-timestamp-p t))
9018 (org-timestamp-up 1)
9019 (org-table-maybe-recalculate-line))
9020 (org-table-align)
9021 (move-to-column col))
9022 (error "No non-empty field found"))))
9024 (defun org-table-check-inside-data-field ()
9025 "Is point inside a table data field?
9026 I.e. not on a hline or before the first or after the last column?
9027 This actually throws an error, so it aborts the current command."
9028 (if (or (not (org-at-table-p))
9029 (= (org-table-current-column) 0)
9030 (org-at-table-hline-p)
9031 (looking-at "[ \t]*$"))
9032 (error "Not in table data field")))
9034 (defvar org-table-clip nil
9035 "Clipboard for table regions.")
9037 (defun org-table-blank-field ()
9038 "Blank the current table field or active region."
9039 (interactive)
9040 (org-table-check-inside-data-field)
9041 (if (and (interactive-p) (org-region-active-p))
9042 (let (org-table-clip)
9043 (org-table-cut-region (region-beginning) (region-end)))
9044 (skip-chars-backward "^|")
9045 (backward-char 1)
9046 (if (looking-at "|[^|\n]+")
9047 (let* ((pos (match-beginning 0))
9048 (match (match-string 0))
9049 (len (org-string-width match)))
9050 (replace-match (concat "|" (make-string (1- len) ?\ )))
9051 (goto-char (+ 2 pos))
9052 (substring match 1)))))
9054 (defun org-table-get-field (&optional n replace)
9055 "Return the value of the field in column N of current row.
9056 N defaults to current field.
9057 If REPLACE is a string, replace field with this value. The return value
9058 is always the old value."
9059 (and n (org-table-goto-column n))
9060 (skip-chars-backward "^|\n")
9061 (backward-char 1)
9062 (if (looking-at "|[^|\r\n]*")
9063 (let* ((pos (match-beginning 0))
9064 (val (buffer-substring (1+ pos) (match-end 0))))
9065 (if replace
9066 (replace-match (concat "|" replace) t t))
9067 (goto-char (min (point-at-eol) (+ 2 pos)))
9068 val)
9069 (forward-char 1) ""))
9071 (defun org-table-field-info (arg)
9072 "Show info about the current field, and highlight any reference at point."
9073 (interactive "P")
9074 (org-table-get-specials)
9075 (save-excursion
9076 (let* ((pos (point))
9077 (col (org-table-current-column))
9078 (cname (car (rassoc (int-to-string col) org-table-column-names)))
9079 (name (car (rassoc (list (org-current-line) col)
9080 org-table-named-field-locations)))
9081 (eql (org-table-get-stored-formulas))
9082 (dline (org-table-current-dline))
9083 (ref (format "@%d$%d" dline col))
9084 (ref1 (org-table-convert-refs-to-an ref))
9085 (fequation (or (assoc name eql) (assoc ref eql)))
9086 (cequation (assoc (int-to-string col) eql))
9087 (eqn (or fequation cequation)))
9088 (goto-char pos)
9089 (condition-case nil
9090 (org-table-show-reference 'local)
9091 (error nil))
9092 (message "line @%d, col $%s%s, ref @%d$%d or %s%s%s"
9093 dline col
9094 (if cname (concat " or $" cname) "")
9095 dline col ref1
9096 (if name (concat " or $" name) "")
9097 ;; FIXME: formula info not correct if special table line
9098 (if eqn
9099 (concat ", formula: "
9100 (org-table-formula-to-user
9101 (concat
9102 (if (string-match "^[$@]"(car eqn)) "" "$")
9103 (car eqn) "=" (cdr eqn))))
9104 "")))))
9106 (defun org-table-current-column ()
9107 "Find out which column we are in.
9108 When called interactively, column is also displayed in echo area."
9109 (interactive)
9110 (if (interactive-p) (org-table-check-inside-data-field))
9111 (save-excursion
9112 (let ((cnt 0) (pos (point)))
9113 (beginning-of-line 1)
9114 (while (search-forward "|" pos t)
9115 (setq cnt (1+ cnt)))
9116 (if (interactive-p) (message "This is table column %d" cnt))
9117 cnt)))
9119 (defun org-table-current-dline ()
9120 "Find out what table data line we are in.
9121 Only datalins count for this."
9122 (interactive)
9123 (if (interactive-p) (org-table-check-inside-data-field))
9124 (save-excursion
9125 (let ((cnt 0) (pos (point)))
9126 (goto-char (org-table-begin))
9127 (while (<= (point) pos)
9128 (if (looking-at org-table-dataline-regexp) (setq cnt (1+ cnt)))
9129 (beginning-of-line 2))
9130 (if (interactive-p) (message "This is table line %d" cnt))
9131 cnt)))
9133 (defun org-table-goto-column (n &optional on-delim force)
9134 "Move the cursor to the Nth column in the current table line.
9135 With optional argument ON-DELIM, stop with point before the left delimiter
9136 of the field.
9137 If there are less than N fields, just go to after the last delimiter.
9138 However, when FORCE is non-nil, create new columns if necessary."
9139 (interactive "p")
9140 (let ((pos (point-at-eol)))
9141 (beginning-of-line 1)
9142 (when (> n 0)
9143 (while (and (> (setq n (1- n)) -1)
9144 (or (search-forward "|" pos t)
9145 (and force
9146 (progn (end-of-line 1)
9147 (skip-chars-backward "^|")
9148 (insert " | "))))))
9149 ; (backward-char 2) t)))))
9150 (when (and force (not (looking-at ".*|")))
9151 (save-excursion (end-of-line 1) (insert " | ")))
9152 (if on-delim
9153 (backward-char 1)
9154 (if (looking-at " ") (forward-char 1))))))
9156 (defun org-at-table-p (&optional table-type)
9157 "Return t if the cursor is inside an org-type table.
9158 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9159 (if org-enable-table-editor
9160 (save-excursion
9161 (beginning-of-line 1)
9162 (looking-at (if table-type org-table-any-line-regexp
9163 org-table-line-regexp)))
9164 nil))
9166 (defun org-at-table.el-p ()
9167 "Return t if and only if we are at a table.el table."
9168 (and (org-at-table-p 'any)
9169 (save-excursion
9170 (goto-char (org-table-begin 'any))
9171 (looking-at org-table1-hline-regexp))))
9173 (defun org-table-recognize-table.el ()
9174 "If there is a table.el table nearby, recognize it and move into it."
9175 (if org-table-tab-recognizes-table.el
9176 (if (org-at-table.el-p)
9177 (progn
9178 (beginning-of-line 1)
9179 (if (looking-at org-table-dataline-regexp)
9181 (if (looking-at org-table1-hline-regexp)
9182 (progn
9183 (beginning-of-line 2)
9184 (if (looking-at org-table-any-border-regexp)
9185 (beginning-of-line -1)))))
9186 (if (re-search-forward "|" (org-table-end t) t)
9187 (progn
9188 (require 'table)
9189 (if (table--at-cell-p (point))
9191 (message "recognizing table.el table...")
9192 (table-recognize-table)
9193 (message "recognizing table.el table...done")))
9194 (error "This should not happen..."))
9196 nil)
9197 nil))
9199 (defun org-at-table-hline-p ()
9200 "Return t if the cursor is inside a hline in a table."
9201 (if org-enable-table-editor
9202 (save-excursion
9203 (beginning-of-line 1)
9204 (looking-at org-table-hline-regexp))
9205 nil))
9207 (defun org-table-insert-column ()
9208 "Insert a new column into the table."
9209 (interactive)
9210 (if (not (org-at-table-p))
9211 (error "Not at a table"))
9212 (org-table-find-dataline)
9213 (let* ((col (max 1 (org-table-current-column)))
9214 (beg (org-table-begin))
9215 (end (org-table-end))
9216 ;; Current cursor position
9217 (linepos (org-current-line))
9218 (colpos col))
9219 (goto-char beg)
9220 (while (< (point) end)
9221 (if (org-at-table-hline-p)
9223 (org-table-goto-column col t)
9224 (insert "| "))
9225 (beginning-of-line 2))
9226 (move-marker end nil)
9227 (goto-line linepos)
9228 (org-table-goto-column colpos)
9229 (org-table-align)
9230 (org-table-fix-formulas "$" nil (1- col) 1)))
9232 (defun org-table-find-dataline ()
9233 "Find a dataline in the current table, which is needed for column commands."
9234 (if (and (org-at-table-p)
9235 (not (org-at-table-hline-p)))
9237 (let ((col (current-column))
9238 (end (org-table-end)))
9239 (move-to-column col)
9240 (while (and (< (point) end)
9241 (or (not (= (current-column) col))
9242 (org-at-table-hline-p)))
9243 (beginning-of-line 2)
9244 (move-to-column col))
9245 (if (and (org-at-table-p)
9246 (not (org-at-table-hline-p)))
9248 (error
9249 "Please position cursor in a data line for column operations")))))
9251 (defun org-table-delete-column ()
9252 "Delete a column from the table."
9253 (interactive)
9254 (if (not (org-at-table-p))
9255 (error "Not at a table"))
9256 (org-table-find-dataline)
9257 (org-table-check-inside-data-field)
9258 (let* ((col (org-table-current-column))
9259 (beg (org-table-begin))
9260 (end (org-table-end))
9261 ;; Current cursor position
9262 (linepos (org-current-line))
9263 (colpos col))
9264 (goto-char beg)
9265 (while (< (point) end)
9266 (if (org-at-table-hline-p)
9268 (org-table-goto-column col t)
9269 (and (looking-at "|[^|\n]+|")
9270 (replace-match "|")))
9271 (beginning-of-line 2))
9272 (move-marker end nil)
9273 (goto-line linepos)
9274 (org-table-goto-column colpos)
9275 (org-table-align)
9276 (org-table-fix-formulas "$" (list (cons (number-to-string col) "INVALID"))
9277 col -1 col)))
9279 (defun org-table-move-column-right ()
9280 "Move column to the right."
9281 (interactive)
9282 (org-table-move-column nil))
9283 (defun org-table-move-column-left ()
9284 "Move column to the left."
9285 (interactive)
9286 (org-table-move-column 'left))
9288 (defun org-table-move-column (&optional left)
9289 "Move the current column to the right. With arg LEFT, move to the left."
9290 (interactive "P")
9291 (if (not (org-at-table-p))
9292 (error "Not at a table"))
9293 (org-table-find-dataline)
9294 (org-table-check-inside-data-field)
9295 (let* ((col (org-table-current-column))
9296 (col1 (if left (1- col) col))
9297 (beg (org-table-begin))
9298 (end (org-table-end))
9299 ;; Current cursor position
9300 (linepos (org-current-line))
9301 (colpos (if left (1- col) (1+ col))))
9302 (if (and left (= col 1))
9303 (error "Cannot move column further left"))
9304 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9305 (error "Cannot move column further right"))
9306 (goto-char beg)
9307 (while (< (point) end)
9308 (if (org-at-table-hline-p)
9310 (org-table-goto-column col1 t)
9311 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9312 (replace-match "|\\2|\\1|")))
9313 (beginning-of-line 2))
9314 (move-marker end nil)
9315 (goto-line linepos)
9316 (org-table-goto-column colpos)
9317 (org-table-align)
9318 (org-table-fix-formulas
9319 "$" (list (cons (number-to-string col) (number-to-string colpos))
9320 (cons (number-to-string colpos) (number-to-string col))))))
9322 (defun org-table-move-row-down ()
9323 "Move table row down."
9324 (interactive)
9325 (org-table-move-row nil))
9326 (defun org-table-move-row-up ()
9327 "Move table row up."
9328 (interactive)
9329 (org-table-move-row 'up))
9331 (defun org-table-move-row (&optional up)
9332 "Move the current table line down. With arg UP, move it up."
9333 (interactive "P")
9334 (let* ((col (current-column))
9335 (pos (point))
9336 (hline1p (save-excursion (beginning-of-line 1)
9337 (looking-at org-table-hline-regexp)))
9338 (dline1 (org-table-current-dline))
9339 (dline2 (+ dline1 (if up -1 1)))
9340 (tonew (if up 0 2))
9341 txt hline2p)
9342 (beginning-of-line tonew)
9343 (unless (org-at-table-p)
9344 (goto-char pos)
9345 (error "Cannot move row further"))
9346 (setq hline2p (looking-at org-table-hline-regexp))
9347 (goto-char pos)
9348 (beginning-of-line 1)
9349 (setq pos (point))
9350 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9351 (delete-region (point) (1+ (point-at-eol)))
9352 (beginning-of-line tonew)
9353 (insert txt)
9354 (beginning-of-line 0)
9355 (move-to-column col)
9356 (unless (or hline1p hline2p)
9357 (org-table-fix-formulas
9358 "@" (list (cons (number-to-string dline1) (number-to-string dline2))
9359 (cons (number-to-string dline2) (number-to-string dline1)))))))
9361 (defun org-table-insert-row (&optional arg)
9362 "Insert a new row above the current line into the table.
9363 With prefix ARG, insert below the current line."
9364 (interactive "P")
9365 (if (not (org-at-table-p))
9366 (error "Not at a table"))
9367 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9368 (new (org-table-clean-line line)))
9369 ;; Fix the first field if necessary
9370 (if (string-match "^[ \t]*| *[#$] *|" line)
9371 (setq new (replace-match (match-string 0 line) t t new)))
9372 (beginning-of-line (if arg 2 1))
9373 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9374 (beginning-of-line 0)
9375 (re-search-forward "| ?" (point-at-eol) t)
9376 (and (or org-table-may-need-update org-table-overlay-coordinates)
9377 (org-table-align))
9378 (org-table-fix-formulas "@" nil (1- (org-table-current-dline)) 1)))
9380 (defun org-table-insert-hline (&optional above)
9381 "Insert a horizontal-line below the current line into the table.
9382 With prefix ABOVE, insert above the current line."
9383 (interactive "P")
9384 (if (not (org-at-table-p))
9385 (error "Not at a table"))
9386 (let ((line (org-table-clean-line
9387 (buffer-substring (point-at-bol) (point-at-eol))))
9388 (col (current-column)))
9389 (while (string-match "|\\( +\\)|" line)
9390 (setq line (replace-match
9391 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9392 ?-) "|") t t line)))
9393 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9394 (beginning-of-line (if above 1 2))
9395 (insert line "\n")
9396 (beginning-of-line (if above 1 -1))
9397 (move-to-column col)
9398 (and org-table-overlay-coordinates (org-table-align))))
9400 (defun org-table-hline-and-move (&optional same-column)
9401 "Insert a hline and move to the row below that line."
9402 (interactive "P")
9403 (let ((col (org-table-current-column)))
9404 (org-table-maybe-eval-formula)
9405 (org-table-maybe-recalculate-line)
9406 (org-table-insert-hline)
9407 (end-of-line 2)
9408 (if (looking-at "\n[ \t]*|-")
9409 (progn (insert "\n|") (org-table-align))
9410 (org-table-next-field))
9411 (if same-column (org-table-goto-column col))))
9413 (defun org-table-clean-line (s)
9414 "Convert a table line S into a string with only \"|\" and space.
9415 In particular, this does handle wide and invisible characters."
9416 (if (string-match "^[ \t]*|-" s)
9417 ;; It's a hline, just map the characters
9418 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
9419 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9420 (setq s (replace-match
9421 (concat "|" (make-string (org-string-width (match-string 1 s))
9422 ?\ ) "|")
9423 t t s)))
9426 (defun org-table-kill-row ()
9427 "Delete the current row or horizontal line from the table."
9428 (interactive)
9429 (if (not (org-at-table-p))
9430 (error "Not at a table"))
9431 (let ((col (current-column))
9432 (dline (org-table-current-dline)))
9433 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9434 (if (not (org-at-table-p)) (beginning-of-line 0))
9435 (move-to-column col)
9436 (org-table-fix-formulas "@" (list (cons (number-to-string dline) "INVALID"))
9437 dline -1 dline)))
9439 (defun org-table-sort-lines (with-case &optional sorting-type)
9440 "Sort table lines according to the column at point.
9442 The position of point indicates the column to be used for
9443 sorting, and the range of lines is the range between the nearest
9444 horizontal separator lines, or the entire table of no such lines
9445 exist. If point is before the first column, you will be prompted
9446 for the sorting column. If there is an active region, the mark
9447 specifies the first line and the sorting column, while point
9448 should be in the last line to be included into the sorting.
9450 The command then prompts for the sorting type which can be
9451 alphabetically, numerically, or by time (as given in a time stamp
9452 in the field). Sorting in reverse order is also possible.
9454 With prefix argument WITH-CASE, alphabetic sorting will be case-sensitive.
9456 If SORTING-TYPE is specified when this function is called from a Lisp
9457 program, no prompting will take place. SORTING-TYPE must be a character,
9458 any of (?a ?A ?n ?N ?t ?T) where the capital letter indicate that sorting
9459 should be done in reverse order."
9460 (interactive "P")
9461 (let* ((thisline (org-current-line))
9462 (thiscol (org-table-current-column))
9463 beg end bcol ecol tend tbeg column lns pos)
9464 (when (equal thiscol 0)
9465 (if (interactive-p)
9466 (setq thiscol
9467 (string-to-number
9468 (read-string "Use column N for sorting: ")))
9469 (setq thiscol 1))
9470 (org-table-goto-column thiscol))
9471 (org-table-check-inside-data-field)
9472 (if (org-region-active-p)
9473 (progn
9474 (setq beg (region-beginning) end (region-end))
9475 (goto-char beg)
9476 (setq column (org-table-current-column)
9477 beg (point-at-bol))
9478 (goto-char end)
9479 (setq end (point-at-bol 2)))
9480 (setq column (org-table-current-column)
9481 pos (point)
9482 tbeg (org-table-begin)
9483 tend (org-table-end))
9484 (if (re-search-backward org-table-hline-regexp tbeg t)
9485 (setq beg (point-at-bol 2))
9486 (goto-char tbeg)
9487 (setq beg (point-at-bol 1)))
9488 (goto-char pos)
9489 (if (re-search-forward org-table-hline-regexp tend t)
9490 (setq end (point-at-bol 1))
9491 (goto-char tend)
9492 (setq end (point-at-bol))))
9493 (setq beg (move-marker (make-marker) beg)
9494 end (move-marker (make-marker) end))
9495 (untabify beg end)
9496 (goto-char beg)
9497 (org-table-goto-column column)
9498 (skip-chars-backward "^|")
9499 (setq bcol (current-column))
9500 (org-table-goto-column (1+ column))
9501 (skip-chars-backward "^|")
9502 (setq ecol (1- (current-column)))
9503 (org-table-goto-column column)
9504 (setq lns (mapcar (lambda(x) (cons
9505 (org-sort-remove-invisible
9506 (nth (1- column)
9507 (org-split-string x "[ \t]*|[ \t]*")))
9509 (org-split-string (buffer-substring beg end) "\n")))
9510 (setq lns (org-do-sort lns "Table" with-case sorting-type))
9511 (delete-region beg end)
9512 (move-marker beg nil)
9513 (move-marker end nil)
9514 (insert (mapconcat 'cdr lns "\n") "\n")
9515 (goto-line thisline)
9516 (org-table-goto-column thiscol)
9517 (message "%d lines sorted, based on column %d" (length lns) column)))
9519 ;; FIXME: maybe we will not need this? Table sorting is broken....
9520 (defun org-sort-remove-invisible (s)
9521 (remove-text-properties 0 (length s) org-rm-props s)
9522 (while (string-match org-bracket-link-regexp s)
9523 (setq s (replace-match (if (match-end 2)
9524 (match-string 3 s)
9525 (match-string 1 s)) t t s)))
9528 (defun org-table-cut-region (beg end)
9529 "Copy region in table to the clipboard and blank all relevant fields."
9530 (interactive "r")
9531 (org-table-copy-region beg end 'cut))
9533 (defun org-table-copy-region (beg end &optional cut)
9534 "Copy rectangular region in table to clipboard.
9535 A special clipboard is used which can only be accessed
9536 with `org-table-paste-rectangle'."
9537 (interactive "rP")
9538 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9539 region cols
9540 (rpl (if cut " " nil)))
9541 (goto-char beg)
9542 (org-table-check-inside-data-field)
9543 (setq l01 (org-current-line)
9544 c01 (org-table-current-column))
9545 (goto-char end)
9546 (org-table-check-inside-data-field)
9547 (setq l02 (org-current-line)
9548 c02 (org-table-current-column))
9549 (setq l1 (min l01 l02) l2 (max l01 l02)
9550 c1 (min c01 c02) c2 (max c01 c02))
9551 (catch 'exit
9552 (while t
9553 (catch 'nextline
9554 (if (> l1 l2) (throw 'exit t))
9555 (goto-line l1)
9556 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9557 (setq cols nil ic1 c1 ic2 c2)
9558 (while (< ic1 (1+ ic2))
9559 (push (org-table-get-field ic1 rpl) cols)
9560 (setq ic1 (1+ ic1)))
9561 (push (nreverse cols) region)
9562 (setq l1 (1+ l1)))))
9563 (setq org-table-clip (nreverse region))
9564 (if cut (org-table-align))
9565 org-table-clip))
9567 (defun org-table-paste-rectangle ()
9568 "Paste a rectangular region into a table.
9569 The upper right corner ends up in the current field. All involved fields
9570 will be overwritten. If the rectangle does not fit into the present table,
9571 the table is enlarged as needed. The process ignores horizontal separator
9572 lines."
9573 (interactive)
9574 (unless (and org-table-clip (listp org-table-clip))
9575 (error "First cut/copy a region to paste!"))
9576 (org-table-check-inside-data-field)
9577 (let* ((clip org-table-clip)
9578 (line (org-current-line))
9579 (col (org-table-current-column))
9580 (org-enable-table-editor t)
9581 (org-table-automatic-realign nil)
9582 c cols field)
9583 (while (setq cols (pop clip))
9584 (while (org-at-table-hline-p) (beginning-of-line 2))
9585 (if (not (org-at-table-p))
9586 (progn (end-of-line 0) (org-table-next-field)))
9587 (setq c col)
9588 (while (setq field (pop cols))
9589 (org-table-goto-column c nil 'force)
9590 (org-table-get-field nil field)
9591 (setq c (1+ c)))
9592 (beginning-of-line 2))
9593 (goto-line line)
9594 (org-table-goto-column col)
9595 (org-table-align)))
9597 (defun org-table-convert ()
9598 "Convert from `org-mode' table to table.el and back.
9599 Obviously, this only works within limits. When an Org-mode table is
9600 converted to table.el, all horizontal separator lines get lost, because
9601 table.el uses these as cell boundaries and has no notion of horizontal lines.
9602 A table.el table can be converted to an Org-mode table only if it does not
9603 do row or column spanning. Multiline cells will become multiple cells.
9604 Beware, Org-mode does not test if the table can be successfully converted - it
9605 blindly applies a recipe that works for simple tables."
9606 (interactive)
9607 (require 'table)
9608 (if (org-at-table.el-p)
9609 ;; convert to Org-mode table
9610 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9611 (end (move-marker (make-marker) (org-table-end t))))
9612 (table-unrecognize-region beg end)
9613 (goto-char beg)
9614 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9615 (replace-match ""))
9616 (goto-char beg))
9617 (if (org-at-table-p)
9618 ;; convert to table.el table
9619 (let ((beg (move-marker (make-marker) (org-table-begin)))
9620 (end (move-marker (make-marker) (org-table-end))))
9621 ;; first, get rid of all horizontal lines
9622 (goto-char beg)
9623 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9624 (replace-match ""))
9625 ;; insert a hline before first
9626 (goto-char beg)
9627 (org-table-insert-hline 'above)
9628 (beginning-of-line -1)
9629 ;; insert a hline after each line
9630 (while (progn (beginning-of-line 3) (< (point) end))
9631 (org-table-insert-hline))
9632 (goto-char beg)
9633 (setq end (move-marker end (org-table-end)))
9634 ;; replace "+" at beginning and ending of hlines
9635 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9636 (replace-match "\\1+-"))
9637 (goto-char beg)
9638 (while (re-search-forward "-|[ \t]*$" end t)
9639 (replace-match "-+"))
9640 (goto-char beg)))))
9642 (defun org-table-wrap-region (arg)
9643 "Wrap several fields in a column like a paragraph.
9644 This is useful if you'd like to spread the contents of a field over several
9645 lines, in order to keep the table compact.
9647 If there is an active region, and both point and mark are in the same column,
9648 the text in the column is wrapped to minimum width for the given number of
9649 lines. Generally, this makes the table more compact. A prefix ARG may be
9650 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9651 formats the selected text to two lines. If the region was longer than two
9652 lines, the remaining lines remain empty. A negative prefix argument reduces
9653 the current number of lines by that amount. The wrapped text is pasted back
9654 into the table. If you formatted it to more lines than it was before, fields
9655 further down in the table get overwritten - so you might need to make space in
9656 the table first.
9658 If there is no region, the current field is split at the cursor position and
9659 the text fragment to the right of the cursor is prepended to the field one
9660 line down.
9662 If there is no region, but you specify a prefix ARG, the current field gets
9663 blank, and the content is appended to the field above."
9664 (interactive "P")
9665 (org-table-check-inside-data-field)
9666 (if (org-region-active-p)
9667 ;; There is a region: fill as a paragraph
9668 (let* ((beg (region-beginning))
9669 (cline (save-excursion (goto-char beg) (org-current-line)))
9670 (ccol (save-excursion (goto-char beg) (org-table-current-column)))
9671 nlines)
9672 (org-table-cut-region (region-beginning) (region-end))
9673 (if (> (length (car org-table-clip)) 1)
9674 (error "Region must be limited to single column"))
9675 (setq nlines (if arg
9676 (if (< arg 1)
9677 (+ (length org-table-clip) arg)
9678 arg)
9679 (length org-table-clip)))
9680 (setq org-table-clip
9681 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9682 nil nlines)))
9683 (goto-line cline)
9684 (org-table-goto-column ccol)
9685 (org-table-paste-rectangle))
9686 ;; No region, split the current field at point
9687 (unless (org-get-alist-option org-M-RET-may-split-line 'table)
9688 (skip-chars-forward "^\r\n|"))
9689 (if arg
9690 ;; combine with field above
9691 (let ((s (org-table-blank-field))
9692 (col (org-table-current-column)))
9693 (beginning-of-line 0)
9694 (while (org-at-table-hline-p) (beginning-of-line 0))
9695 (org-table-goto-column col)
9696 (skip-chars-forward "^|")
9697 (skip-chars-backward " ")
9698 (insert " " (org-trim s))
9699 (org-table-align))
9700 ;; split field
9701 (if (looking-at "\\([^|]+\\)+|")
9702 (let ((s (match-string 1)))
9703 (replace-match " |")
9704 (goto-char (match-beginning 0))
9705 (org-table-next-row)
9706 (insert (org-trim s) " ")
9707 (org-table-align))
9708 (org-table-next-row)))))
9710 (defvar org-field-marker nil)
9712 (defun org-table-edit-field (arg)
9713 "Edit table field in a different window.
9714 This is mainly useful for fields that contain hidden parts.
9715 When called with a \\[universal-argument] prefix, just make the full field visible so that
9716 it can be edited in place."
9717 (interactive "P")
9718 (if arg
9719 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9720 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9721 (remove-text-properties b e '(org-cwidth t invisible t
9722 display t intangible t))
9723 (if (and (boundp 'font-lock-mode) font-lock-mode)
9724 (font-lock-fontify-block)))
9725 (let ((pos (move-marker (make-marker) (point)))
9726 (field (org-table-get-field))
9727 (cw (current-window-configuration))
9729 (org-switch-to-buffer-other-window "*Org tmp*")
9730 (erase-buffer)
9731 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9732 (let ((org-inhibit-startup t)) (org-mode))
9733 (goto-char (setq p (point-max)))
9734 (insert (org-trim field))
9735 (remove-text-properties p (point-max)
9736 '(invisible t org-cwidth t display t
9737 intangible t))
9738 (goto-char p)
9739 (org-set-local 'org-finish-function 'org-table-finish-edit-field)
9740 (org-set-local 'org-window-configuration cw)
9741 (org-set-local 'org-field-marker pos)
9742 (message "Edit and finish with C-c C-c"))))
9744 (defun org-table-finish-edit-field ()
9745 "Finish editing a table data field.
9746 Remove all newline characters, insert the result into the table, realign
9747 the table and kill the editing buffer."
9748 (let ((pos org-field-marker)
9749 (cw org-window-configuration)
9750 (cb (current-buffer))
9751 text)
9752 (goto-char (point-min))
9753 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9754 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9755 (replace-match " "))
9756 (setq text (org-trim (buffer-string)))
9757 (set-window-configuration cw)
9758 (kill-buffer cb)
9759 (select-window (get-buffer-window (marker-buffer pos)))
9760 (goto-char pos)
9761 (move-marker pos nil)
9762 (org-table-check-inside-data-field)
9763 (org-table-get-field nil text)
9764 (org-table-align)
9765 (message "New field value inserted")))
9767 (defun org-trim (s)
9768 "Remove whitespace at beginning and end of string."
9769 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
9770 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
9773 (defun org-wrap (string &optional width lines)
9774 "Wrap string to either a number of lines, or a width in characters.
9775 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9776 that costs. If there is a word longer than WIDTH, the text is actually
9777 wrapped to the length of that word.
9778 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9779 many lines, whatever width that takes.
9780 The return value is a list of lines, without newlines at the end."
9781 (let* ((words (org-split-string string "[ \t\n]+"))
9782 (maxword (apply 'max (mapcar 'org-string-width words)))
9783 w ll)
9784 (cond (width
9785 (org-do-wrap words (max maxword width)))
9786 (lines
9787 (setq w maxword)
9788 (setq ll (org-do-wrap words maxword))
9789 (if (<= (length ll) lines)
9791 (setq ll words)
9792 (while (> (length ll) lines)
9793 (setq w (1+ w))
9794 (setq ll (org-do-wrap words w)))
9795 ll))
9796 (t (error "Cannot wrap this")))))
9799 (defun org-do-wrap (words width)
9800 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9801 (let (lines line)
9802 (while words
9803 (setq line (pop words))
9804 (while (and words (< (+ (length line) (length (car words))) width))
9805 (setq line (concat line " " (pop words))))
9806 (setq lines (push line lines)))
9807 (nreverse lines)))
9809 (defun org-split-string (string &optional separators)
9810 "Splits STRING into substrings at SEPARATORS.
9811 No empty strings are returned if there are matches at the beginning
9812 and end of string."
9813 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9814 (start 0)
9815 notfirst
9816 (list nil))
9817 (while (and (string-match rexp string
9818 (if (and notfirst
9819 (= start (match-beginning 0))
9820 (< start (length string)))
9821 (1+ start) start))
9822 (< (match-beginning 0) (length string)))
9823 (setq notfirst t)
9824 (or (eq (match-beginning 0) 0)
9825 (and (eq (match-beginning 0) (match-end 0))
9826 (eq (match-beginning 0) start))
9827 (setq list
9828 (cons (substring string start (match-beginning 0))
9829 list)))
9830 (setq start (match-end 0)))
9831 (or (eq start (length string))
9832 (setq list
9833 (cons (substring string start)
9834 list)))
9835 (nreverse list)))
9837 (defun org-table-map-tables (function)
9838 "Apply FUNCTION to the start of all tables in the buffer."
9839 (save-excursion
9840 (save-restriction
9841 (widen)
9842 (goto-char (point-min))
9843 (while (re-search-forward org-table-any-line-regexp nil t)
9844 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9845 (beginning-of-line 1)
9846 (if (looking-at org-table-line-regexp)
9847 (save-excursion (funcall function)))
9848 (re-search-forward org-table-any-border-regexp nil 1))))
9849 (message "Mapping tables: done"))
9851 (defvar org-timecnt) ; dynamically scoped parameter
9853 (defun org-table-sum (&optional beg end nlast)
9854 "Sum numbers in region of current table column.
9855 The result will be displayed in the echo area, and will be available
9856 as kill to be inserted with \\[yank].
9858 If there is an active region, it is interpreted as a rectangle and all
9859 numbers in that rectangle will be summed. If there is no active
9860 region and point is located in a table column, sum all numbers in that
9861 column.
9863 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9864 numbers are assumed to be times as well (in decimal hours) and the
9865 numbers are added as such.
9867 If NLAST is a number, only the NLAST fields will actually be summed."
9868 (interactive)
9869 (save-excursion
9870 (let (col (org-timecnt 0) diff h m s org-table-clip)
9871 (cond
9872 ((and beg end)) ; beg and end given explicitly
9873 ((org-region-active-p)
9874 (setq beg (region-beginning) end (region-end)))
9876 (setq col (org-table-current-column))
9877 (goto-char (org-table-begin))
9878 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9879 (error "No table data"))
9880 (org-table-goto-column col)
9881 (setq beg (point))
9882 (goto-char (org-table-end))
9883 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9884 (error "No table data"))
9885 (org-table-goto-column col)
9886 (setq end (point))))
9887 (let* ((items (apply 'append (org-table-copy-region beg end)))
9888 (items1 (cond ((not nlast) items)
9889 ((>= nlast (length items)) items)
9890 (t (setq items (reverse items))
9891 (setcdr (nthcdr (1- nlast) items) nil)
9892 (nreverse items))))
9893 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9894 items1)))
9895 (res (apply '+ numbers))
9896 (sres (if (= org-timecnt 0)
9897 (format "%g" res)
9898 (setq diff (* 3600 res)
9899 h (floor (/ diff 3600)) diff (mod diff 3600)
9900 m (floor (/ diff 60)) diff (mod diff 60)
9901 s diff)
9902 (format "%d:%02d:%02d" h m s))))
9903 (kill-new sres)
9904 (if (interactive-p)
9905 (message "%s"
9906 (substitute-command-keys
9907 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9908 (length numbers) sres))))
9909 sres))))
9911 (defun org-table-get-number-for-summing (s)
9912 (let (n)
9913 (if (string-match "^ *|? *" s)
9914 (setq s (replace-match "" nil nil s)))
9915 (if (string-match " *|? *$" s)
9916 (setq s (replace-match "" nil nil s)))
9917 (setq n (string-to-number s))
9918 (cond
9919 ((and (string-match "0" s)
9920 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9921 ((string-match "\\`[ \t]+\\'" s) nil)
9922 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9923 (let ((h (string-to-number (or (match-string 1 s) "0")))
9924 (m (string-to-number (or (match-string 2 s) "0")))
9925 (s (string-to-number (or (match-string 4 s) "0"))))
9926 (if (boundp 'org-timecnt) (setq org-timecnt (1+ org-timecnt)))
9927 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9928 ((equal n 0) nil)
9929 (t n))))
9931 (defun org-table-current-field-formula (&optional key noerror)
9932 "Return the formula active for the current field.
9933 Assumes that specials are in place.
9934 If KEY is given, return the key to this formula.
9935 Otherwise return the formula preceeded with \"=\" or \":=\"."
9936 (let* ((name (car (rassoc (list (org-current-line)
9937 (org-table-current-column))
9938 org-table-named-field-locations)))
9939 (col (org-table-current-column))
9940 (scol (int-to-string col))
9941 (ref (format "@%d$%d" (org-table-current-dline) col))
9942 (stored-list (org-table-get-stored-formulas noerror))
9943 (ass (or (assoc name stored-list)
9944 (assoc ref stored-list)
9945 (assoc scol stored-list))))
9946 (if key
9947 (car ass)
9948 (if ass (concat (if (string-match "^[0-9]+$" (car ass)) "=" ":=")
9949 (cdr ass))))))
9951 (defun org-table-get-formula (&optional equation named)
9952 "Read a formula from the minibuffer, offer stored formula as default.
9953 When NAMED is non-nil, look for a named equation."
9954 (let* ((stored-list (org-table-get-stored-formulas))
9955 (name (car (rassoc (list (org-current-line)
9956 (org-table-current-column))
9957 org-table-named-field-locations)))
9958 (ref (format "@%d$%d" (org-table-current-dline)
9959 (org-table-current-column)))
9960 (refass (assoc ref stored-list))
9961 (scol (if named
9962 (if name name ref)
9963 (int-to-string (org-table-current-column))))
9964 (dummy (and (or name refass) (not named)
9965 (not (y-or-n-p "Replace field formula with column formula? " ))
9966 (error "Abort")))
9967 (name (or name ref))
9968 (org-table-may-need-update nil)
9969 (stored (cdr (assoc scol stored-list)))
9970 (eq (cond
9971 ((and stored equation (string-match "^ *=? *$" equation))
9972 stored)
9973 ((stringp equation)
9974 equation)
9975 (t (org-table-formula-from-user
9976 (read-string
9977 (org-table-formula-to-user
9978 (format "%s formula %s%s="
9979 (if named "Field" "Column")
9980 (if (member (string-to-char scol) '(?$ ?@)) "" "$")
9981 scol))
9982 (if stored (org-table-formula-to-user stored) "")
9983 'org-table-formula-history
9984 )))))
9985 mustsave)
9986 (when (not (string-match "\\S-" eq))
9987 ;; remove formula
9988 (setq stored-list (delq (assoc scol stored-list) stored-list))
9989 (org-table-store-formulas stored-list)
9990 (error "Formula removed"))
9991 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9992 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9993 (if (and name (not named))
9994 ;; We set the column equation, delete the named one.
9995 (setq stored-list (delq (assoc name stored-list) stored-list)
9996 mustsave t))
9997 (if stored
9998 (setcdr (assoc scol stored-list) eq)
9999 (setq stored-list (cons (cons scol eq) stored-list)))
10000 (if (or mustsave (not (equal stored eq)))
10001 (org-table-store-formulas stored-list))
10002 eq))
10004 (defun org-table-store-formulas (alist)
10005 "Store the list of formulas below the current table."
10006 (setq alist (sort alist 'org-table-formula-less-p))
10007 (save-excursion
10008 (goto-char (org-table-end))
10009 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:\\(.*\n?\\)")
10010 (progn
10011 ;; don't overwrite TBLFM, we might use text properties to store stuff
10012 (goto-char (match-beginning 2))
10013 (delete-region (match-beginning 2) (match-end 0)))
10014 (insert "#+TBLFM:"))
10015 (insert " "
10016 (mapconcat (lambda (x)
10017 (concat
10018 (if (equal (string-to-char (car x)) ?@) "" "$")
10019 (car x) "=" (cdr x)))
10020 alist "::")
10021 "\n")))
10023 (defsubst org-table-formula-make-cmp-string (a)
10024 (when (string-match "^\\(@\\([0-9]+\\)\\)?\\(\\$?\\([0-9]+\\)\\)?\\(\\$?[a-zA-Z0-9]+\\)?" a)
10025 (concat
10026 (if (match-end 2) (format "@%05d" (string-to-number (match-string 2 a))) "")
10027 (if (match-end 4) (format "$%05d" (string-to-number (match-string 4 a))) "")
10028 (if (match-end 5) (concat "@@" (match-string 5 a))))))
10030 (defun org-table-formula-less-p (a b)
10031 "Compare two formulas for sorting."
10032 (let ((as (org-table-formula-make-cmp-string (car a)))
10033 (bs (org-table-formula-make-cmp-string (car b))))
10034 (and as bs (string< as bs))))
10036 (defun org-table-get-stored-formulas (&optional noerror)
10037 "Return an alist with the stored formulas directly after current table."
10038 (interactive)
10039 (let (scol eq eq-alist strings string seen)
10040 (save-excursion
10041 (goto-char (org-table-end))
10042 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10043 (setq strings (org-split-string (match-string 2) " *:: *"))
10044 (while (setq string (pop strings))
10045 (when (string-match "\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*[^ \t]\\)" string)
10046 (setq scol (if (match-end 2)
10047 (match-string 2 string)
10048 (match-string 1 string))
10049 eq (match-string 3 string)
10050 eq-alist (cons (cons scol eq) eq-alist))
10051 (if (member scol seen)
10052 (if noerror
10053 (progn
10054 (message "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10055 (ding)
10056 (sit-for 2))
10057 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol))
10058 (push scol seen))))))
10059 (nreverse eq-alist)))
10061 (defun org-table-fix-formulas (key replace &optional limit delta remove)
10062 "Modify the equations after the table structure has been edited.
10063 KEY is \"@\" or \"$\". REPLACE is an alist of numbers to replace.
10064 For all numbers larger than LIMIT, shift them by DELTA."
10065 (save-excursion
10066 (goto-char (org-table-end))
10067 (when (looking-at "#\\+TBLFM:")
10068 (let ((re (concat key "\\([0-9]+\\)"))
10069 (re2
10070 (when remove
10071 (if (equal key "$")
10072 (format "\\(@[0-9]+\\)?\\$%d=.*?\\(::\\|$\\)" remove)
10073 (format "@%d\\$[0-9]+=.*?\\(::\\|$\\)" remove))))
10074 s n a)
10075 (when remove
10076 (while (re-search-forward re2 (point-at-eol) t)
10077 (replace-match "")))
10078 (while (re-search-forward re (point-at-eol) t)
10079 (setq s (match-string 1) n (string-to-number s))
10080 (cond
10081 ((setq a (assoc s replace))
10082 (replace-match (concat key (cdr a)) t t))
10083 ((and limit (> n limit))
10084 (replace-match (concat key (int-to-string (+ n delta))) t t))))))))
10086 (defun org-table-get-specials ()
10087 "Get the column names and local parameters for this table."
10088 (save-excursion
10089 (let ((beg (org-table-begin)) (end (org-table-end))
10090 names name fields fields1 field cnt
10091 c v l line col types dlines hlines)
10092 (setq org-table-column-names nil
10093 org-table-local-parameters nil
10094 org-table-named-field-locations nil
10095 org-table-current-begin-line nil
10096 org-table-current-begin-pos nil
10097 org-table-current-line-types nil)
10098 (goto-char beg)
10099 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10100 (setq names (org-split-string (match-string 1) " *| *")
10101 cnt 1)
10102 (while (setq name (pop names))
10103 (setq cnt (1+ cnt))
10104 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10105 (push (cons name (int-to-string cnt)) org-table-column-names))))
10106 (setq org-table-column-names (nreverse org-table-column-names))
10107 (setq org-table-column-name-regexp
10108 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10109 (goto-char beg)
10110 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10111 (setq fields (org-split-string (match-string 1) " *| *"))
10112 (while (setq field (pop fields))
10113 (if (string-match "^\\([a-zA-Z][_a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10114 (push (cons (match-string 1 field) (match-string 2 field))
10115 org-table-local-parameters))))
10116 (goto-char beg)
10117 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10118 (setq c (match-string 1)
10119 fields (org-split-string (match-string 2) " *| *"))
10120 (save-excursion
10121 (beginning-of-line (if (equal c "_") 2 0))
10122 (setq line (org-current-line) col 1)
10123 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10124 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10125 (while (and fields1 (setq field (pop fields)))
10126 (setq v (pop fields1) col (1+ col))
10127 (when (and (stringp field) (stringp v)
10128 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10129 (push (cons field v) org-table-local-parameters)
10130 (push (list field line col) org-table-named-field-locations))))
10131 ;; Analyse the line types
10132 (goto-char beg)
10133 (setq org-table-current-begin-line (org-current-line)
10134 org-table-current-begin-pos (point)
10135 l org-table-current-begin-line)
10136 (while (looking-at "[ \t]*|\\(-\\)?")
10137 (push (if (match-end 1) 'hline 'dline) types)
10138 (if (match-end 1) (push l hlines) (push l dlines))
10139 (beginning-of-line 2)
10140 (setq l (1+ l)))
10141 (setq org-table-current-line-types (apply 'vector (nreverse types))
10142 org-table-dlines (apply 'vector (cons nil (nreverse dlines)))
10143 org-table-hlines (apply 'vector (cons nil (nreverse hlines)))))))
10145 (defun org-table-maybe-eval-formula ()
10146 "Check if the current field starts with \"=\" or \":=\".
10147 If yes, store the formula and apply it."
10148 ;; We already know we are in a table. Get field will only return a formula
10149 ;; when appropriate. It might return a separator line, but no problem.
10150 (when org-table-formula-evaluate-inline
10151 (let* ((field (org-trim (or (org-table-get-field) "")))
10152 named eq)
10153 (when (string-match "^:?=\\(.*\\)" field)
10154 (setq named (equal (string-to-char field) ?:)
10155 eq (match-string 1 field))
10156 (if (or (fboundp 'calc-eval)
10157 (equal (substring eq 0 (min 2 (length eq))) "'("))
10158 (org-table-eval-formula (if named '(4) nil)
10159 (org-table-formula-from-user eq))
10160 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))))))
10162 (defvar org-recalc-commands nil
10163 "List of commands triggering the recalculation of a line.
10164 Will be filled automatically during use.")
10166 (defvar org-recalc-marks
10167 '((" " . "Unmarked: no special line, no automatic recalculation")
10168 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10169 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10170 ("!" . "Column name definition line. Reference in formula as $name.")
10171 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10172 ("_" . "Names for values in row below this one.")
10173 ("^" . "Names for values in row above this one.")))
10175 (defun org-table-rotate-recalc-marks (&optional newchar)
10176 "Rotate the recalculation mark in the first column.
10177 If in any row, the first field is not consistent with a mark,
10178 insert a new column for the markers.
10179 When there is an active region, change all the lines in the region,
10180 after prompting for the marking character.
10181 After each change, a message will be displayed indicating the meaning
10182 of the new mark."
10183 (interactive)
10184 (unless (org-at-table-p) (error "Not at a table"))
10185 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10186 (beg (org-table-begin))
10187 (end (org-table-end))
10188 (l (org-current-line))
10189 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10190 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10191 (have-col
10192 (save-excursion
10193 (goto-char beg)
10194 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10195 (col (org-table-current-column))
10196 (forcenew (car (assoc newchar org-recalc-marks)))
10197 epos new)
10198 (when l1
10199 (message "Change region to what mark? Type # * ! $ or SPC: ")
10200 (setq newchar (char-to-string (read-char-exclusive))
10201 forcenew (car (assoc newchar org-recalc-marks))))
10202 (if (and newchar (not forcenew))
10203 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10204 newchar))
10205 (if l1 (goto-line l1))
10206 (save-excursion
10207 (beginning-of-line 1)
10208 (unless (looking-at org-table-dataline-regexp)
10209 (error "Not at a table data line")))
10210 (unless have-col
10211 (org-table-goto-column 1)
10212 (org-table-insert-column)
10213 (org-table-goto-column (1+ col)))
10214 (setq epos (point-at-eol))
10215 (save-excursion
10216 (beginning-of-line 1)
10217 (org-table-get-field
10218 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10219 (concat " "
10220 (setq new (or forcenew
10221 (cadr (member (match-string 1) marks))))
10222 " ")
10223 " # ")))
10224 (if (and l1 l2)
10225 (progn
10226 (goto-line l1)
10227 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10228 (and (looking-at org-table-dataline-regexp)
10229 (org-table-get-field 1 (concat " " new " "))))
10230 (goto-line l1)))
10231 (if (not (= epos (point-at-eol))) (org-table-align))
10232 (goto-line l)
10233 (and (interactive-p) (message "%s" (cdr (assoc new org-recalc-marks))))))
10235 (defun org-table-maybe-recalculate-line ()
10236 "Recompute the current line if marked for it, and if we haven't just done it."
10237 (interactive)
10238 (and org-table-allow-automatic-line-recalculation
10239 (not (and (memq last-command org-recalc-commands)
10240 (equal org-last-recalc-line (org-current-line))))
10241 (save-excursion (beginning-of-line 1)
10242 (looking-at org-table-auto-recalculate-regexp))
10243 (org-table-recalculate) t))
10245 (defvar org-table-formula-debug nil
10246 "Non-nil means, debug table formulas.
10247 When nil, simply write \"#ERROR\" in corrupted fields.")
10248 (make-variable-buffer-local 'org-table-formula-debug)
10250 (defvar modes)
10251 (defsubst org-set-calc-mode (var &optional value)
10252 (if (stringp var)
10253 (setq var (assoc var '(("D" calc-angle-mode deg)
10254 ("R" calc-angle-mode rad)
10255 ("F" calc-prefer-frac t)
10256 ("S" calc-symbolic-mode t)))
10257 value (nth 2 var) var (nth 1 var)))
10258 (if (memq var modes)
10259 (setcar (cdr (memq var modes)) value)
10260 (cons var (cons value modes)))
10261 modes)
10263 (defun org-table-eval-formula (&optional arg equation
10264 suppress-align suppress-const
10265 suppress-store suppress-analysis)
10266 "Replace the table field value at the cursor by the result of a calculation.
10268 This function makes use of Dave Gillespie's Calc package, in my view the
10269 most exciting program ever written for GNU Emacs. So you need to have Calc
10270 installed in order to use this function.
10272 In a table, this command replaces the value in the current field with the
10273 result of a formula. It also installs the formula as the \"current\" column
10274 formula, by storing it in a special line below the table. When called
10275 with a `C-u' prefix, the current field must ba a named field, and the
10276 formula is installed as valid in only this specific field.
10278 When called with two `C-u' prefixes, insert the active equation
10279 for the field back into the current field, so that it can be
10280 edited there. This is useful in order to use \\[org-table-show-reference]
10281 to check the referenced fields.
10283 When called, the command first prompts for a formula, which is read in
10284 the minibuffer. Previously entered formulas are available through the
10285 history list, and the last used formula is offered as a default.
10286 These stored formulas are adapted correctly when moving, inserting, or
10287 deleting columns with the corresponding commands.
10289 The formula can be any algebraic expression understood by the Calc package.
10290 For details, see the Org-mode manual.
10292 This function can also be called from Lisp programs and offers
10293 additional arguments: EQUATION can be the formula to apply. If this
10294 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10295 used to speed-up recursive calls by by-passing unnecessary aligns.
10296 SUPPRESS-CONST suppresses the interpretation of constants in the
10297 formula, assuming that this has been done already outside the function.
10298 SUPPRESS-STORE means the formula should not be stored, either because
10299 it is already stored, or because it is a modified equation that should
10300 not overwrite the stored one."
10301 (interactive "P")
10302 (org-table-check-inside-data-field)
10303 (or suppress-analysis (org-table-get-specials))
10304 (if (equal arg '(16))
10305 (let ((eq (org-table-current-field-formula)))
10306 (or eq (error "No equation active for current field"))
10307 (org-table-get-field nil eq)
10308 (org-table-align)
10309 (setq org-table-may-need-update t))
10310 (let* (fields
10311 (ndown (if (integerp arg) arg 1))
10312 (org-table-automatic-realign nil)
10313 (case-fold-search nil)
10314 (down (> ndown 1))
10315 (formula (if (and equation suppress-store)
10316 equation
10317 (org-table-get-formula equation (equal arg '(4)))))
10318 (n0 (org-table-current-column))
10319 (modes (copy-sequence org-calc-default-modes))
10320 (numbers nil) ; was a variable, now fixed default
10321 (keep-empty nil)
10322 n form form0 bw fmt x ev orig c lispp literal)
10323 ;; Parse the format string. Since we have a lot of modes, this is
10324 ;; a lot of work. However, I think calc still uses most of the time.
10325 (if (string-match ";" formula)
10326 (let ((tmp (org-split-string formula ";")))
10327 (setq formula (car tmp)
10328 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10329 (nth 1 tmp)))
10330 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
10331 (setq c (string-to-char (match-string 1 fmt))
10332 n (string-to-number (match-string 2 fmt)))
10333 (if (= c ?p)
10334 (setq modes (org-set-calc-mode 'calc-internal-prec n))
10335 (setq modes (org-set-calc-mode
10336 'calc-float-format
10337 (list (cdr (assoc c '((?n . float) (?f . fix)
10338 (?s . sci) (?e . eng))))
10339 n))))
10340 (setq fmt (replace-match "" t t fmt)))
10341 (if (string-match "[NT]" fmt)
10342 (setq numbers (equal (match-string 0 fmt) "N")
10343 fmt (replace-match "" t t fmt)))
10344 (if (string-match "L" fmt)
10345 (setq literal t
10346 fmt (replace-match "" t t fmt)))
10347 (if (string-match "E" fmt)
10348 (setq keep-empty t
10349 fmt (replace-match "" t t fmt)))
10350 (while (string-match "[DRFS]" fmt)
10351 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10352 (setq fmt (replace-match "" t t fmt)))
10353 (unless (string-match "\\S-" fmt)
10354 (setq fmt nil))))
10355 (if (and (not suppress-const) org-table-formula-use-constants)
10356 (setq formula (org-table-formula-substitute-names formula)))
10357 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10358 (while (> ndown 0)
10359 (setq fields (org-split-string
10360 (org-no-properties
10361 (buffer-substring (point-at-bol) (point-at-eol)))
10362 " *| *"))
10363 (if (eq numbers t)
10364 (setq fields (mapcar
10365 (lambda (x) (number-to-string (string-to-number x)))
10366 fields)))
10367 (setq ndown (1- ndown))
10368 (setq form (copy-sequence formula)
10369 lispp (and (> (length form) 2)(equal (substring form 0 2) "'(")))
10370 (if (and lispp literal) (setq lispp 'literal))
10371 ;; Check for old vertical references
10372 (setq form (org-rewrite-old-row-references form))
10373 ;; Insert complex ranges
10374 (while (string-match org-table-range-regexp form)
10375 (setq form
10376 (replace-match
10377 (save-match-data
10378 (org-table-make-reference
10379 (org-table-get-range (match-string 0 form) nil n0)
10380 keep-empty numbers lispp))
10381 t t form)))
10382 ;; Insert simple ranges
10383 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\$\\([0-9]+\\)" form)
10384 (setq form
10385 (replace-match
10386 (save-match-data
10387 (org-table-make-reference
10388 (org-sublist
10389 fields (string-to-number (match-string 1 form))
10390 (string-to-number (match-string 2 form)))
10391 keep-empty numbers lispp))
10392 t t form)))
10393 (setq form0 form)
10394 ;; Insert the references to fields in same row
10395 (while (string-match "\\$\\([0-9]+\\)" form)
10396 (setq n (string-to-number (match-string 1 form))
10397 x (nth (1- (if (= n 0) n0 n)) fields))
10398 (unless x (error "Invalid field specifier \"%s\""
10399 (match-string 0 form)))
10400 (setq form (replace-match
10401 (save-match-data
10402 (org-table-make-reference x nil numbers lispp))
10403 t t form)))
10405 (if lispp
10406 (setq ev (condition-case nil
10407 (eval (eval (read form)))
10408 (error "#ERROR"))
10409 ev (if (numberp ev) (number-to-string ev) ev))
10410 (or (fboundp 'calc-eval)
10411 (error "Calc does not seem to be installed, and is needed to evaluate the formula"))
10412 (setq ev (calc-eval (cons form modes)
10413 (if numbers 'num))))
10415 (when org-table-formula-debug
10416 (with-output-to-temp-buffer "*Substitution History*"
10417 (princ (format "Substitution history of formula
10418 Orig: %s
10419 $xyz-> %s
10420 @r$c-> %s
10421 $1-> %s\n" orig formula form0 form))
10422 (if (listp ev)
10423 (princ (format " %s^\nError: %s"
10424 (make-string (car ev) ?\-) (nth 1 ev)))
10425 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10426 ev (or fmt "NONE")
10427 (if fmt (format fmt (string-to-number ev)) ev)))))
10428 (setq bw (get-buffer-window "*Substitution History*"))
10429 (shrink-window-if-larger-than-buffer bw)
10430 (unless (and (interactive-p) (not ndown))
10431 (unless (let (inhibit-redisplay)
10432 (y-or-n-p "Debugging Formula. Continue to next? "))
10433 (org-table-align)
10434 (error "Abort"))
10435 (delete-window bw)
10436 (message "")))
10437 (if (listp ev) (setq fmt nil ev "#ERROR"))
10438 (org-table-justify-field-maybe
10439 (if fmt (format fmt (string-to-number ev)) ev))
10440 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10441 (call-interactively 'org-return)
10442 (setq ndown 0)))
10443 (and down (org-table-maybe-recalculate-line))
10444 (or suppress-align (and org-table-may-need-update
10445 (org-table-align))))))
10447 (defun org-table-put-field-property (prop value)
10448 (save-excursion
10449 (put-text-property (progn (skip-chars-backward "^|") (point))
10450 (progn (skip-chars-forward "^|") (point))
10451 prop value)))
10453 (defun org-table-get-range (desc &optional tbeg col highlight)
10454 "Get a calc vector from a column, accorting to descriptor DESC.
10455 Optional arguments TBEG and COL can give the beginning of the table and
10456 the current column, to avoid unnecessary parsing.
10457 HIGHLIGHT means, just highlight the range."
10458 (if (not (equal (string-to-char desc) ?@))
10459 (setq desc (concat "@" desc)))
10460 (save-excursion
10461 (or tbeg (setq tbeg (org-table-begin)))
10462 (or col (setq col (org-table-current-column)))
10463 (let ((thisline (org-current-line))
10464 beg end c1 c2 r1 r2 rangep tmp)
10465 (unless (string-match org-table-range-regexp desc)
10466 (error "Invalid table range specifier `%s'" desc))
10467 (setq rangep (match-end 3)
10468 r1 (and (match-end 1) (match-string 1 desc))
10469 r2 (and (match-end 4) (match-string 4 desc))
10470 c1 (and (match-end 2) (substring (match-string 2 desc) 1))
10471 c2 (and (match-end 5) (substring (match-string 5 desc) 1)))
10473 (and c1 (setq c1 (+ (string-to-number c1)
10474 (if (memq (string-to-char c1) '(?- ?+)) col 0))))
10475 (and c2 (setq c2 (+ (string-to-number c2)
10476 (if (memq (string-to-char c2) '(?- ?+)) col 0))))
10477 (if (equal r1 "") (setq r1 nil))
10478 (if (equal r2 "") (setq r2 nil))
10479 (if r1 (setq r1 (org-table-get-descriptor-line r1)))
10480 (if r2 (setq r2 (org-table-get-descriptor-line r2)))
10481 ; (setq r2 (or r2 r1) c2 (or c2 c1))
10482 (if (not r1) (setq r1 thisline))
10483 (if (not r2) (setq r2 thisline))
10484 (if (not c1) (setq c1 col))
10485 (if (not c2) (setq c2 col))
10486 (if (or (not rangep) (and (= r1 r2) (= c1 c2)))
10487 ;; just one field
10488 (progn
10489 (goto-line r1)
10490 (while (not (looking-at org-table-dataline-regexp))
10491 (beginning-of-line 2))
10492 (prog1 (org-trim (org-table-get-field c1))
10493 (if highlight (org-table-highlight-rectangle (point) (point)))))
10494 ;; A range, return a vector
10495 ;; First sort the numbers to get a regular ractangle
10496 (if (< r2 r1) (setq tmp r1 r1 r2 r2 tmp))
10497 (if (< c2 c1) (setq tmp c1 c1 c2 c2 tmp))
10498 (goto-line r1)
10499 (while (not (looking-at org-table-dataline-regexp))
10500 (beginning-of-line 2))
10501 (org-table-goto-column c1)
10502 (setq beg (point))
10503 (goto-line r2)
10504 (while (not (looking-at org-table-dataline-regexp))
10505 (beginning-of-line 0))
10506 (org-table-goto-column c2)
10507 (setq end (point))
10508 (if highlight
10509 (org-table-highlight-rectangle
10510 beg (progn (skip-chars-forward "^|\n") (point))))
10511 ;; return string representation of calc vector
10512 (mapcar 'org-trim
10513 (apply 'append (org-table-copy-region beg end)))))))
10515 (defun org-table-get-descriptor-line (desc &optional cline bline table)
10516 "Analyze descriptor DESC and retrieve the corresponding line number.
10517 The cursor is currently in line CLINE, the table begins in line BLINE,
10518 and TABLE is a vector with line types."
10519 (if (string-match "^[0-9]+$" desc)
10520 (aref org-table-dlines (string-to-number desc))
10521 (setq cline (or cline (org-current-line))
10522 bline (or bline org-table-current-begin-line)
10523 table (or table org-table-current-line-types))
10524 (if (or
10525 (not (string-match "^\\(\\([-+]\\)?\\(I+\\)\\)?\\(\\([-+]\\)?\\([0-9]+\\)\\)?" desc))
10526 ;; 1 2 3 4 5 6
10527 (and (not (match-end 3)) (not (match-end 6)))
10528 (and (match-end 3) (match-end 6) (not (match-end 5))))
10529 (error "invalid row descriptor `%s'" desc))
10530 (let* ((hdir (and (match-end 2) (match-string 2 desc)))
10531 (hn (if (match-end 3) (- (match-end 3) (match-beginning 3)) nil))
10532 (odir (and (match-end 5) (match-string 5 desc)))
10533 (on (if (match-end 6) (string-to-number (match-string 6 desc))))
10534 (i (- cline bline))
10535 (rel (and (match-end 6)
10536 (or (and (match-end 1) (not (match-end 3)))
10537 (match-end 5)))))
10538 (if (and hn (not hdir))
10539 (progn
10540 (setq i 0 hdir "+")
10541 (if (eq (aref table 0) 'hline) (setq hn (1- hn)))))
10542 (if (and (not hn) on (not odir))
10543 (error "should never happen");;(aref org-table-dlines on)
10544 (if (and hn (> hn 0))
10545 (setq i (org-find-row-type table i 'hline (equal hdir "-") nil hn)))
10546 (if on
10547 (setq i (org-find-row-type table i 'dline (equal odir "-") rel on)))
10548 (+ bline i)))))
10550 (defun org-find-row-type (table i type backwards relative n)
10551 (let ((l (length table)))
10552 (while (> n 0)
10553 (while (and (setq i (+ i (if backwards -1 1)))
10554 (>= i 0) (< i l)
10555 (not (eq (aref table i) type))
10556 (if (and relative (eq (aref table i) 'hline))
10557 (progn (setq i (- i (if backwards -1 1)) n 1) nil)
10558 t)))
10559 (setq n (1- n)))
10560 (if (or (< i 0) (>= i l))
10561 (error "Row descriptior leads outside table")
10562 i)))
10564 (defun org-rewrite-old-row-references (s)
10565 (if (string-match "&[-+0-9I]" s)
10566 (error "Formula contains old &row reference, please rewrite using @-syntax")
10569 (defun org-table-make-reference (elements keep-empty numbers lispp)
10570 "Convert list ELEMENTS to something appropriate to insert into formula.
10571 KEEP-EMPTY indicated to keep empty fields, default is to skip them.
10572 NUMBERS indicates that everything should be converted to numbers.
10573 LISPP means to return something appropriate for a Lisp list."
10574 (if (stringp elements) ; just a single val
10575 (if lispp
10576 (if (eq lispp 'literal)
10577 elements
10578 (prin1-to-string (if numbers (string-to-number elements) elements)))
10579 (if (equal elements "") (setq elements "0"))
10580 (if numbers (number-to-string (string-to-number elements)) elements))
10581 (unless keep-empty
10582 (setq elements
10583 (delq nil
10584 (mapcar (lambda (x) (if (string-match "\\S-" x) x nil))
10585 elements))))
10586 (setq elements (or elements '("0")))
10587 (if lispp
10588 (mapconcat
10589 (lambda (x)
10590 (if (eq lispp 'literal)
10592 (prin1-to-string (if numbers (string-to-number x) x))))
10593 elements " ")
10594 (concat "[" (mapconcat
10595 (lambda (x)
10596 (if numbers (number-to-string (string-to-number x)) x))
10597 elements
10598 ",") "]"))))
10600 (defun org-table-recalculate (&optional all noalign)
10601 "Recalculate the current table line by applying all stored formulas.
10602 With prefix arg ALL, do this for all lines in the table."
10603 (interactive "P")
10604 (or (memq this-command org-recalc-commands)
10605 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10606 (unless (org-at-table-p) (error "Not at a table"))
10607 (if (equal all '(16))
10608 (org-table-iterate)
10609 (org-table-get-specials)
10610 (let* ((eqlist (sort (org-table-get-stored-formulas)
10611 (lambda (a b) (string< (car a) (car b)))))
10612 (inhibit-redisplay (not debug-on-error))
10613 (line-re org-table-dataline-regexp)
10614 (thisline (org-current-line))
10615 (thiscol (org-table-current-column))
10616 beg end entry eqlnum eqlname eqlname1 eql (cnt 0) eq a name)
10617 ;; Insert constants in all formulas
10618 (setq eqlist
10619 (mapcar (lambda (x)
10620 (setcdr x (org-table-formula-substitute-names (cdr x)))
10622 eqlist))
10623 ;; Split the equation list
10624 (while (setq eq (pop eqlist))
10625 (if (<= (string-to-char (car eq)) ?9)
10626 (push eq eqlnum)
10627 (push eq eqlname)))
10628 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10629 (if all
10630 (progn
10631 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10632 (goto-char (setq beg (org-table-begin)))
10633 (if (re-search-forward org-table-calculate-mark-regexp end t)
10634 ;; This is a table with marked lines, compute selected lines
10635 (setq line-re org-table-recalculate-regexp)
10636 ;; Move forward to the first non-header line
10637 (if (and (re-search-forward org-table-dataline-regexp end t)
10638 (re-search-forward org-table-hline-regexp end t)
10639 (re-search-forward org-table-dataline-regexp end t))
10640 (setq beg (match-beginning 0))
10641 nil))) ;; just leave beg where it is
10642 (setq beg (point-at-bol)
10643 end (move-marker (make-marker) (1+ (point-at-eol)))))
10644 (goto-char beg)
10645 (and all (message "Re-applying formulas to full table..."))
10647 ;; First find the named fields, and mark them untouchanble
10648 (remove-text-properties beg end '(org-untouchable t))
10649 (while (setq eq (pop eqlname))
10650 (setq name (car eq)
10651 a (assoc name org-table-named-field-locations))
10652 (and (not a)
10653 (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" name)
10654 (setq a (list name
10655 (aref org-table-dlines
10656 (string-to-number (match-string 1 name)))
10657 (string-to-number (match-string 2 name)))))
10658 (when (and a (or all (equal (nth 1 a) thisline)))
10659 (message "Re-applying formula to field: %s" name)
10660 (goto-line (nth 1 a))
10661 (org-table-goto-column (nth 2 a))
10662 (push (append a (list (cdr eq))) eqlname1)
10663 (org-table-put-field-property :org-untouchable t)))
10665 ;; Now evauluate the column formulas, but skip fields covered by
10666 ;; field formulas
10667 (goto-char beg)
10668 (while (re-search-forward line-re end t)
10669 (unless (string-match "^ *[_^!$/] *$" (org-table-get-field 1))
10670 ;; Unprotected line, recalculate
10671 (and all (message "Re-applying formulas to full table...(line %d)"
10672 (setq cnt (1+ cnt))))
10673 (setq org-last-recalc-line (org-current-line))
10674 (setq eql eqlnum)
10675 (while (setq entry (pop eql))
10676 (goto-line org-last-recalc-line)
10677 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10678 (unless (get-text-property (point) :org-untouchable)
10679 (org-table-eval-formula nil (cdr entry)
10680 'noalign 'nocst 'nostore 'noanalysis)))))
10682 ;; Now evaluate the field formulas
10683 (while (setq eq (pop eqlname1))
10684 (message "Re-applying formula to field: %s" (car eq))
10685 (goto-line (nth 1 eq))
10686 (org-table-goto-column (nth 2 eq))
10687 (org-table-eval-formula nil (nth 3 eq) 'noalign 'nocst
10688 'nostore 'noanalysis))
10690 (goto-line thisline)
10691 (org-table-goto-column thiscol)
10692 (remove-text-properties (point-min) (point-max) '(org-untouchable t))
10693 (or noalign (and org-table-may-need-update (org-table-align))
10694 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10696 ;; back to initial position
10697 (message "Re-applying formulas...done")
10698 (goto-line thisline)
10699 (org-table-goto-column thiscol)
10700 (or noalign (and org-table-may-need-update (org-table-align))
10701 (and all (message "Re-applying formulas...done"))))))
10703 (defun org-table-iterate (&optional arg)
10704 "Recalculate the table until it does not change anymore."
10705 (interactive "P")
10706 (let ((imax (if arg (prefix-numeric-value arg) 10))
10707 (i 0)
10708 (lasttbl (buffer-substring (org-table-begin) (org-table-end)))
10709 thistbl)
10710 (catch 'exit
10711 (while (< i imax)
10712 (setq i (1+ i))
10713 (org-table-recalculate 'all)
10714 (setq thistbl (buffer-substring (org-table-begin) (org-table-end)))
10715 (if (not (string= lasttbl thistbl))
10716 (setq lasttbl thistbl)
10717 (if (> i 1)
10718 (message "Convergence after %d iterations" i)
10719 (message "Table was already stable"))
10720 (throw 'exit t)))
10721 (error "No convergence after %d iterations" i))))
10723 (defun org-table-formula-substitute-names (f)
10724 "Replace $const with values in string F."
10725 (let ((start 0) a (f1 f) (pp (/= (string-to-char f) ?')))
10726 ;; First, check for column names
10727 (while (setq start (string-match org-table-column-name-regexp f start))
10728 (setq start (1+ start))
10729 (setq a (assoc (match-string 1 f) org-table-column-names))
10730 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10731 ;; Parameters and constants
10732 (setq start 0)
10733 (while (setq start (string-match "\\$\\([a-zA-Z][_a-zA-Z0-9]*\\)" f start))
10734 (setq start (1+ start))
10735 (if (setq a (save-match-data
10736 (org-table-get-constant (match-string 1 f))))
10737 (setq f (replace-match
10738 (concat (if pp "(") a (if pp ")")) t t f))))
10739 (if org-table-formula-debug
10740 (put-text-property 0 (length f) :orig-formula f1 f))
10743 (defun org-table-get-constant (const)
10744 "Find the value for a parameter or constant in a formula.
10745 Parameters get priority."
10746 (or (cdr (assoc const org-table-local-parameters))
10747 (cdr (assoc const org-table-formula-constants-local))
10748 (cdr (assoc const org-table-formula-constants))
10749 (and (fboundp 'constants-get) (constants-get const))
10750 (and (string= (substring const 0 (min 5 (length const))) "PROP_")
10751 (org-entry-get nil (substring const 5) 'inherit))
10752 "#UNDEFINED_NAME"))
10754 (defvar org-table-fedit-map
10755 (let ((map (make-sparse-keymap)))
10756 (org-defkey map "\C-x\C-s" 'org-table-fedit-finish)
10757 (org-defkey map "\C-c\C-s" 'org-table-fedit-finish)
10758 (org-defkey map "\C-c\C-c" 'org-table-fedit-finish)
10759 (org-defkey map "\C-c\C-q" 'org-table-fedit-abort)
10760 (org-defkey map "\C-c?" 'org-table-show-reference)
10761 (org-defkey map [(meta shift up)] 'org-table-fedit-line-up)
10762 (org-defkey map [(meta shift down)] 'org-table-fedit-line-down)
10763 (org-defkey map [(shift up)] 'org-table-fedit-ref-up)
10764 (org-defkey map [(shift down)] 'org-table-fedit-ref-down)
10765 (org-defkey map [(shift left)] 'org-table-fedit-ref-left)
10766 (org-defkey map [(shift right)] 'org-table-fedit-ref-right)
10767 (org-defkey map [(meta up)] 'org-table-fedit-scroll-down)
10768 (org-defkey map [(meta down)] 'org-table-fedit-scroll)
10769 (org-defkey map [(meta tab)] 'lisp-complete-symbol)
10770 (org-defkey map "\M-\C-i" 'lisp-complete-symbol)
10771 (org-defkey map [(tab)] 'org-table-fedit-lisp-indent)
10772 (org-defkey map "\C-i" 'org-table-fedit-lisp-indent)
10773 (org-defkey map "\C-c\C-r" 'org-table-fedit-toggle-ref-type)
10774 (org-defkey map "\C-c}" 'org-table-fedit-toggle-coordinates)
10775 map))
10777 (easy-menu-define org-table-fedit-menu org-table-fedit-map "Org Edit Formulas Menu"
10778 '("Edit-Formulas"
10779 ["Finish and Install" org-table-fedit-finish t]
10780 ["Finish, Install, and Apply" (org-table-fedit-finish t) :keys "C-u C-c C-c"]
10781 ["Abort" org-table-fedit-abort t]
10782 "--"
10783 ["Pretty-Print Lisp Formula" org-table-fedit-lisp-indent t]
10784 ["Complete Lisp Symbol" lisp-complete-symbol t]
10785 "--"
10786 "Shift Reference at Point"
10787 ["Up" org-table-fedit-ref-up t]
10788 ["Down" org-table-fedit-ref-down t]
10789 ["Left" org-table-fedit-ref-left t]
10790 ["Right" org-table-fedit-ref-right t]
10792 "Change Test Row for Column Formulas"
10793 ["Up" org-table-fedit-line-up t]
10794 ["Down" org-table-fedit-line-down t]
10795 "--"
10796 ["Scroll Table Window" org-table-fedit-scroll t]
10797 ["Scroll Table Window down" org-table-fedit-scroll-down t]
10798 ["Show Table Grid" org-table-fedit-toggle-coordinates
10799 :style toggle :selected (with-current-buffer (marker-buffer org-pos)
10800 org-table-overlay-coordinates)]
10801 "--"
10802 ["Standard Refs (B3 instead of @3$2)" org-table-fedit-toggle-ref-type
10803 :style toggle :selected org-table-buffer-is-an]))
10805 (defvar org-pos)
10807 (defun org-table-edit-formulas ()
10808 "Edit the formulas of the current table in a separate buffer."
10809 (interactive)
10810 (when (save-excursion (beginning-of-line 1) (looking-at "#\\+TBLFM"))
10811 (beginning-of-line 0))
10812 (unless (org-at-table-p) (error "Not at a table"))
10813 (org-table-get-specials)
10814 (let ((key (org-table-current-field-formula 'key 'noerror))
10815 (eql (sort (org-table-get-stored-formulas 'noerror)
10816 'org-table-formula-less-p))
10817 (pos (move-marker (make-marker) (point)))
10818 (startline 1)
10819 (wc (current-window-configuration))
10820 (titles '((column . "# Column Formulas\n")
10821 (field . "# Field Formulas\n")
10822 (named . "# Named Field Formulas\n")))
10823 entry s type title)
10824 (org-switch-to-buffer-other-window "*Edit Formulas*")
10825 (erase-buffer)
10826 ;; Keep global-font-lock-mode from turning on font-lock-mode
10827 (let ((font-lock-global-modes '(not fundamental-mode)))
10828 (fundamental-mode))
10829 (org-set-local 'font-lock-global-modes (list 'not major-mode))
10830 (org-set-local 'org-pos pos)
10831 (org-set-local 'org-window-configuration wc)
10832 (use-local-map org-table-fedit-map)
10833 (org-add-hook 'post-command-hook 'org-table-fedit-post-command t t)
10834 (easy-menu-add org-table-fedit-menu)
10835 (setq startline (org-current-line))
10836 (while (setq entry (pop eql))
10837 (setq type (cond
10838 ((equal (string-to-char (car entry)) ?@) 'field)
10839 ((string-match "^[0-9]" (car entry)) 'column)
10840 (t 'named)))
10841 (when (setq title (assq type titles))
10842 (or (bobp) (insert "\n"))
10843 (insert (org-add-props (cdr title) nil 'face font-lock-comment-face))
10844 (setq titles (delq title titles)))
10845 (if (equal key (car entry)) (setq startline (org-current-line)))
10846 (setq s (concat (if (equal (string-to-char (car entry)) ?@) "" "$")
10847 (car entry) " = " (cdr entry) "\n"))
10848 (remove-text-properties 0 (length s) '(face nil) s)
10849 (insert s))
10850 (if (eq org-table-use-standard-references t)
10851 (org-table-fedit-toggle-ref-type))
10852 (goto-line startline)
10853 (message "Edit formulas and finish with `C-c C-c'. See menu for more commands.")))
10855 (defun org-table-fedit-post-command ()
10856 (when (not (memq this-command '(lisp-complete-symbol)))
10857 (let ((win (selected-window)))
10858 (save-excursion
10859 (condition-case nil
10860 (org-table-show-reference)
10861 (error nil))
10862 (select-window win)))))
10864 (defun org-table-formula-to-user (s)
10865 "Convert a formula from internal to user representation."
10866 (if (eq org-table-use-standard-references t)
10867 (org-table-convert-refs-to-an s)
10870 (defun org-table-formula-from-user (s)
10871 "Convert a formula from user to internal representation."
10872 (if org-table-use-standard-references
10873 (org-table-convert-refs-to-rc s)
10876 (defun org-table-convert-refs-to-rc (s)
10877 "Convert spreadsheet references from AB7 to @7$28.
10878 Works for single references, but also for entire formulas and even the
10879 full TBLFM line."
10880 (let ((start 0))
10881 (while (string-match "\\<\\([a-zA-Z]+\\)\\([0-9]+\\>\\|&\\)\\|\\(;[^\r\n:]+\\)" s start)
10882 (cond
10883 ((match-end 3)
10884 ;; format match, just advance
10885 (setq start (match-end 0)))
10886 ((and (> (match-beginning 0) 0)
10887 (equal ?. (aref s (max (1- (match-beginning 0)) 0)))
10888 (not (equal ?. (aref s (max (- (match-beginning 0) 2) 0)))))
10889 ;; 3.e5 or something like this.
10890 (setq start (match-end 0)))
10892 (setq start (match-beginning 0)
10893 s (replace-match
10894 (if (equal (match-string 2 s) "&")
10895 (format "$%d" (org-letters-to-number (match-string 1 s)))
10896 (format "@%d$%d"
10897 (string-to-number (match-string 2 s))
10898 (org-letters-to-number (match-string 1 s))))
10899 t t s)))))
10902 (defun org-table-convert-refs-to-an (s)
10903 "Convert spreadsheet references from to @7$28 to AB7.
10904 Works for single references, but also for entire formulas and even the
10905 full TBLFM line."
10906 (while (string-match "@\\([0-9]+\\)\\$\\([0-9]+\\)" s)
10907 (setq s (replace-match
10908 (format "%s%d"
10909 (org-number-to-letters
10910 (string-to-number (match-string 2 s)))
10911 (string-to-number (match-string 1 s)))
10912 t t s)))
10913 (while (string-match "\\(^\\|[^0-9a-zA-Z]\\)\\$\\([0-9]+\\)" s)
10914 (setq s (replace-match (concat "\\1"
10915 (org-number-to-letters
10916 (string-to-number (match-string 2 s))) "&")
10917 t nil s)))
10920 (defun org-letters-to-number (s)
10921 "Convert a base 26 number represented by letters into an integer.
10922 For example: AB -> 28."
10923 (let ((n 0))
10924 (setq s (upcase s))
10925 (while (> (length s) 0)
10926 (setq n (+ (* n 26) (string-to-char s) (- ?A) 1)
10927 s (substring s 1)))
10930 (defun org-number-to-letters (n)
10931 "Convert an integer into a base 26 number represented by letters.
10932 For example: 28 -> AB."
10933 (let ((s ""))
10934 (while (> n 0)
10935 (setq s (concat (char-to-string (+ (mod (1- n) 26) ?A)) s)
10936 n (/ (1- n) 26)))
10939 (defun org-table-fedit-convert-buffer (function)
10940 "Convert all references in this buffer, using FUNTION."
10941 (let ((line (org-current-line)))
10942 (goto-char (point-min))
10943 (while (not (eobp))
10944 (insert (funcall function (buffer-substring (point) (point-at-eol))))
10945 (delete-region (point) (point-at-eol))
10946 (or (eobp) (forward-char 1)))
10947 (goto-line line)))
10949 (defun org-table-fedit-toggle-ref-type ()
10950 "Convert all references in the buffer from B3 to @3$2 and back."
10951 (interactive)
10952 (org-set-local 'org-table-buffer-is-an (not org-table-buffer-is-an))
10953 (org-table-fedit-convert-buffer
10954 (if org-table-buffer-is-an
10955 'org-table-convert-refs-to-an 'org-table-convert-refs-to-rc))
10956 (message "Reference type switched to %s"
10957 (if org-table-buffer-is-an "A1 etc" "@row$column")))
10959 (defun org-table-fedit-ref-up ()
10960 "Shift the reference at point one row/hline up."
10961 (interactive)
10962 (org-table-fedit-shift-reference 'up))
10963 (defun org-table-fedit-ref-down ()
10964 "Shift the reference at point one row/hline down."
10965 (interactive)
10966 (org-table-fedit-shift-reference 'down))
10967 (defun org-table-fedit-ref-left ()
10968 "Shift the reference at point one field to the left."
10969 (interactive)
10970 (org-table-fedit-shift-reference 'left))
10971 (defun org-table-fedit-ref-right ()
10972 "Shift the reference at point one field to the right."
10973 (interactive)
10974 (org-table-fedit-shift-reference 'right))
10976 (defun org-table-fedit-shift-reference (dir)
10977 (cond
10978 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\)&")
10979 (if (memq dir '(left right))
10980 (org-rematch-and-replace 1 (eq dir 'left))
10981 (error "Cannot shift reference in this direction")))
10982 ((org-at-regexp-p "\\(\\<[a-zA-Z]\\{1,2\\}\\)\\([0-9]+\\)")
10983 ;; A B3-like reference
10984 (if (memq dir '(up down))
10985 (org-rematch-and-replace 2 (eq dir 'up))
10986 (org-rematch-and-replace 1 (eq dir 'left))))
10987 ((org-at-regexp-p
10988 "\\(@\\|\\.\\.\\)\\([-+]?\\(I+\\>\\|[0-9]+\\)\\)\\(\\$\\([-+]?[0-9]+\\)\\)?")
10989 ;; An internal reference
10990 (if (memq dir '(up down))
10991 (org-rematch-and-replace 2 (eq dir 'up) (match-end 3))
10992 (org-rematch-and-replace 5 (eq dir 'left))))))
10994 (defun org-rematch-and-replace (n &optional decr hline)
10995 "Re-match the group N, and replace it with the shifted refrence."
10996 (or (match-end n) (error "Cannot shift reference in this direction"))
10997 (goto-char (match-beginning n))
10998 (and (looking-at (regexp-quote (match-string n)))
10999 (replace-match (org-shift-refpart (match-string 0) decr hline)
11000 t t)))
11002 (defun org-shift-refpart (ref &optional decr hline)
11003 "Shift a refrence part REF.
11004 If DECR is set, decrease the references row/column, else increase.
11005 If HLINE is set, this may be a hline reference, it certainly is not
11006 a translation reference."
11007 (save-match-data
11008 (let* ((sign (string-match "^[-+]" ref)) n)
11010 (if sign (setq sign (substring ref 0 1) ref (substring ref 1)))
11011 (cond
11012 ((and hline (string-match "^I+" ref))
11013 (setq n (string-to-number (concat sign (number-to-string (length ref)))))
11014 (setq n (+ n (if decr -1 1)))
11015 (if (= n 0) (setq n (+ n (if decr -1 1))))
11016 (if sign
11017 (setq sign (if (< n 0) "-" "+") n (abs n))
11018 (setq n (max 1 n)))
11019 (concat sign (make-string n ?I)))
11021 ((string-match "^[0-9]+" ref)
11022 (setq n (string-to-number (concat sign ref)))
11023 (setq n (+ n (if decr -1 1)))
11024 (if sign
11025 (concat (if (< n 0) "-" "+") (number-to-string (abs n)))
11026 (number-to-string (max 1 n))))
11028 ((string-match "^[a-zA-Z]+" ref)
11029 (org-number-to-letters
11030 (max 1 (+ (org-letters-to-number ref) (if decr -1 1)))))
11032 (t (error "Cannot shift reference"))))))
11034 (defun org-table-fedit-toggle-coordinates ()
11035 "Toggle the display of coordinates in the refrenced table."
11036 (interactive)
11037 (let ((pos (marker-position org-pos)))
11038 (with-current-buffer (marker-buffer org-pos)
11039 (save-excursion
11040 (goto-char pos)
11041 (org-table-toggle-coordinate-overlays)))))
11043 (defun org-table-fedit-finish (&optional arg)
11044 "Parse the buffer for formula definitions and install them.
11045 With prefix ARG, apply the new formulas to the table."
11046 (interactive "P")
11047 (org-table-remove-rectangle-highlight)
11048 (if org-table-use-standard-references
11049 (progn
11050 (org-table-fedit-convert-buffer 'org-table-convert-refs-to-rc)
11051 (setq org-table-buffer-is-an nil)))
11052 (let ((pos org-pos) eql var form)
11053 (goto-char (point-min))
11054 (while (re-search-forward
11055 "^\\(@[0-9]+\\$[0-9]+\\|\\$\\([a-zA-Z0-9]+\\)\\) *= *\\(.*\\(\n[ \t]+.*$\\)*\\)"
11056 nil t)
11057 (setq var (if (match-end 2) (match-string 2) (match-string 1))
11058 form (match-string 3))
11059 (setq form (org-trim form))
11060 (when (not (equal form ""))
11061 (while (string-match "[ \t]*\n[ \t]*" form)
11062 (setq form (replace-match " " t t form)))
11063 (when (assoc var eql)
11064 (error "Double formulas for %s" var))
11065 (push (cons var form) eql)))
11066 (setq org-pos nil)
11067 (set-window-configuration org-window-configuration)
11068 (select-window (get-buffer-window (marker-buffer pos)))
11069 (goto-char pos)
11070 (unless (org-at-table-p)
11071 (error "Lost table position - cannot install formulae"))
11072 (org-table-store-formulas eql)
11073 (move-marker pos nil)
11074 (kill-buffer "*Edit Formulas*")
11075 (if arg
11076 (org-table-recalculate 'all)
11077 (message "New formulas installed - press C-u C-c C-c to apply."))))
11079 (defun org-table-fedit-abort ()
11080 "Abort editing formulas, without installing the changes."
11081 (interactive)
11082 (org-table-remove-rectangle-highlight)
11083 (let ((pos org-pos))
11084 (set-window-configuration org-window-configuration)
11085 (select-window (get-buffer-window (marker-buffer pos)))
11086 (goto-char pos)
11087 (move-marker pos nil)
11088 (message "Formula editing aborted without installing changes")))
11090 (defun org-table-fedit-lisp-indent ()
11091 "Pretty-print and re-indent Lisp expressions in the Formula Editor."
11092 (interactive)
11093 (let ((pos (point)) beg end ind)
11094 (beginning-of-line 1)
11095 (cond
11096 ((looking-at "[ \t]")
11097 (goto-char pos)
11098 (call-interactively 'lisp-indent-line))
11099 ((looking-at "[$&@0-9a-zA-Z]+ *= *[^ \t\n']") (goto-char pos))
11100 ((not (fboundp 'pp-buffer))
11101 (error "Cannot pretty-print. Command `pp-buffer' is not available."))
11102 ((looking-at "[$&@0-9a-zA-Z]+ *= *'(")
11103 (goto-char (- (match-end 0) 2))
11104 (setq beg (point))
11105 (setq ind (make-string (current-column) ?\ ))
11106 (condition-case nil (forward-sexp 1)
11107 (error
11108 (error "Cannot pretty-print Lisp expression: Unbalanced parenthesis")))
11109 (setq end (point))
11110 (save-restriction
11111 (narrow-to-region beg end)
11112 (if (eq last-command this-command)
11113 (progn
11114 (goto-char (point-min))
11115 (setq this-command nil)
11116 (while (re-search-forward "[ \t]*\n[ \t]*" nil t)
11117 (replace-match " ")))
11118 (pp-buffer)
11119 (untabify (point-min) (point-max))
11120 (goto-char (1+ (point-min)))
11121 (while (re-search-forward "^." nil t)
11122 (beginning-of-line 1)
11123 (insert ind))
11124 (goto-char (point-max))
11125 (backward-delete-char 1)))
11126 (goto-char beg))
11127 (t nil))))
11129 (defvar org-show-positions nil)
11131 (defun org-table-show-reference (&optional local)
11132 "Show the location/value of the $ expression at point."
11133 (interactive)
11134 (org-table-remove-rectangle-highlight)
11135 (catch 'exit
11136 (let ((pos (if local (point) org-pos))
11137 (face2 'highlight)
11138 (org-inhibit-highlight-removal t)
11139 (win (selected-window))
11140 (org-show-positions nil)
11141 var name e what match dest)
11142 (if local (org-table-get-specials))
11143 (setq what (cond
11144 ((or (org-at-regexp-p org-table-range-regexp2)
11145 (org-at-regexp-p org-table-translate-regexp)
11146 (org-at-regexp-p org-table-range-regexp))
11147 (setq match
11148 (save-match-data
11149 (org-table-convert-refs-to-rc (match-string 0))))
11150 'range)
11151 ((org-at-regexp-p "\\$[a-zA-Z][a-zA-Z0-9]*") 'name)
11152 ((org-at-regexp-p "\\$[0-9]+") 'column)
11153 ((not local) nil)
11154 (t (error "No reference at point")))
11155 match (and what (or match (match-string 0))))
11156 (when (and match (not (equal (match-beginning 0) (point-at-bol))))
11157 (org-table-add-rectangle-overlay (match-beginning 0) (match-end 0)
11158 'secondary-selection))
11159 (org-add-hook 'before-change-functions
11160 'org-table-remove-rectangle-highlight)
11161 (if (eq what 'name) (setq var (substring match 1)))
11162 (when (eq what 'range)
11163 (or (equal (string-to-char match) ?@) (setq match (concat "@" match)))
11164 (setq match (org-table-formula-substitute-names match)))
11165 (unless local
11166 (save-excursion
11167 (end-of-line 1)
11168 (re-search-backward "^\\S-" nil t)
11169 (beginning-of-line 1)
11170 (when (looking-at "\\(\\$[0-9a-zA-Z]+\\|@[0-9]+\\$[0-9]+\\|[a-zA-Z]+\\([0-9]+\\|&\\)\\) *=")
11171 (setq dest
11172 (save-match-data
11173 (org-table-convert-refs-to-rc (match-string 1))))
11174 (org-table-add-rectangle-overlay
11175 (match-beginning 1) (match-end 1) face2))))
11176 (if (and (markerp pos) (marker-buffer pos))
11177 (if (get-buffer-window (marker-buffer pos))
11178 (select-window (get-buffer-window (marker-buffer pos)))
11179 (org-switch-to-buffer-other-window (get-buffer-window
11180 (marker-buffer pos)))))
11181 (goto-char pos)
11182 (org-table-force-dataline)
11183 (when dest
11184 (setq name (substring dest 1))
11185 (cond
11186 ((string-match "^\\$[a-zA-Z][a-zA-Z0-9]*" dest)
11187 (setq e (assoc name org-table-named-field-locations))
11188 (goto-line (nth 1 e))
11189 (org-table-goto-column (nth 2 e)))
11190 ((string-match "^@\\([0-9]+\\)\\$\\([0-9]+\\)" dest)
11191 (let ((l (string-to-number (match-string 1 dest)))
11192 (c (string-to-number (match-string 2 dest))))
11193 (goto-line (aref org-table-dlines l))
11194 (org-table-goto-column c)))
11195 (t (org-table-goto-column (string-to-number name))))
11196 (move-marker pos (point))
11197 (org-table-highlight-rectangle nil nil face2))
11198 (cond
11199 ((equal dest match))
11200 ((not match))
11201 ((eq what 'range)
11202 (condition-case nil
11203 (save-excursion
11204 (org-table-get-range match nil nil 'highlight))
11205 (error nil)))
11206 ((setq e (assoc var org-table-named-field-locations))
11207 (goto-line (nth 1 e))
11208 (org-table-goto-column (nth 2 e))
11209 (org-table-highlight-rectangle (point) (point))
11210 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11211 ((setq e (assoc var org-table-column-names))
11212 (org-table-goto-column (string-to-number (cdr e)))
11213 (org-table-highlight-rectangle (point) (point))
11214 (goto-char (org-table-begin))
11215 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11216 (org-table-end) t)
11217 (progn
11218 (goto-char (match-beginning 1))
11219 (org-table-highlight-rectangle)
11220 (message "Named column (column %s)" (cdr e)))
11221 (error "Column name not found")))
11222 ((eq what 'column)
11223 ;; column number
11224 (org-table-goto-column (string-to-number (substring match 1)))
11225 (org-table-highlight-rectangle (point) (point))
11226 (message "Column %s" (substring match 1)))
11227 ((setq e (assoc var org-table-local-parameters))
11228 (goto-char (org-table-begin))
11229 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11230 (progn
11231 (goto-char (match-beginning 1))
11232 (org-table-highlight-rectangle)
11233 (message "Local parameter."))
11234 (error "Parameter not found")))
11236 (cond
11237 ((not var) (error "No reference at point"))
11238 ((setq e (assoc var org-table-formula-constants-local))
11239 (message "Local Constant: $%s=%s in #+CONSTANTS line."
11240 var (cdr e)))
11241 ((setq e (assoc var org-table-formula-constants))
11242 (message "Constant: $%s=%s in `org-table-formula-constants'."
11243 var (cdr e)))
11244 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11245 (message "Constant: $%s=%s, from `constants.el'%s."
11246 var e (format " (%s units)" constants-unit-system)))
11247 (t (error "Undefined name $%s" var)))))
11248 (goto-char pos)
11249 (when (and org-show-positions
11250 (not (memq this-command '(org-table-fedit-scroll
11251 org-table-fedit-scroll-down))))
11252 (push pos org-show-positions)
11253 (push org-table-current-begin-pos org-show-positions)
11254 (let ((min (apply 'min org-show-positions))
11255 (max (apply 'max org-show-positions)))
11256 (goto-char min) (recenter 0)
11257 (goto-char max)
11258 (or (pos-visible-in-window-p max) (recenter -1))))
11259 (select-window win))))
11261 (defun org-table-force-dataline ()
11262 "Make sure the cursor is in a dataline in a table."
11263 (unless (save-excursion
11264 (beginning-of-line 1)
11265 (looking-at org-table-dataline-regexp))
11266 (let* ((re org-table-dataline-regexp)
11267 (p1 (save-excursion (re-search-forward re nil 'move)))
11268 (p2 (save-excursion (re-search-backward re nil 'move))))
11269 (cond ((and p1 p2)
11270 (goto-char (if (< (abs (- p1 (point))) (abs (- p2 (point))))
11271 p1 p2)))
11272 ((or p1 p2) (goto-char (or p1 p2)))
11273 (t (error "No table dataline around here"))))))
11275 (defun org-table-fedit-line-up ()
11276 "Move cursor one line up in the window showing the table."
11277 (interactive)
11278 (org-table-fedit-move 'previous-line))
11280 (defun org-table-fedit-line-down ()
11281 "Move cursor one line down in the window showing the table."
11282 (interactive)
11283 (org-table-fedit-move 'next-line))
11285 (defun org-table-fedit-move (command)
11286 "Move the cursor in the window shoinw the table.
11287 Use COMMAND to do the motion, repeat if necessary to end up in a data line."
11288 (let ((org-table-allow-automatic-line-recalculation nil)
11289 (pos org-pos) (win (selected-window)) p)
11290 (select-window (get-buffer-window (marker-buffer org-pos)))
11291 (setq p (point))
11292 (call-interactively command)
11293 (while (and (org-at-table-p)
11294 (org-at-table-hline-p))
11295 (call-interactively command))
11296 (or (org-at-table-p) (goto-char p))
11297 (move-marker pos (point))
11298 (select-window win)))
11300 (defun org-table-fedit-scroll (N)
11301 (interactive "p")
11302 (let ((other-window-scroll-buffer (marker-buffer org-pos)))
11303 (scroll-other-window N)))
11305 (defun org-table-fedit-scroll-down (N)
11306 (interactive "p")
11307 (org-table-fedit-scroll (- N)))
11309 (defvar org-table-rectangle-overlays nil)
11311 (defun org-table-add-rectangle-overlay (beg end &optional face)
11312 "Add a new overlay."
11313 (let ((ov (org-make-overlay beg end)))
11314 (org-overlay-put ov 'face (or face 'secondary-selection))
11315 (push ov org-table-rectangle-overlays)))
11317 (defun org-table-highlight-rectangle (&optional beg end face)
11318 "Highlight rectangular region in a table."
11319 (setq beg (or beg (point)) end (or end (point)))
11320 (let ((b (min beg end))
11321 (e (max beg end))
11322 l1 c1 l2 c2 tmp)
11323 (and (boundp 'org-show-positions)
11324 (setq org-show-positions (cons b (cons e org-show-positions))))
11325 (goto-char (min beg end))
11326 (setq l1 (org-current-line)
11327 c1 (org-table-current-column))
11328 (goto-char (max beg end))
11329 (setq l2 (org-current-line)
11330 c2 (org-table-current-column))
11331 (if (> c1 c2) (setq tmp c1 c1 c2 c2 tmp))
11332 (goto-line l1)
11333 (beginning-of-line 1)
11334 (loop for line from l1 to l2 do
11335 (when (looking-at org-table-dataline-regexp)
11336 (org-table-goto-column c1)
11337 (skip-chars-backward "^|\n") (setq beg (point))
11338 (org-table-goto-column c2)
11339 (skip-chars-forward "^|\n") (setq end (point))
11340 (org-table-add-rectangle-overlay beg end face))
11341 (beginning-of-line 2))
11342 (goto-char b))
11343 (add-hook 'before-change-functions 'org-table-remove-rectangle-highlight))
11345 (defun org-table-remove-rectangle-highlight (&rest ignore)
11346 "Remove the rectangle overlays."
11347 (unless org-inhibit-highlight-removal
11348 (remove-hook 'before-change-functions 'org-table-remove-rectangle-highlight)
11349 (mapc 'org-delete-overlay org-table-rectangle-overlays)
11350 (setq org-table-rectangle-overlays nil)))
11352 (defvar org-table-coordinate-overlays nil
11353 "Collects the cooordinate grid overlays, so that they can be removed.")
11354 (make-variable-buffer-local 'org-table-coordinate-overlays)
11356 (defun org-table-overlay-coordinates ()
11357 "Add overlays to the table at point, to show row/column coordinates."
11358 (interactive)
11359 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11360 (setq org-table-coordinate-overlays nil)
11361 (save-excursion
11362 (let ((id 0) (ih 0) hline eol s1 s2 str ic ov beg)
11363 (goto-char (org-table-begin))
11364 (while (org-at-table-p)
11365 (setq eol (point-at-eol))
11366 (setq ov (org-make-overlay (point-at-bol) (1+ (point-at-bol))))
11367 (push ov org-table-coordinate-overlays)
11368 (setq hline (looking-at org-table-hline-regexp))
11369 (setq str (if hline (format "I*%-2d" (setq ih (1+ ih)))
11370 (format "%4d" (setq id (1+ id)))))
11371 (org-overlay-before-string ov str 'org-special-keyword 'evaporate)
11372 (when hline
11373 (setq ic 0)
11374 (while (re-search-forward "[+|]\\(-+\\)" eol t)
11375 (setq beg (1+ (match-beginning 0))
11376 ic (1+ ic)
11377 s1 (concat "$" (int-to-string ic))
11378 s2 (org-number-to-letters ic)
11379 str (if (eq org-table-use-standard-references t) s2 s1))
11380 (setq ov (org-make-overlay beg (+ beg (length str))))
11381 (push ov org-table-coordinate-overlays)
11382 (org-overlay-display ov str 'org-special-keyword 'evaporate)))
11383 (beginning-of-line 2)))))
11385 (defun org-table-toggle-coordinate-overlays ()
11386 "Toggle the display of Row/Column numbers in tables."
11387 (interactive)
11388 (setq org-table-overlay-coordinates (not org-table-overlay-coordinates))
11389 (message "Row/Column number display turned %s"
11390 (if org-table-overlay-coordinates "on" "off"))
11391 (if (and (org-at-table-p) org-table-overlay-coordinates)
11392 (org-table-align))
11393 (unless org-table-overlay-coordinates
11394 (mapc 'org-delete-overlay org-table-coordinate-overlays)
11395 (setq org-table-coordinate-overlays nil)))
11397 (defun org-table-toggle-formula-debugger ()
11398 "Toggle the formula debugger in tables."
11399 (interactive)
11400 (setq org-table-formula-debug (not org-table-formula-debug))
11401 (message "Formula debugging has been turned %s"
11402 (if org-table-formula-debug "on" "off")))
11404 ;;; The orgtbl minor mode
11406 ;; Define a minor mode which can be used in other modes in order to
11407 ;; integrate the org-mode table editor.
11409 ;; This is really a hack, because the org-mode table editor uses several
11410 ;; keys which normally belong to the major mode, for example the TAB and
11411 ;; RET keys. Here is how it works: The minor mode defines all the keys
11412 ;; necessary to operate the table editor, but wraps the commands into a
11413 ;; function which tests if the cursor is currently inside a table. If that
11414 ;; is the case, the table editor command is executed. However, when any of
11415 ;; those keys is used outside a table, the function uses `key-binding' to
11416 ;; look up if the key has an associated command in another currently active
11417 ;; keymap (minor modes, major mode, global), and executes that command.
11418 ;; There might be problems if any of the keys used by the table editor is
11419 ;; otherwise used as a prefix key.
11421 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11422 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11423 ;; addresses this by checking explicitly for both bindings.
11425 ;; The optimized version (see variable `orgtbl-optimized') takes over
11426 ;; all keys which are bound to `self-insert-command' in the *global map*.
11427 ;; Some modes bind other commands to simple characters, for example
11428 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11429 ;; active, this binding is ignored inside tables and replaced with a
11430 ;; modified self-insert.
11432 (defvar orgtbl-mode nil
11433 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11434 table editor in arbitrary modes.")
11435 (make-variable-buffer-local 'orgtbl-mode)
11437 (defvar orgtbl-mode-map (make-keymap)
11438 "Keymap for `orgtbl-mode'.")
11440 ;;;###autoload
11441 (defun turn-on-orgtbl ()
11442 "Unconditionally turn on `orgtbl-mode'."
11443 (orgtbl-mode 1))
11445 (defvar org-old-auto-fill-inhibit-regexp nil
11446 "Local variable used by `orgtbl-mode'")
11448 (defconst orgtbl-line-start-regexp "[ \t]*\\(|\\|#\\+\\(TBLFM\\|ORGTBL\\):\\)"
11449 "Matches a line belonging to an orgtbl.")
11451 (defconst orgtbl-extra-font-lock-keywords
11452 (list (list (concat "^" orgtbl-line-start-regexp ".*")
11453 0 (quote 'org-table) 'prepend))
11454 "Extra font-lock-keywords to be added when orgtbl-mode is active.")
11456 ;;;###autoload
11457 (defun orgtbl-mode (&optional arg)
11458 "The `org-mode' table editor as a minor mode for use in other modes."
11459 (interactive)
11460 (if (org-mode-p)
11461 ;; Exit without error, in case some hook functions calls this
11462 ;; by accident in org-mode.
11463 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11464 (setq orgtbl-mode
11465 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11466 (if orgtbl-mode
11467 (progn
11468 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11469 ;; Make sure we are first in minor-mode-map-alist
11470 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11471 (and c (setq minor-mode-map-alist
11472 (cons c (delq c minor-mode-map-alist)))))
11473 (org-set-local (quote org-table-may-need-update) t)
11474 (org-add-hook 'before-change-functions 'org-before-change-function
11475 nil 'local)
11476 (org-set-local 'org-old-auto-fill-inhibit-regexp
11477 auto-fill-inhibit-regexp)
11478 (org-set-local 'auto-fill-inhibit-regexp
11479 (if auto-fill-inhibit-regexp
11480 (concat orgtbl-line-start-regexp "\\|"
11481 auto-fill-inhibit-regexp)
11482 orgtbl-line-start-regexp))
11483 (org-add-to-invisibility-spec '(org-cwidth))
11484 (when (fboundp 'font-lock-add-keywords)
11485 (font-lock-add-keywords nil orgtbl-extra-font-lock-keywords)
11486 (org-restart-font-lock))
11487 (easy-menu-add orgtbl-mode-menu)
11488 (run-hooks 'orgtbl-mode-hook))
11489 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11490 (org-cleanup-narrow-column-properties)
11491 (org-remove-from-invisibility-spec '(org-cwidth))
11492 (remove-hook 'before-change-functions 'org-before-change-function t)
11493 (when (fboundp 'font-lock-remove-keywords)
11494 (font-lock-remove-keywords nil orgtbl-extra-font-lock-keywords)
11495 (org-restart-font-lock))
11496 (easy-menu-remove orgtbl-mode-menu)
11497 (force-mode-line-update 'all))))
11499 (defun org-cleanup-narrow-column-properties ()
11500 "Remove all properties related to narrow-column invisibility."
11501 (let ((s 1))
11502 (while (setq s (text-property-any s (point-max)
11503 'display org-narrow-column-arrow))
11504 (remove-text-properties s (1+ s) '(display t)))
11505 (setq s 1)
11506 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11507 (remove-text-properties s (1+ s) '(org-cwidth t)))
11508 (setq s 1)
11509 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11510 (remove-text-properties s (1+ s) '(invisible t)))))
11512 ;; Install it as a minor mode.
11513 (put 'orgtbl-mode :included t)
11514 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11515 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11517 (defun orgtbl-make-binding (fun n &rest keys)
11518 "Create a function for binding in the table minor mode.
11519 FUN is the command to call inside a table. N is used to create a unique
11520 command name. KEYS are keys that should be checked in for a command
11521 to execute outside of tables."
11522 (eval
11523 (list 'defun
11524 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11525 '(arg)
11526 (concat "In tables, run `" (symbol-name fun) "'.\n"
11527 "Outside of tables, run the binding of `"
11528 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11529 "'.")
11530 '(interactive "p")
11531 (list 'if
11532 '(org-at-table-p)
11533 (list 'call-interactively (list 'quote fun))
11534 (list 'let '(orgtbl-mode)
11535 (list 'call-interactively
11536 (append '(or)
11537 (mapcar (lambda (k)
11538 (list 'key-binding k))
11539 keys)
11540 '('orgtbl-error))))))))
11542 (defun orgtbl-error ()
11543 "Error when there is no default binding for a table key."
11544 (interactive)
11545 (error "This key has no function outside tables"))
11547 (defun orgtbl-setup ()
11548 "Setup orgtbl keymaps."
11549 (let ((nfunc 0)
11550 (bindings
11551 (list
11552 '([(meta shift left)] org-table-delete-column)
11553 '([(meta left)] org-table-move-column-left)
11554 '([(meta right)] org-table-move-column-right)
11555 '([(meta shift right)] org-table-insert-column)
11556 '([(meta shift up)] org-table-kill-row)
11557 '([(meta shift down)] org-table-insert-row)
11558 '([(meta up)] org-table-move-row-up)
11559 '([(meta down)] org-table-move-row-down)
11560 '("\C-c\C-w" org-table-cut-region)
11561 '("\C-c\M-w" org-table-copy-region)
11562 '("\C-c\C-y" org-table-paste-rectangle)
11563 '("\C-c-" org-table-insert-hline)
11564 '("\C-c}" org-table-toggle-coordinate-overlays)
11565 '("\C-c{" org-table-toggle-formula-debugger)
11566 '("\C-m" org-table-next-row)
11567 '([(shift return)] org-table-copy-down)
11568 '("\C-c\C-q" org-table-wrap-region)
11569 '("\C-c?" org-table-field-info)
11570 '("\C-c " org-table-blank-field)
11571 '("\C-c+" org-table-sum)
11572 '("\C-c=" org-table-eval-formula)
11573 '("\C-c'" org-table-edit-formulas)
11574 '("\C-c`" org-table-edit-field)
11575 '("\C-c*" org-table-recalculate)
11576 '("\C-c|" org-table-create-or-convert-from-region)
11577 '("\C-c^" org-table-sort-lines)
11578 '([(control ?#)] org-table-rotate-recalc-marks)))
11579 elt key fun cmd)
11580 (while (setq elt (pop bindings))
11581 (setq nfunc (1+ nfunc))
11582 (setq key (org-key (car elt))
11583 fun (nth 1 elt)
11584 cmd (orgtbl-make-binding fun nfunc key))
11585 (org-defkey orgtbl-mode-map key cmd))
11587 ;; Special treatment needed for TAB and RET
11588 (org-defkey orgtbl-mode-map [(return)]
11589 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11590 (org-defkey orgtbl-mode-map "\C-m"
11591 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11593 (org-defkey orgtbl-mode-map [(tab)]
11594 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11595 (org-defkey orgtbl-mode-map "\C-i"
11596 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)]))
11598 (org-defkey orgtbl-mode-map [(shift tab)]
11599 (orgtbl-make-binding 'org-table-previous-field 104
11600 [(shift tab)] [(tab)] "\C-i"))
11602 (org-defkey orgtbl-mode-map "\M-\C-m"
11603 (orgtbl-make-binding 'org-table-wrap-region 105
11604 "\M-\C-m" [(meta return)]))
11605 (org-defkey orgtbl-mode-map [(meta return)]
11606 (orgtbl-make-binding 'org-table-wrap-region 106
11607 [(meta return)] "\M-\C-m"))
11609 (org-defkey orgtbl-mode-map "\C-c\C-c" 'orgtbl-ctrl-c-ctrl-c)
11610 (when orgtbl-optimized
11611 ;; If the user wants maximum table support, we need to hijack
11612 ;; some standard editing functions
11613 (org-remap orgtbl-mode-map
11614 'self-insert-command 'orgtbl-self-insert-command
11615 'delete-char 'org-delete-char
11616 'delete-backward-char 'org-delete-backward-char)
11617 (org-defkey orgtbl-mode-map "|" 'org-force-self-insert))
11618 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11619 '("OrgTbl"
11620 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11621 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11622 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11623 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11624 "--"
11625 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11626 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11627 ["Copy Field from Above"
11628 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11629 "--"
11630 ("Column"
11631 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11632 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11633 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11634 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
11635 ("Row"
11636 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11637 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11638 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11639 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11640 ["Sort lines in region" org-table-sort-lines :active (org-at-table-p) :keys "C-c ^"]
11641 "--"
11642 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11643 ("Rectangle"
11644 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11645 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11646 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11647 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11648 "--"
11649 ("Radio tables"
11650 ["Insert table template" orgtbl-insert-radio-table
11651 (assq major-mode orgtbl-radio-table-templates)]
11652 ["Comment/uncomment table" orgtbl-toggle-comment t])
11653 "--"
11654 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11655 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11656 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11657 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11658 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11659 ["Iterate all" (org-table-recalculate '(16)) :active (org-at-table-p) :keys "C-u C-u C-c *"]
11660 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11661 ["Sum Column/Rectangle" org-table-sum
11662 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11663 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11664 ["Debug Formulas"
11665 org-table-toggle-formula-debugger :active (org-at-table-p)
11666 :keys "C-c {"
11667 :style toggle :selected org-table-formula-debug]
11668 ["Show Col/Row Numbers"
11669 org-table-toggle-coordinate-overlays :active (org-at-table-p)
11670 :keys "C-c }"
11671 :style toggle :selected org-table-overlay-coordinates]
11675 (defun orgtbl-ctrl-c-ctrl-c (arg)
11676 "If the cursor is inside a table, realign the table.
11677 It it is a table to be sent away to a receiver, do it.
11678 With prefix arg, also recompute table."
11679 (interactive "P")
11680 (let ((pos (point)) action)
11681 (save-excursion
11682 (beginning-of-line 1)
11683 (setq action (cond ((looking-at "#\\+ORGTBL:.*\n[ \t]*|") (match-end 0))
11684 ((looking-at "[ \t]*|") pos)
11685 ((looking-at "#\\+TBLFM:") 'recalc))))
11686 (cond
11687 ((integerp action)
11688 (goto-char action)
11689 (org-table-maybe-eval-formula)
11690 (if arg
11691 (call-interactively 'org-table-recalculate)
11692 (org-table-maybe-recalculate-line))
11693 (call-interactively 'org-table-align)
11694 (orgtbl-send-table 'maybe))
11695 ((eq action 'recalc)
11696 (save-excursion
11697 (beginning-of-line 1)
11698 (skip-chars-backward " \r\n\t")
11699 (if (org-at-table-p)
11700 (org-call-with-arg 'org-table-recalculate t))))
11701 (t (let (orgtbl-mode)
11702 (call-interactively (key-binding "\C-c\C-c")))))))
11704 (defun orgtbl-tab (arg)
11705 "Justification and field motion for `orgtbl-mode'."
11706 (interactive "P")
11707 (if arg (org-table-edit-field t)
11708 (org-table-justify-field-maybe)
11709 (org-table-next-field)))
11711 (defun orgtbl-ret ()
11712 "Justification and field motion for `orgtbl-mode'."
11713 (interactive)
11714 (org-table-justify-field-maybe)
11715 (org-table-next-row))
11717 (defun orgtbl-self-insert-command (N)
11718 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11719 If the cursor is in a table looking at whitespace, the whitespace is
11720 overwritten, and the table is not marked as requiring realignment."
11721 (interactive "p")
11722 (if (and (org-at-table-p)
11724 (and org-table-auto-blank-field
11725 (member last-command
11726 '(orgtbl-hijacker-command-100
11727 orgtbl-hijacker-command-101
11728 orgtbl-hijacker-command-102
11729 orgtbl-hijacker-command-103
11730 orgtbl-hijacker-command-104
11731 orgtbl-hijacker-command-105))
11732 (org-table-blank-field))
11734 (eq N 1)
11735 (looking-at "[^|\n]* +|"))
11736 (let (org-table-may-need-update)
11737 (goto-char (1- (match-end 0)))
11738 (delete-backward-char 1)
11739 (goto-char (match-beginning 0))
11740 (self-insert-command N))
11741 (setq org-table-may-need-update t)
11742 (let (orgtbl-mode)
11743 (call-interactively (key-binding (vector last-input-event))))))
11745 (defun org-force-self-insert (N)
11746 "Needed to enforce self-insert under remapping."
11747 (interactive "p")
11748 (self-insert-command N))
11750 (defvar orgtbl-exp-regexp "^\\([-+]?[0-9][0-9.]*\\)[eE]\\([-+]?[0-9]+\\)$"
11751 "Regula expression matching exponentials as produced by calc.")
11753 (defvar org-table-clean-did-remove-column nil)
11755 (defun orgtbl-export (table target)
11756 (let ((func (intern (concat "orgtbl-to-" (symbol-name target))))
11757 (lines (org-split-string table "[ \t]*\n[ \t]*"))
11758 org-table-last-alignment org-table-last-column-widths
11759 maxcol column)
11760 (if (not (fboundp func))
11761 (error "Cannot export orgtbl table to %s" target))
11762 (setq lines (org-table-clean-before-export lines))
11763 (setq table
11764 (mapcar
11765 (lambda (x)
11766 (if (string-match org-table-hline-regexp x)
11767 'hline
11768 (org-split-string (org-trim x) "\\s-*|\\s-*")))
11769 lines))
11770 (setq maxcol (apply 'max (mapcar (lambda (x) (if (listp x) (length x) 0))
11771 table)))
11772 (loop for i from (1- maxcol) downto 0 do
11773 (setq column (mapcar (lambda (x) (if (listp x) (nth i x) nil)) table))
11774 (setq column (delq nil column))
11775 (push (apply 'max (mapcar 'string-width column)) org-table-last-column-widths)
11776 (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))
11777 (funcall func table nil)))
11779 (defun orgtbl-send-table (&optional maybe)
11780 "Send a tranformed version of this table to the receiver position.
11781 With argument MAYBE, fail quietly if no transformation is defined for
11782 this table."
11783 (interactive)
11784 (catch 'exit
11785 (unless (org-at-table-p) (error "Not at a table"))
11786 ;; when non-interactive, we assume align has just happened.
11787 (when (interactive-p) (org-table-align))
11788 (save-excursion
11789 (goto-char (org-table-begin))
11790 (beginning-of-line 0)
11791 (unless (looking-at "#\\+ORGTBL: *SEND +\\([a-zA-Z0-9_]+\\) +\\([^ \t\r\n]+\\)\\( +.*\\)?")
11792 (if maybe
11793 (throw 'exit nil)
11794 (error "Don't know how to transform this table."))))
11795 (let* ((name (match-string 1))
11797 (transform (intern (match-string 2)))
11798 (params (if (match-end 3) (read (concat "(" (match-string 3) ")"))))
11799 (skip (plist-get params :skip))
11800 (skipcols (plist-get params :skipcols))
11801 (txt (buffer-substring-no-properties
11802 (org-table-begin) (org-table-end)))
11803 (lines (nthcdr (or skip 0) (org-split-string txt "[ \t]*\n[ \t]*")))
11804 (lines (org-table-clean-before-export lines))
11805 (i0 (if org-table-clean-did-remove-column 2 1))
11806 (table (mapcar
11807 (lambda (x)
11808 (if (string-match org-table-hline-regexp x)
11809 'hline
11810 (org-remove-by-index
11811 (org-split-string (org-trim x) "\\s-*|\\s-*")
11812 skipcols i0)))
11813 lines))
11814 (fun (if (= i0 2) 'cdr 'identity))
11815 (org-table-last-alignment
11816 (org-remove-by-index (funcall fun org-table-last-alignment)
11817 skipcols i0))
11818 (org-table-last-column-widths
11819 (org-remove-by-index (funcall fun org-table-last-column-widths)
11820 skipcols i0)))
11822 (unless (fboundp transform)
11823 (error "No such transformation function %s" transform))
11824 (setq txt (funcall transform table params))
11825 ;; Find the insertion place
11826 (save-excursion
11827 (goto-char (point-min))
11828 (unless (re-search-forward
11829 (concat "BEGIN RECEIVE ORGTBL +" name "\\([ \t]\\|$\\)") nil t)
11830 (error "Don't know where to insert translated table"))
11831 (goto-char (match-beginning 0))
11832 (beginning-of-line 2)
11833 (setq beg (point))
11834 (unless (re-search-forward (concat "END RECEIVE ORGTBL +" name) nil t)
11835 (error "Cannot find end of insertion region"))
11836 (beginning-of-line 1)
11837 (delete-region beg (point))
11838 (goto-char beg)
11839 (insert txt "\n"))
11840 (message "Table converted and installed at receiver location"))))
11842 (defun org-remove-by-index (list indices &optional i0)
11843 "Remove the elements in LIST with indices in INDICES.
11844 First element has index 0, or I0 if given."
11845 (if (not indices)
11846 list
11847 (if (integerp indices) (setq indices (list indices)))
11848 (setq i0 (1- (or i0 0)))
11849 (delq :rm (mapcar (lambda (x)
11850 (setq i0 (1+ i0))
11851 (if (memq i0 indices) :rm x))
11852 list))))
11854 (defun orgtbl-toggle-comment ()
11855 "Comment or uncomment the orgtbl at point."
11856 (interactive)
11857 (let* ((re1 (concat "^" (regexp-quote comment-start) orgtbl-line-start-regexp))
11858 (re2 (concat "^" orgtbl-line-start-regexp))
11859 (commented (save-excursion (beginning-of-line 1)
11860 (cond ((looking-at re1) t)
11861 ((looking-at re2) nil)
11862 (t (error "Not at an org table")))))
11863 (re (if commented re1 re2))
11864 beg end)
11865 (save-excursion
11866 (beginning-of-line 1)
11867 (while (looking-at re) (beginning-of-line 0))
11868 (beginning-of-line 2)
11869 (setq beg (point))
11870 (while (looking-at re) (beginning-of-line 2))
11871 (setq end (point)))
11872 (comment-region beg end (if commented '(4) nil))))
11874 (defun orgtbl-insert-radio-table ()
11875 "Insert a radio table template appropriate for this major mode."
11876 (interactive)
11877 (let* ((e (assq major-mode orgtbl-radio-table-templates))
11878 (txt (nth 1 e))
11879 name pos)
11880 (unless e (error "No radio table setup defined for %s" major-mode))
11881 (setq name (read-string "Table name: "))
11882 (while (string-match "%n" txt)
11883 (setq txt (replace-match name t t txt)))
11884 (or (bolp) (insert "\n"))
11885 (setq pos (point))
11886 (insert txt)
11887 (goto-char pos)))
11889 (defun org-get-param (params header i sym &optional hsym)
11890 "Get parameter value for symbol SYM.
11891 If this is a header line, actually get the value for the symbol with an
11892 additional \"h\" inserted after the colon.
11893 If the value is a protperty list, get the element for the current column.
11894 Assumes variables VAL, PARAMS, HEAD and I to be scoped into the function."
11895 (let ((val (plist-get params sym)))
11896 (and hsym header (setq val (or (plist-get params hsym) val)))
11897 (if (consp val) (plist-get val i) val)))
11899 (defun orgtbl-to-generic (table params)
11900 "Convert the orgtbl-mode TABLE to some other format.
11901 This generic routine can be used for many standard cases.
11902 TABLE is a list, each entry either the symbol `hline' for a horizontal
11903 separator line, or a list of fields for that line.
11904 PARAMS is a property list of parameters that can influence the conversion.
11905 For the generic converter, some parameters are obligatory: You need to
11906 specify either :lfmt, or all of (:lstart :lend :sep). If you do not use
11907 :splice, you must have :tstart and :tend.
11909 Valid parameters are
11911 :tstart String to start the table. Ignored when :splice is t.
11912 :tend String to end the table. Ignored when :splice is t.
11914 :splice When set to t, return only table body lines, don't wrap
11915 them into :tstart and :tend. Default is nil.
11917 :hline String to be inserted on horizontal separation lines.
11918 May be nil to ignore hlines.
11920 :lstart String to start a new table line.
11921 :lend String to end a table line
11922 :sep Separator between two fields
11923 :lfmt Format for entire line, with enough %s to capture all fields.
11924 If this is present, :lstart, :lend, and :sep are ignored.
11925 :fmt A format to be used to wrap the field, should contain
11926 %s for the original field value. For example, to wrap
11927 everything in dollars, you could use :fmt \"$%s$\".
11928 This may also be a property list with column numbers and
11929 formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
11931 :hlstart :hlend :hlsep :hlfmt :hfmt
11932 Same as above, specific for the header lines in the table.
11933 All lines before the first hline are treated as header.
11934 If any of these is not present, the data line value is used.
11936 :efmt Use this format to print numbers with exponentials.
11937 The format should have %s twice for inserting mantissa
11938 and exponent, for example \"%s\\\\times10^{%s}\". This
11939 may also be a property list with column numbers and
11940 formats. :fmt will still be applied after :efmt.
11942 In addition to this, the parameters :skip and :skipcols are always handled
11943 directly by `orgtbl-send-table'. See manual."
11944 (interactive)
11945 (let* ((p params)
11946 (splicep (plist-get p :splice))
11947 (hline (plist-get p :hline))
11948 rtn line i fm efm lfmt h)
11950 ;; Do we have a header?
11951 (if (and (not splicep) (listp (car table)) (memq 'hline table))
11952 (setq h t))
11954 ;; Put header
11955 (unless splicep
11956 (push (or (plist-get p :tstart) "ERROR: no :tstart") rtn))
11958 ;; Now loop over all lines
11959 (while (setq line (pop table))
11960 (if (eq line 'hline)
11961 ;; A horizontal separator line
11962 (progn (if hline (push hline rtn))
11963 (setq h nil)) ; no longer in header
11964 ;; A normal line. Convert the fields, push line onto the result list
11965 (setq i 0)
11966 (setq line
11967 (mapcar
11968 (lambda (f)
11969 (setq i (1+ i)
11970 fm (org-get-param p h i :fmt :hfmt)
11971 efm (org-get-param p h i :efmt))
11972 (if (and efm (string-match orgtbl-exp-regexp f))
11973 (setq f (format
11974 efm (match-string 1 f) (match-string 2 f))))
11975 (if fm (setq f (format fm f)))
11977 line))
11978 (if (setq lfmt (org-get-param p h i :lfmt :hlfmt))
11979 (push (apply 'format lfmt line) rtn)
11980 (push (concat
11981 (org-get-param p h i :lstart :hlstart)
11982 (mapconcat 'identity line (org-get-param p h i :sep :hsep))
11983 (org-get-param p h i :lend :hlend))
11984 rtn))))
11986 (unless splicep
11987 (push (or (plist-get p :tend) "ERROR: no :tend") rtn))
11989 (mapconcat 'identity (nreverse rtn) "\n")))
11991 (defun orgtbl-to-latex (table params)
11992 "Convert the orgtbl-mode TABLE to LaTeX.
11993 TABLE is a list, each entry either the symbol `hline' for a horizontal
11994 separator line, or a list of fields for that line.
11995 PARAMS is a property list of parameters that can influence the conversion.
11996 Supports all parameters from `orgtbl-to-generic'. Most important for
11997 LaTeX are:
11999 :splice When set to t, return only table body lines, don't wrap
12000 them into a tabular environment. Default is nil.
12002 :fmt A format to be used to wrap the field, should contain %s for the
12003 original field value. For example, to wrap everything in dollars,
12004 use :fmt \"$%s$\". This may also be a property list with column
12005 numbers and formats. For example :fmt (2 \"$%s$\" 4 \"%s%%\")
12007 :efmt Format for transforming numbers with exponentials. The format
12008 should have %s twice for inserting mantissa and exponent, for
12009 example \"%s\\\\times10^{%s}\". LaTeX default is \"%s\\\\,(%s)\".
12010 This may also be a property list with column numbers and formats.
12012 The general parameters :skip and :skipcols have already been applied when
12013 this function is called."
12014 (let* ((alignment (mapconcat (lambda (x) (if x "r" "l"))
12015 org-table-last-alignment ""))
12016 (params2
12017 (list
12018 :tstart (concat "\\begin{tabular}{" alignment "}")
12019 :tend "\\end{tabular}"
12020 :lstart "" :lend " \\\\" :sep " & "
12021 :efmt "%s\\,(%s)" :hline "\\hline")))
12022 (orgtbl-to-generic table (org-combine-plists params2 params))))
12024 (defun orgtbl-to-html (table params)
12025 "Convert the orgtbl-mode TABLE to LaTeX.
12026 TABLE is a list, each entry either the symbol `hline' for a horizontal
12027 separator line, or a list of fields for that line.
12028 PARAMS is a property list of parameters that can influence the conversion.
12029 Currently this function recognizes the following parameters:
12031 :splice When set to t, return only table body lines, don't wrap
12032 them into a <table> environment. Default is nil.
12034 The general parameters :skip and :skipcols have already been applied when
12035 this function is called. The function does *not* use `orgtbl-to-generic',
12036 so you cannot specify parameters for it."
12037 (let* ((splicep (plist-get params :splice))
12038 html)
12039 ;; Just call the formatter we already have
12040 ;; We need to make text lines for it, so put the fields back together.
12041 (setq html (org-format-org-table-html
12042 (mapcar
12043 (lambda (x)
12044 (if (eq x 'hline)
12045 "|----+----|"
12046 (concat "| " (mapconcat 'identity x " | ") " |")))
12047 table)
12048 splicep))
12049 (if (string-match "\n+\\'" html)
12050 (setq html (replace-match "" t t html)))
12051 html))
12053 (defun orgtbl-to-texinfo (table params)
12054 "Convert the orgtbl-mode TABLE to TeXInfo.
12055 TABLE is a list, each entry either the symbol `hline' for a horizontal
12056 separator line, or a list of fields for that line.
12057 PARAMS is a property list of parameters that can influence the conversion.
12058 Supports all parameters from `orgtbl-to-generic'. Most important for
12059 TeXInfo are:
12061 :splice nil/t When set to t, return only table body lines, don't wrap
12062 them into a multitable environment. Default is nil.
12064 :fmt fmt A format to be used to wrap the field, should contain
12065 %s for the original field value. For example, to wrap
12066 everything in @kbd{}, you could use :fmt \"@kbd{%s}\".
12067 This may also be a property list with column numbers and
12068 formats. For example :fmt (2 \"@kbd{%s}\" 4 \"@code{%s}\").
12070 :cf \"f1 f2..\" The column fractions for the table. By default these
12071 are computed automatically from the width of the columns
12072 under org-mode.
12074 The general parameters :skip and :skipcols have already been applied when
12075 this function is called."
12076 (let* ((total (float (apply '+ org-table-last-column-widths)))
12077 (colfrac (or (plist-get params :cf)
12078 (mapconcat
12079 (lambda (x) (format "%.3f" (/ (float x) total)))
12080 org-table-last-column-widths " ")))
12081 (params2
12082 (list
12083 :tstart (concat "@multitable @columnfractions " colfrac)
12084 :tend "@end multitable"
12085 :lstart "@item " :lend "" :sep " @tab "
12086 :hlstart "@headitem ")))
12087 (orgtbl-to-generic table (org-combine-plists params2 params))))
12089 ;;;; Link Stuff
12091 ;;; Link abbreviations
12093 (defun org-link-expand-abbrev (link)
12094 "Apply replacements as defined in `org-link-abbrev-alist."
12095 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
12096 (let* ((key (match-string 1 link))
12097 (as (or (assoc key org-link-abbrev-alist-local)
12098 (assoc key org-link-abbrev-alist)))
12099 (tag (and (match-end 2) (match-string 3 link)))
12100 rpl)
12101 (if (not as)
12102 link
12103 (setq rpl (cdr as))
12104 (cond
12105 ((symbolp rpl) (funcall rpl tag))
12106 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
12107 (t (concat rpl tag)))))
12108 link))
12110 ;;; Storing and inserting links
12112 (defvar org-insert-link-history nil
12113 "Minibuffer history for links inserted with `org-insert-link'.")
12115 (defvar org-stored-links nil
12116 "Contains the links stored with `org-store-link'.")
12118 (defvar org-store-link-plist nil
12119 "Plist with info about the most recently link created with `org-store-link'.")
12121 (defvar org-link-protocols nil
12122 "Link protocols added to Org-mode using `org-add-link-type'.")
12124 (defvar org-store-link-functions nil
12125 "List of functions that are called to create and store a link.
12126 Each function will be called in turn until one returns a non-nil
12127 value. Each function should check if it is responsible for creating
12128 this link (for example by looking at the major mode).
12129 If not, it must exit and return nil.
12130 If yes, it should return a non-nil value after a calling
12131 `org-store-link-props' with a list of properties and values.
12132 Special properties are:
12134 :type The link prefix. like \"http\". This must be given.
12135 :link The link, like \"http://www.astro.uva.nl/~dominik\".
12136 This is obligatory as well.
12137 :description Optional default description for the second pair
12138 of brackets in an Org-mode link. The user can still change
12139 this when inserting this link into an Org-mode buffer.
12141 In addition to these, any additional properties can be specified
12142 and then used in remember templates.")
12144 (defun org-add-link-type (type &optional follow publish)
12145 "Add TYPE to the list of `org-link-types'.
12146 Re-compute all regular expressions depending on `org-link-types'
12147 FOLLOW and PUBLISH are two functions. Both take the link path as
12148 an argument.
12149 FOLLOW should do whatever is necessary to follow the link, for example
12150 to find a file or display a mail message.
12152 PUBLISH takes the path and retuns the string that should be used when
12153 this document is published. FIMXE: This is actually not yet implemented."
12154 (add-to-list 'org-link-types type t)
12155 (org-make-link-regexps)
12156 (add-to-list 'org-link-protocols
12157 (list type follow publish)))
12159 (defun org-add-agenda-custom-command (entry)
12160 "Replace or add a command in `org-agenda-custom-commands'.
12161 This is mostly for hacking and trying a new command - once the command
12162 works you probably want to add it to `org-agenda-custom-commands' for good."
12163 (let ((ass (assoc (car entry) org-agenda-custom-commands)))
12164 (if ass
12165 (setcdr ass (cdr entry))
12166 (push entry org-agenda-custom-commands))))
12168 ;;;###autoload
12169 (defun org-store-link (arg)
12170 "\\<org-mode-map>Store an org-link to the current location.
12171 This link is added to `org-stored-links' and can later be inserted
12172 into an org-buffer with \\[org-insert-link].
12174 For some link types, a prefix arg is interpreted:
12175 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
12176 For file links, arg negates `org-context-in-file-links'."
12177 (interactive "P")
12178 (setq org-store-link-plist nil) ; reset
12179 (let (link cpltxt desc description search txt)
12180 (cond
12182 ((run-hook-with-args-until-success 'org-store-link-functions)
12183 (setq link (plist-get org-store-link-plist :link)
12184 desc (or (plist-get org-store-link-plist :description) link)))
12186 ((eq major-mode 'bbdb-mode)
12187 (let ((name (bbdb-record-name (bbdb-current-record)))
12188 (company (bbdb-record-getprop (bbdb-current-record) 'company)))
12189 (setq cpltxt (concat "bbdb:" (or name company))
12190 link (org-make-link cpltxt))
12191 (org-store-link-props :type "bbdb" :name name :company company)))
12193 ((eq major-mode 'Info-mode)
12194 (setq link (org-make-link "info:"
12195 (file-name-nondirectory Info-current-file)
12196 ":" Info-current-node))
12197 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
12198 ":" Info-current-node))
12199 (org-store-link-props :type "info" :file Info-current-file
12200 :node Info-current-node))
12202 ((eq major-mode 'calendar-mode)
12203 (let ((cd (calendar-cursor-to-date)))
12204 (setq link
12205 (format-time-string
12206 (car org-time-stamp-formats)
12207 (apply 'encode-time
12208 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
12209 nil nil nil))))
12210 (org-store-link-props :type "calendar" :date cd)))
12212 ((or (eq major-mode 'vm-summary-mode)
12213 (eq major-mode 'vm-presentation-mode))
12214 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
12215 (vm-follow-summary-cursor)
12216 (save-excursion
12217 (vm-select-folder-buffer)
12218 (let* ((message (car vm-message-pointer))
12219 (folder buffer-file-name)
12220 (subject (vm-su-subject message))
12221 (to (vm-get-header-contents message "To"))
12222 (from (vm-get-header-contents message "From"))
12223 (message-id (vm-su-message-id message)))
12224 (org-store-link-props :type "vm" :from from :to to :subject subject
12225 :message-id message-id)
12226 (setq message-id (org-remove-angle-brackets message-id))
12227 (setq folder (abbreviate-file-name folder))
12228 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
12229 folder)
12230 (setq folder (replace-match "" t t folder)))
12231 (setq cpltxt (org-email-link-description))
12232 (setq link (org-make-link "vm:" folder "#" message-id)))))
12234 ((eq major-mode 'wl-summary-mode)
12235 (let* ((msgnum (wl-summary-message-number))
12236 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
12237 msgnum 'message-id))
12238 (wl-message-entity
12239 (if (fboundp 'elmo-message-entity)
12240 (elmo-message-entity
12241 wl-summary-buffer-elmo-folder msgnum)
12242 (elmo-msgdb-overview-get-entity
12243 msgnum (wl-summary-buffer-msgdb))))
12244 (from (wl-summary-line-from))
12245 (to (car (elmo-message-entity-field wl-message-entity 'to)))
12246 (subject (let (wl-thr-indent-string wl-parent-message-entity)
12247 (wl-summary-line-subject))))
12248 (org-store-link-props :type "wl" :from from :to to
12249 :subject subject :message-id message-id)
12250 (setq message-id (org-remove-angle-brackets message-id))
12251 (setq cpltxt (org-email-link-description))
12252 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
12253 "#" message-id))))
12255 ((or (equal major-mode 'mh-folder-mode)
12256 (equal major-mode 'mh-show-mode))
12257 (let ((from (org-mhe-get-header "From:"))
12258 (to (org-mhe-get-header "To:"))
12259 (message-id (org-mhe-get-header "Message-Id:"))
12260 (subject (org-mhe-get-header "Subject:")))
12261 (org-store-link-props :type "mh" :from from :to to
12262 :subject subject :message-id message-id)
12263 (setq cpltxt (org-email-link-description))
12264 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
12265 (org-remove-angle-brackets message-id)))))
12267 ((or (eq major-mode 'rmail-mode)
12268 (eq major-mode 'rmail-summary-mode))
12269 (save-window-excursion
12270 (save-restriction
12271 (when (eq major-mode 'rmail-summary-mode)
12272 (rmail-show-message rmail-current-message))
12273 (rmail-narrow-to-non-pruned-header)
12274 (let ((folder buffer-file-name)
12275 (message-id (mail-fetch-field "message-id"))
12276 (from (mail-fetch-field "from"))
12277 (to (mail-fetch-field "to"))
12278 (subject (mail-fetch-field "subject")))
12279 (org-store-link-props
12280 :type "rmail" :from from :to to
12281 :subject subject :message-id message-id)
12282 (setq message-id (org-remove-angle-brackets message-id))
12283 (setq cpltxt (org-email-link-description))
12284 (setq link (org-make-link "rmail:" folder "#" message-id)))
12285 (rmail-show-message rmail-current-message))))
12287 ((eq major-mode 'gnus-group-mode)
12288 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
12289 (gnus-group-group-name)) ; version
12290 ((fboundp 'gnus-group-name)
12291 (gnus-group-name))
12292 (t "???"))))
12293 (unless group (error "Not on a group"))
12294 (org-store-link-props :type "gnus" :group group)
12295 (setq cpltxt (concat
12296 (if (org-xor arg org-usenet-links-prefer-google)
12297 "http://groups.google.com/groups?group="
12298 "gnus:")
12299 group)
12300 link (org-make-link cpltxt))))
12302 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
12303 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
12304 (let* ((group gnus-newsgroup-name)
12305 (article (gnus-summary-article-number))
12306 (header (gnus-summary-article-header article))
12307 (from (mail-header-from header))
12308 (message-id (mail-header-id header))
12309 (date (mail-header-date header))
12310 (subject (gnus-summary-subject-string)))
12311 (org-store-link-props :type "gnus" :from from :subject subject
12312 :message-id message-id :group group)
12313 (setq cpltxt (org-email-link-description))
12314 (if (org-xor arg org-usenet-links-prefer-google)
12315 (setq link
12316 (concat
12317 cpltxt "\n "
12318 (format "http://groups.google.com/groups?as_umsgid=%s"
12319 (org-fixup-message-id-for-http message-id))))
12320 (setq link (org-make-link "gnus:" group
12321 "#" (number-to-string article))))))
12323 ((eq major-mode 'w3-mode)
12324 (setq cpltxt (url-view-url t)
12325 link (org-make-link cpltxt))
12326 (org-store-link-props :type "w3" :url (url-view-url t)))
12328 ((eq major-mode 'w3m-mode)
12329 (setq cpltxt (or w3m-current-title w3m-current-url)
12330 link (org-make-link w3m-current-url))
12331 (org-store-link-props :type "w3m" :url (url-view-url t)))
12333 ((setq search (run-hook-with-args-until-success
12334 'org-create-file-search-functions))
12335 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
12336 "::" search))
12337 (setq cpltxt (or description link)))
12339 ((eq major-mode 'image-mode)
12340 (setq cpltxt (concat "file:"
12341 (abbreviate-file-name buffer-file-name))
12342 link (org-make-link cpltxt))
12343 (org-store-link-props :type "image" :file buffer-file-name))
12345 ((eq major-mode 'dired-mode)
12346 ;; link to the file in the current line
12347 (setq cpltxt (concat "file:"
12348 (abbreviate-file-name
12349 (expand-file-name
12350 (dired-get-filename nil t))))
12351 link (org-make-link cpltxt)))
12353 ((and buffer-file-name (org-mode-p))
12354 ;; Just link to current headline
12355 (setq cpltxt (concat "file:"
12356 (abbreviate-file-name buffer-file-name)))
12357 ;; Add a context search string
12358 (when (org-xor org-context-in-file-links arg)
12359 ;; Check if we are on a target
12360 (if (org-in-regexp "<<\\(.*?\\)>>")
12361 (setq cpltxt (concat cpltxt "::" (match-string 1)))
12362 (setq txt (cond
12363 ((org-on-heading-p) nil)
12364 ((org-region-active-p)
12365 (buffer-substring (region-beginning) (region-end)))
12366 (t (buffer-substring (point-at-bol) (point-at-eol)))))
12367 (when (or (null txt) (string-match "\\S-" txt))
12368 (setq cpltxt
12369 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12370 desc "NONE"))))
12371 (if (string-match "::\\'" cpltxt)
12372 (setq cpltxt (substring cpltxt 0 -2)))
12373 (setq link (org-make-link cpltxt)))
12375 ((buffer-file-name (buffer-base-buffer))
12376 ;; Just link to this file here.
12377 (setq cpltxt (concat "file:"
12378 (abbreviate-file-name
12379 (buffer-file-name (buffer-base-buffer)))))
12380 ;; Add a context string
12381 (when (org-xor org-context-in-file-links arg)
12382 (setq txt (if (org-region-active-p)
12383 (buffer-substring (region-beginning) (region-end))
12384 (buffer-substring (point-at-bol) (point-at-eol))))
12385 ;; Only use search option if there is some text.
12386 (when (string-match "\\S-" txt)
12387 (setq cpltxt
12388 (concat cpltxt "::" (org-make-org-heading-search-string txt))
12389 desc "NONE")))
12390 (setq link (org-make-link cpltxt)))
12392 ((interactive-p)
12393 (error "Cannot link to a buffer which is not visiting a file"))
12395 (t (setq link nil)))
12397 (if (consp link) (setq cpltxt (car link) link (cdr link)))
12398 (setq link (or link cpltxt)
12399 desc (or desc cpltxt))
12400 (if (equal desc "NONE") (setq desc nil))
12402 (if (and (interactive-p) link)
12403 (progn
12404 (setq org-stored-links
12405 (cons (list link desc) org-stored-links))
12406 (message "Stored: %s" (or desc link)))
12407 (and link (org-make-link-string link desc)))))
12409 (defun org-store-link-props (&rest plist)
12410 "Store link properties, extract names and addresses."
12411 (let (x adr)
12412 (when (setq x (plist-get plist :from))
12413 (setq adr (mail-extract-address-components x))
12414 (plist-put plist :fromname (car adr))
12415 (plist-put plist :fromaddress (nth 1 adr)))
12416 (when (setq x (plist-get plist :to))
12417 (setq adr (mail-extract-address-components x))
12418 (plist-put plist :toname (car adr))
12419 (plist-put plist :toaddress (nth 1 adr))))
12420 (let ((from (plist-get plist :from))
12421 (to (plist-get plist :to)))
12422 (when (and from to org-from-is-user-regexp)
12423 (plist-put plist :fromto
12424 (if (string-match org-from-is-user-regexp from)
12425 (concat "to %t")
12426 (concat "from %f")))))
12427 (setq org-store-link-plist plist))
12429 (defun org-email-link-description (&optional fmt)
12430 "Return the description part of an email link.
12431 This takes information from `org-store-link-plist' and formats it
12432 according to FMT (default from `org-email-link-description-format')."
12433 (setq fmt (or fmt org-email-link-description-format))
12434 (let* ((p org-store-link-plist)
12435 (to (plist-get p :toaddress))
12436 (from (plist-get p :fromaddress))
12437 (table
12438 (list
12439 (cons "%c" (plist-get p :fromto))
12440 (cons "%F" (plist-get p :from))
12441 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
12442 (cons "%T" (plist-get p :to))
12443 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
12444 (cons "%s" (plist-get p :subject))
12445 (cons "%m" (plist-get p :message-id)))))
12446 (when (string-match "%c" fmt)
12447 ;; Check if the user wrote this message
12448 (if (and org-from-is-user-regexp from to
12449 (save-match-data (string-match org-from-is-user-regexp from)))
12450 (setq fmt (replace-match "to %t" t t fmt))
12451 (setq fmt (replace-match "from %f" t t fmt))))
12452 (org-replace-escapes fmt table)))
12454 (defun org-make-org-heading-search-string (&optional string heading)
12455 "Make search string for STRING or current headline."
12456 (interactive)
12457 (let ((s (or string (org-get-heading))))
12458 (unless (and string (not heading))
12459 ;; We are using a headline, clean up garbage in there.
12460 (if (string-match org-todo-regexp s)
12461 (setq s (replace-match "" t t s)))
12462 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
12463 (setq s (replace-match "" t t s)))
12464 (setq s (org-trim s))
12465 (if (string-match (concat "^\\(" org-quote-string "\\|"
12466 org-comment-string "\\)") s)
12467 (setq s (replace-match "" t t s)))
12468 (while (string-match org-ts-regexp s)
12469 (setq s (replace-match "" t t s))))
12470 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
12471 (setq s (replace-match " " t t s)))
12472 (or string (setq s (concat "*" s))) ; Add * for headlines
12473 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
12475 (defun org-make-link (&rest strings)
12476 "Concatenate STRINGS."
12477 (apply 'concat strings))
12479 (defun org-make-link-string (link &optional description)
12480 "Make a link with brackets, consisting of LINK and DESCRIPTION."
12481 (unless (string-match "\\S-" link)
12482 (error "Empty link"))
12483 (when (stringp description)
12484 ;; Remove brackets from the description, they are fatal.
12485 (while (string-match "\\[" description)
12486 (setq description (replace-match "{" t t description)))
12487 (while (string-match "\\]" description)
12488 (setq description (replace-match "}" t t description))))
12489 (when (equal (org-link-escape link) description)
12490 ;; No description needed, it is identical
12491 (setq description nil))
12492 (when (and (not description)
12493 (not (equal link (org-link-escape link))))
12494 (setq description link))
12495 (concat "[[" (org-link-escape link) "]"
12496 (if description (concat "[" description "]") "")
12497 "]"))
12499 (defconst org-link-escape-chars
12500 '((?\ . "%20")
12501 (?\[ . "%5B")
12502 (?\] . "%5D")
12503 (?\340 . "%E0") ; `a
12504 (?\342 . "%E2") ; ^a
12505 (?\347 . "%E7") ; ,c
12506 (?\350 . "%E8") ; `e
12507 (?\351 . "%E9") ; 'e
12508 (?\352 . "%EA") ; ^e
12509 (?\356 . "%EE") ; ^i
12510 (?\364 . "%F4") ; ^o
12511 (?\371 . "%F9") ; `u
12512 (?\373 . "%FB") ; ^u
12513 (?\; . "%3B")
12514 (?? . "%3F")
12515 (?= . "%3D")
12516 (?+ . "%2B")
12518 "Association list of escapes for some characters problematic in links.
12519 This is the list that is used for internal purposes.")
12521 (defconst org-link-escape-chars-browser
12522 '((?\ . "%20")) ; 32 for the SPC char
12523 "Association list of escapes for some characters problematic in links.
12524 This is the list that is used before handing over to the browser.")
12526 (defun org-link-escape (text &optional table)
12527 "Escape charaters in TEXT that are problematic for links."
12528 (setq table (or table org-link-escape-chars))
12529 (when text
12530 (let ((re (mapconcat (lambda (x) (regexp-quote
12531 (char-to-string (car x))))
12532 table "\\|")))
12533 (while (string-match re text)
12534 (setq text
12535 (replace-match
12536 (cdr (assoc (string-to-char (match-string 0 text))
12537 table))
12538 t t text)))
12539 text)))
12541 (defun org-link-unescape (text &optional table)
12542 "Reverse the action of `org-link-escape'."
12543 (setq table (or table org-link-escape-chars))
12544 (when text
12545 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
12546 table "\\|")))
12547 (while (string-match re text)
12548 (setq text
12549 (replace-match
12550 (char-to-string (car (rassoc (match-string 0 text) table)))
12551 t t text)))
12552 text)))
12554 (defun org-xor (a b)
12555 "Exclusive or."
12556 (if a (not b) b))
12558 (defun org-get-header (header)
12559 "Find a header field in the current buffer."
12560 (save-excursion
12561 (goto-char (point-min))
12562 (let ((case-fold-search t) s)
12563 (cond
12564 ((eq header 'from)
12565 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
12566 (setq s (match-string 1)))
12567 (while (string-match "\"" s)
12568 (setq s (replace-match "" t t s)))
12569 (if (string-match "[<(].*" s)
12570 (setq s (replace-match "" t t s))))
12571 ((eq header 'message-id)
12572 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
12573 (setq s (match-string 1))))
12574 ((eq header 'subject)
12575 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
12576 (setq s (match-string 1)))))
12577 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
12578 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
12579 s)))
12582 (defun org-fixup-message-id-for-http (s)
12583 "Replace special characters in a message id, so it can be used in an http query."
12584 (while (string-match "<" s)
12585 (setq s (replace-match "%3C" t t s)))
12586 (while (string-match ">" s)
12587 (setq s (replace-match "%3E" t t s)))
12588 (while (string-match "@" s)
12589 (setq s (replace-match "%40" t t s)))
12592 ;;;###autoload
12593 (defun org-insert-link-global ()
12594 "Insert a link like Org-mode does.
12595 This command can be called in any mode to insert a link in Org-mode syntax."
12596 (interactive)
12597 (org-run-like-in-org-mode 'org-insert-link))
12599 (defun org-insert-link (&optional complete-file)
12600 "Insert a link. At the prompt, enter the link.
12602 Completion can be used to select a link previously stored with
12603 `org-store-link'. When the empty string is entered (i.e. if you just
12604 press RET at the prompt), the link defaults to the most recently
12605 stored link. As SPC triggers completion in the minibuffer, you need to
12606 use M-SPC or C-q SPC to force the insertion of a space character.
12608 You will also be prompted for a description, and if one is given, it will
12609 be displayed in the buffer instead of the link.
12611 If there is already a link at point, this command will allow you to edit link
12612 and description parts.
12614 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
12615 selected using completion. The path to the file will be relative to
12616 the current directory if the file is in the current directory or a
12617 subdirectory. Otherwise, the link will be the absolute path as
12618 completed in the minibuffer (i.e. normally ~/path/to/file).
12620 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
12621 is in the current directory or below.
12622 With three \\[universal-argument] prefixes, negate the meaning of
12623 `org-keep-stored-link-after-insertion'."
12624 (interactive "P")
12625 (let* ((wcf (current-window-configuration))
12626 (region (if (org-region-active-p)
12627 (buffer-substring (region-beginning) (region-end))))
12628 (remove (and region (list (region-beginning) (region-end))))
12629 (desc region)
12630 tmphist ; byte-compile incorrectly complains about this
12631 link entry file)
12632 (cond
12633 ((org-in-regexp org-bracket-link-regexp 1)
12634 ;; We do have a link at point, and we are going to edit it.
12635 (setq remove (list (match-beginning 0) (match-end 0)))
12636 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
12637 (setq link (read-string "Link: "
12638 (org-link-unescape
12639 (org-match-string-no-properties 1)))))
12640 ((or (org-in-regexp org-angle-link-re)
12641 (org-in-regexp org-plain-link-re))
12642 ;; Convert to bracket link
12643 (setq remove (list (match-beginning 0) (match-end 0))
12644 link (read-string "Link: "
12645 (org-remove-angle-brackets (match-string 0)))))
12646 ((equal complete-file '(4))
12647 ;; Completing read for file names.
12648 (setq file (read-file-name "File: "))
12649 (let ((pwd (file-name-as-directory (expand-file-name ".")))
12650 (pwd1 (file-name-as-directory (abbreviate-file-name
12651 (expand-file-name ".")))))
12652 (cond
12653 ((equal complete-file '(16))
12654 (setq link (org-make-link
12655 "file:"
12656 (abbreviate-file-name (expand-file-name file)))))
12657 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
12658 (setq link (org-make-link "file:" (match-string 1 file))))
12659 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
12660 (expand-file-name file))
12661 (setq link (org-make-link
12662 "file:" (match-string 1 (expand-file-name file)))))
12663 (t (setq link (org-make-link "file:" file))))))
12665 ;; Read link, with completion for stored links.
12666 (with-output-to-temp-buffer "*Org Links*"
12667 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
12668 (when org-stored-links
12669 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
12670 (princ (mapconcat
12671 (lambda (x)
12672 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
12673 (reverse org-stored-links) "\n"))))
12674 (let ((cw (selected-window)))
12675 (select-window (get-buffer-window "*Org Links*"))
12676 (shrink-window-if-larger-than-buffer)
12677 (setq truncate-lines t)
12678 (select-window cw))
12679 ;; Fake a link history, containing the stored links.
12680 (setq tmphist (append (mapcar 'car org-stored-links)
12681 org-insert-link-history))
12682 (unwind-protect
12683 (setq link (org-completing-read
12684 "Link: "
12685 (append
12686 (mapcar (lambda (x) (list (concat (car x) ":")))
12687 (append org-link-abbrev-alist-local org-link-abbrev-alist))
12688 (mapcar (lambda (x) (list (concat x ":")))
12689 org-link-types))
12690 nil nil nil
12691 'tmphist
12692 (or (car (car org-stored-links)))))
12693 (set-window-configuration wcf)
12694 (kill-buffer "*Org Links*"))
12695 (setq entry (assoc link org-stored-links))
12696 (or entry (push link org-insert-link-history))
12697 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
12698 (not org-keep-stored-link-after-insertion))
12699 (setq org-stored-links (delq (assoc link org-stored-links)
12700 org-stored-links)))
12701 (setq desc (or desc (nth 1 entry)))))
12703 (if (string-match org-plain-link-re link)
12704 ;; URL-like link, normalize the use of angular brackets.
12705 (setq link (org-make-link (org-remove-angle-brackets link))))
12707 ;; Check if we are linking to the current file with a search option
12708 ;; If yes, simplify the link by using only the search option.
12709 (when (and buffer-file-name
12710 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
12711 (let* ((path (match-string 1 link))
12712 (case-fold-search nil)
12713 (search (match-string 2 link)))
12714 (save-match-data
12715 (if (equal (file-truename buffer-file-name) (file-truename path))
12716 ;; We are linking to this same file, with a search option
12717 (setq link search)))))
12719 ;; Check if we can/should use a relative path. If yes, simplify the link
12720 (when (string-match "\\<file:\\(.*\\)" link)
12721 (let* ((path (match-string 1 link))
12722 (origpath path)
12723 (case-fold-search nil))
12724 (cond
12725 ((eq org-link-file-path-type 'absolute)
12726 (setq path (abbreviate-file-name (expand-file-name path))))
12727 ((eq org-link-file-path-type 'noabbrev)
12728 (setq path (expand-file-name path)))
12729 ((eq org-link-file-path-type 'relative)
12730 (setq path (file-relative-name path)))
12732 (save-match-data
12733 (if (string-match (concat "^" (regexp-quote
12734 (file-name-as-directory
12735 (expand-file-name "."))))
12736 (expand-file-name path))
12737 ;; We are linking a file with relative path name.
12738 (setq path (substring (expand-file-name path)
12739 (match-end 0)))))))
12740 (setq link (concat "file:" path))
12741 (if (equal desc origpath)
12742 (setq desc path))))
12744 (setq desc (read-string "Description: " desc))
12745 (unless (string-match "\\S-" desc) (setq desc nil))
12746 (if remove (apply 'delete-region remove))
12747 (insert (org-make-link-string link desc))))
12749 (defun org-completing-read (&rest args)
12750 (let ((minibuffer-local-completion-map
12751 (copy-keymap minibuffer-local-completion-map)))
12752 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
12753 (apply 'completing-read args)))
12755 ;;; Opening/following a link
12756 (defvar org-link-search-failed nil)
12758 (defun org-next-link ()
12759 "Move forward to the next link.
12760 If the link is in hidden text, expose it."
12761 (interactive)
12762 (when (and org-link-search-failed (eq this-command last-command))
12763 (goto-char (point-min))
12764 (message "Link search wrapped back to beginning of buffer"))
12765 (setq org-link-search-failed nil)
12766 (let* ((pos (point))
12767 (ct (org-context))
12768 (a (assoc :link ct)))
12769 (if a (goto-char (nth 2 a)))
12770 (if (re-search-forward org-any-link-re nil t)
12771 (progn
12772 (goto-char (match-beginning 0))
12773 (if (org-invisible-p) (org-show-context)))
12774 (goto-char pos)
12775 (setq org-link-search-failed t)
12776 (error "No further link found"))))
12778 (defun org-previous-link ()
12779 "Move backward to the previous link.
12780 If the link is in hidden text, expose it."
12781 (interactive)
12782 (when (and org-link-search-failed (eq this-command last-command))
12783 (goto-char (point-max))
12784 (message "Link search wrapped back to end of buffer"))
12785 (setq org-link-search-failed nil)
12786 (let* ((pos (point))
12787 (ct (org-context))
12788 (a (assoc :link ct)))
12789 (if a (goto-char (nth 1 a)))
12790 (if (re-search-backward org-any-link-re nil t)
12791 (progn
12792 (goto-char (match-beginning 0))
12793 (if (org-invisible-p) (org-show-context)))
12794 (goto-char pos)
12795 (setq org-link-search-failed t)
12796 (error "No further link found"))))
12798 (defun org-find-file-at-mouse (ev)
12799 "Open file link or URL at mouse."
12800 (interactive "e")
12801 (mouse-set-point ev)
12802 (org-open-at-point 'in-emacs))
12804 (defun org-open-at-mouse (ev)
12805 "Open file link or URL at mouse."
12806 (interactive "e")
12807 (mouse-set-point ev)
12808 (org-open-at-point))
12810 (defvar org-window-config-before-follow-link nil
12811 "The window configuration before following a link.
12812 This is saved in case the need arises to restore it.")
12814 (defvar org-open-link-marker (make-marker)
12815 "Marker pointing to the location where `org-open-at-point; was called.")
12817 ;;;###autoload
12818 (defun org-open-at-point-global ()
12819 "Follow a link like Org-mode does.
12820 This command can be called in any mode to follow a link that has
12821 Org-mode syntax."
12822 (interactive)
12823 (org-run-like-in-org-mode 'org-open-at-point))
12825 (defun org-open-at-point (&optional in-emacs)
12826 "Open link at or after point.
12827 If there is no link at point, this function will search forward up to
12828 the end of the current subtree.
12829 Normally, files will be opened by an appropriate application. If the
12830 optional argument IN-EMACS is non-nil, Emacs will visit the file."
12831 (interactive "P")
12832 (move-marker org-open-link-marker (point))
12833 (setq org-window-config-before-follow-link (current-window-configuration))
12834 (org-remove-occur-highlights nil nil t)
12835 (if (org-at-timestamp-p t)
12836 (org-follow-timestamp-link)
12837 (let (type path link line search (pos (point)))
12838 (catch 'match
12839 (save-excursion
12840 (skip-chars-forward "^]\n\r")
12841 (when (org-in-regexp org-bracket-link-regexp)
12842 (setq link (org-link-unescape (org-match-string-no-properties 1)))
12843 (while (string-match " *\n *" link)
12844 (setq link (replace-match " " t t link)))
12845 (setq link (org-link-expand-abbrev link))
12846 (if (string-match org-link-re-with-space2 link)
12847 (setq type (match-string 1 link) path (match-string 2 link))
12848 (setq type "thisfile" path link))
12849 (throw 'match t)))
12851 (when (get-text-property (point) 'org-linked-text)
12852 (setq type "thisfile"
12853 pos (if (get-text-property (1+ (point)) 'org-linked-text)
12854 (1+ (point)) (point))
12855 path (buffer-substring
12856 (previous-single-property-change pos 'org-linked-text)
12857 (next-single-property-change pos 'org-linked-text)))
12858 (throw 'match t))
12860 (save-excursion
12861 (when (or (org-in-regexp org-angle-link-re)
12862 (org-in-regexp org-plain-link-re))
12863 (setq type (match-string 1) path (match-string 2))
12864 (throw 'match t)))
12865 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
12866 (setq type "tree-match"
12867 path (match-string 1))
12868 (throw 'match t))
12869 (save-excursion
12870 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
12871 (setq type "tags"
12872 path (match-string 1))
12873 (while (string-match ":" path)
12874 (setq path (replace-match "+" t t path)))
12875 (throw 'match t))))
12876 (unless path
12877 (error "No link found"))
12878 ;; Remove any trailing spaces in path
12879 (if (string-match " +\\'" path)
12880 (setq path (replace-match "" t t path)))
12882 (cond
12884 ((assoc type org-link-protocols)
12885 (funcall (nth 1 (assoc type org-link-protocols)) path))
12887 ((equal type "mailto")
12888 (let ((cmd (car org-link-mailto-program))
12889 (args (cdr org-link-mailto-program)) args1
12890 (address path) (subject "") a)
12891 (if (string-match "\\(.*\\)::\\(.*\\)" path)
12892 (setq address (match-string 1 path)
12893 subject (org-link-escape (match-string 2 path))))
12894 (while args
12895 (cond
12896 ((not (stringp (car args))) (push (pop args) args1))
12897 (t (setq a (pop args))
12898 (if (string-match "%a" a)
12899 (setq a (replace-match address t t a)))
12900 (if (string-match "%s" a)
12901 (setq a (replace-match subject t t a)))
12902 (push a args1))))
12903 (apply cmd (nreverse args1))))
12905 ((member type '("http" "https" "ftp" "news"))
12906 (browse-url (concat type ":" (org-link-escape
12907 path org-link-escape-chars-browser))))
12909 ((member type '("message"))
12910 (browse-url (concat type ":" path)))
12912 ((string= type "tags")
12913 (org-tags-view in-emacs path))
12914 ((string= type "thisfile")
12915 (if in-emacs
12916 (switch-to-buffer-other-window
12917 (org-get-buffer-for-internal-link (current-buffer)))
12918 (org-mark-ring-push))
12919 (let ((cmd `(org-link-search
12920 ,path
12921 ,(cond ((equal in-emacs '(4)) 'occur)
12922 ((equal in-emacs '(16)) 'org-occur)
12923 (t nil))
12924 ,pos)))
12925 (condition-case nil (eval cmd)
12926 (error (progn (widen) (eval cmd))))))
12928 ((string= type "tree-match")
12929 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
12931 ((string= type "file")
12932 (if (string-match "::\\([0-9]+\\)\\'" path)
12933 (setq line (string-to-number (match-string 1 path))
12934 path (substring path 0 (match-beginning 0)))
12935 (if (string-match "::\\(.+\\)\\'" path)
12936 (setq search (match-string 1 path)
12937 path (substring path 0 (match-beginning 0)))))
12938 (if (string-match "[*?{]" (file-name-nondirectory path))
12939 (dired path)
12940 (org-open-file path in-emacs line search)))
12942 ((string= type "news")
12943 (org-follow-gnus-link path))
12945 ((string= type "bbdb")
12946 (org-follow-bbdb-link path))
12948 ((string= type "info")
12949 (org-follow-info-link path))
12951 ((string= type "gnus")
12952 (let (group article)
12953 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12954 (error "Error in Gnus link"))
12955 (setq group (match-string 1 path)
12956 article (match-string 3 path))
12957 (org-follow-gnus-link group article)))
12959 ((string= type "vm")
12960 (let (folder article)
12961 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12962 (error "Error in VM link"))
12963 (setq folder (match-string 1 path)
12964 article (match-string 3 path))
12965 ;; in-emacs is the prefix arg, will be interpreted as read-only
12966 (org-follow-vm-link folder article in-emacs)))
12968 ((string= type "wl")
12969 (let (folder article)
12970 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12971 (error "Error in Wanderlust link"))
12972 (setq folder (match-string 1 path)
12973 article (match-string 3 path))
12974 (org-follow-wl-link folder article)))
12976 ((string= type "mhe")
12977 (let (folder article)
12978 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12979 (error "Error in MHE link"))
12980 (setq folder (match-string 1 path)
12981 article (match-string 3 path))
12982 (org-follow-mhe-link folder article)))
12984 ((string= type "rmail")
12985 (let (folder article)
12986 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
12987 (error "Error in RMAIL link"))
12988 (setq folder (match-string 1 path)
12989 article (match-string 3 path))
12990 (org-follow-rmail-link folder article)))
12992 ((string= type "shell")
12993 (let ((cmd path))
12994 (if (or (not org-confirm-shell-link-function)
12995 (funcall org-confirm-shell-link-function
12996 (format "Execute \"%s\" in shell? "
12997 (org-add-props cmd nil
12998 'face 'org-warning))))
12999 (progn
13000 (message "Executing %s" cmd)
13001 (shell-command cmd))
13002 (error "Abort"))))
13004 ((string= type "elisp")
13005 (let ((cmd path))
13006 (if (or (not org-confirm-elisp-link-function)
13007 (funcall org-confirm-elisp-link-function
13008 (format "Execute \"%s\" as elisp? "
13009 (org-add-props cmd nil
13010 'face 'org-warning))))
13011 (message "%s => %s" cmd (eval (read cmd)))
13012 (error "Abort"))))
13015 (browse-url-at-point)))))
13016 (move-marker org-open-link-marker nil)
13017 (run-hook-with-args 'org-follow-link-hook))
13019 ;;; File search
13021 (defvar org-create-file-search-functions nil
13022 "List of functions to construct the right search string for a file link.
13023 These functions are called in turn with point at the location to
13024 which the link should point.
13026 A function in the hook should first test if it would like to
13027 handle this file type, for example by checking the major-mode or
13028 the file extension. If it decides not to handle this file, it
13029 should just return nil to give other functions a chance. If it
13030 does handle the file, it must return the search string to be used
13031 when following the link. The search string will be part of the
13032 file link, given after a double colon, and `org-open-at-point'
13033 will automatically search for it. If special measures must be
13034 taken to make the search successful, another function should be
13035 added to the companion hook `org-execute-file-search-functions',
13036 which see.
13038 A function in this hook may also use `setq' to set the variable
13039 `description' to provide a suggestion for the descriptive text to
13040 be used for this link when it gets inserted into an Org-mode
13041 buffer with \\[org-insert-link].")
13043 (defvar org-execute-file-search-functions nil
13044 "List of functions to execute a file search triggered by a link.
13046 Functions added to this hook must accept a single argument, the
13047 search string that was part of the file link, the part after the
13048 double colon. The function must first check if it would like to
13049 handle this search, for example by checking the major-mode or the
13050 file extension. If it decides not to handle this search, it
13051 should just return nil to give other functions a chance. If it
13052 does handle the search, it must return a non-nil value to keep
13053 other functions from trying.
13055 Each function can access the current prefix argument through the
13056 variable `current-prefix-argument'. Note that a single prefix is
13057 used to force opening a link in Emacs, so it may be good to only
13058 use a numeric or double prefix to guide the search function.
13060 In case this is needed, a function in this hook can also restore
13061 the window configuration before `org-open-at-point' was called using:
13063 (set-window-configuration org-window-config-before-follow-link)")
13065 (defun org-link-search (s &optional type avoid-pos)
13066 "Search for a link search option.
13067 If S is surrounded by forward slashes, it is interpreted as a
13068 regular expression. In org-mode files, this will create an `org-occur'
13069 sparse tree. In ordinary files, `occur' will be used to list matches.
13070 If the current buffer is in `dired-mode', grep will be used to search
13071 in all files. If AVOID-POS is given, ignore matches near that position."
13072 (let ((case-fold-search t)
13073 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
13074 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
13075 (append '(("") (" ") ("\t") ("\n"))
13076 org-emphasis-alist)
13077 "\\|") "\\)"))
13078 (pos (point))
13079 (pre "") (post "")
13080 words re0 re1 re2 re3 re4 re5 re2a reall)
13081 (cond
13082 ;; First check if there are any special
13083 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
13084 ;; Now try the builtin stuff
13085 ((save-excursion
13086 (goto-char (point-min))
13087 (and
13088 (re-search-forward
13089 (concat "<<" (regexp-quote s0) ">>") nil t)
13090 (setq pos (match-beginning 0))))
13091 ;; There is an exact target for this
13092 (goto-char pos))
13093 ((string-match "^/\\(.*\\)/$" s)
13094 ;; A regular expression
13095 (cond
13096 ((org-mode-p)
13097 (org-occur (match-string 1 s)))
13098 ;;((eq major-mode 'dired-mode)
13099 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
13100 (t (org-do-occur (match-string 1 s)))))
13102 ;; A normal search strings
13103 (when (equal (string-to-char s) ?*)
13104 ;; Anchor on headlines, post may include tags.
13105 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
13106 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
13107 s (substring s 1)))
13108 (remove-text-properties
13109 0 (length s)
13110 '(face nil mouse-face nil keymap nil fontified nil) s)
13111 ;; Make a series of regular expressions to find a match
13112 (setq words (org-split-string s "[ \n\r\t]+")
13113 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
13114 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
13115 "\\)" markers)
13116 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
13117 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
13118 re1 (concat pre re2 post)
13119 re3 (concat pre re4 post)
13120 re5 (concat pre ".*" re4)
13121 re2 (concat pre re2)
13122 re2a (concat pre re2a)
13123 re4 (concat pre re4)
13124 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
13125 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
13126 re5 "\\)"
13128 (cond
13129 ((eq type 'org-occur) (org-occur reall))
13130 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
13131 (t (goto-char (point-min))
13132 (if (or (org-search-not-self 1 re0 nil t)
13133 (org-search-not-self 1 re1 nil t)
13134 (org-search-not-self 1 re2 nil t)
13135 (org-search-not-self 1 re2a nil t)
13136 (org-search-not-self 1 re3 nil t)
13137 (org-search-not-self 1 re4 nil t)
13138 (org-search-not-self 1 re5 nil t)
13140 (goto-char (match-beginning 1))
13141 (goto-char pos)
13142 (error "No match")))))
13144 ;; Normal string-search
13145 (goto-char (point-min))
13146 (if (search-forward s nil t)
13147 (goto-char (match-beginning 0))
13148 (error "No match"))))
13149 (and (org-mode-p) (org-show-context 'link-search))))
13151 (defun org-search-not-self (group &rest args)
13152 "Execute `re-search-forward', but only accept matches that do not
13153 enclose the position of `org-open-link-marker'."
13154 (let ((m org-open-link-marker))
13155 (catch 'exit
13156 (while (apply 're-search-forward args)
13157 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
13158 (goto-char (match-end group))
13159 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
13160 (> (match-beginning 0) (marker-position m))
13161 (< (match-end 0) (marker-position m)))
13162 (save-match-data
13163 (or (not (org-in-regexp
13164 org-bracket-link-analytic-regexp 1))
13165 (not (match-end 4)) ; no description
13166 (and (<= (match-beginning 4) (point))
13167 (>= (match-end 4) (point))))))
13168 (throw 'exit (point))))))))
13170 (defun org-get-buffer-for-internal-link (buffer)
13171 "Return a buffer to be used for displaying the link target of internal links."
13172 (cond
13173 ((not org-display-internal-link-with-indirect-buffer)
13174 buffer)
13175 ((string-match "(Clone)$" (buffer-name buffer))
13176 (message "Buffer is already a clone, not making another one")
13177 ;; we also do not modify visibility in this case
13178 buffer)
13179 (t ; make a new indirect buffer for displaying the link
13180 (let* ((bn (buffer-name buffer))
13181 (ibn (concat bn "(Clone)"))
13182 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
13183 (with-current-buffer ib (org-overview))
13184 ib))))
13186 (defun org-do-occur (regexp &optional cleanup)
13187 "Call the Emacs command `occur'.
13188 If CLEANUP is non-nil, remove the printout of the regular expression
13189 in the *Occur* buffer. This is useful if the regex is long and not useful
13190 to read."
13191 (occur regexp)
13192 (when cleanup
13193 (let ((cwin (selected-window)) win beg end)
13194 (when (setq win (get-buffer-window "*Occur*"))
13195 (select-window win))
13196 (goto-char (point-min))
13197 (when (re-search-forward "match[a-z]+" nil t)
13198 (setq beg (match-end 0))
13199 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
13200 (setq end (1- (match-beginning 0)))))
13201 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
13202 (goto-char (point-min))
13203 (select-window cwin))))
13205 ;;; The mark ring for links jumps
13207 (defvar org-mark-ring nil
13208 "Mark ring for positions before jumps in Org-mode.")
13209 (defvar org-mark-ring-last-goto nil
13210 "Last position in the mark ring used to go back.")
13211 ;; Fill and close the ring
13212 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
13213 (loop for i from 1 to org-mark-ring-length do
13214 (push (make-marker) org-mark-ring))
13215 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
13216 org-mark-ring)
13218 (defun org-mark-ring-push (&optional pos buffer)
13219 "Put the current position or POS into the mark ring and rotate it."
13220 (interactive)
13221 (setq pos (or pos (point)))
13222 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
13223 (move-marker (car org-mark-ring)
13224 (or pos (point))
13225 (or buffer (current-buffer)))
13226 (message "%s"
13227 (substitute-command-keys
13228 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
13230 (defun org-mark-ring-goto (&optional n)
13231 "Jump to the previous position in the mark ring.
13232 With prefix arg N, jump back that many stored positions. When
13233 called several times in succession, walk through the entire ring.
13234 Org-mode commands jumping to a different position in the current file,
13235 or to another Org-mode file, automatically push the old position
13236 onto the ring."
13237 (interactive "p")
13238 (let (p m)
13239 (if (eq last-command this-command)
13240 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
13241 (setq p org-mark-ring))
13242 (setq org-mark-ring-last-goto p)
13243 (setq m (car p))
13244 (switch-to-buffer (marker-buffer m))
13245 (goto-char m)
13246 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
13248 (defun org-remove-angle-brackets (s)
13249 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
13250 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
13252 (defun org-add-angle-brackets (s)
13253 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
13254 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
13257 ;;; Following specific links
13259 (defun org-follow-timestamp-link ()
13260 (cond
13261 ((org-at-date-range-p t)
13262 (let ((org-agenda-start-on-weekday)
13263 (t1 (match-string 1))
13264 (t2 (match-string 2)))
13265 (setq t1 (time-to-days (org-time-string-to-time t1))
13266 t2 (time-to-days (org-time-string-to-time t2)))
13267 (org-agenda-list nil t1 (1+ (- t2 t1)))))
13268 ((org-at-timestamp-p t)
13269 (org-agenda-list nil (time-to-days (org-time-string-to-time
13270 (substring (match-string 1) 0 10)))
13272 (t (error "This should not happen"))))
13275 (defun org-follow-bbdb-link (name)
13276 "Follow a BBDB link to NAME."
13277 (require 'bbdb)
13278 (let ((inhibit-redisplay (not debug-on-error))
13279 (bbdb-electric-p nil))
13280 (catch 'exit
13281 ;; Exact match on name
13282 (bbdb-name (concat "\\`" name "\\'") nil)
13283 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13284 ;; Exact match on name
13285 (bbdb-company (concat "\\`" name "\\'") nil)
13286 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13287 ;; Partial match on name
13288 (bbdb-name name nil)
13289 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13290 ;; Partial match on company
13291 (bbdb-company name nil)
13292 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
13293 ;; General match including network address and notes
13294 (bbdb name nil)
13295 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
13296 (delete-window (get-buffer-window "*BBDB*"))
13297 (error "No matching BBDB record")))))
13299 (defun org-follow-info-link (name)
13300 "Follow an info file & node link to NAME."
13301 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
13302 (string-match "\\(.*\\)" name))
13303 (progn
13304 (require 'info)
13305 (if (match-string 2 name) ; If there isn't a node, choose "Top"
13306 (Info-find-node (match-string 1 name) (match-string 2 name))
13307 (Info-find-node (match-string 1 name) "Top")))
13308 (message "Could not open: %s" name)))
13310 (defun org-follow-gnus-link (&optional group article)
13311 "Follow a Gnus link to GROUP and ARTICLE."
13312 (require 'gnus)
13313 (funcall (cdr (assq 'gnus org-link-frame-setup)))
13314 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
13315 (cond ((and group article)
13316 (gnus-group-read-group 1 nil group)
13317 (gnus-summary-goto-article (string-to-number article) nil t))
13318 (group (gnus-group-jump-to-group group))))
13320 (defun org-follow-vm-link (&optional folder article readonly)
13321 "Follow a VM link to FOLDER and ARTICLE."
13322 (require 'vm)
13323 (setq article (org-add-angle-brackets article))
13324 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
13325 ;; ange-ftp or efs or tramp access
13326 (let ((user (or (match-string 1 folder) (user-login-name)))
13327 (host (match-string 2 folder))
13328 (file (match-string 3 folder)))
13329 (cond
13330 ((featurep 'tramp)
13331 ;; use tramp to access the file
13332 (if (featurep 'xemacs)
13333 (setq folder (format "[%s@%s]%s" user host file))
13334 (setq folder (format "/%s@%s:%s" user host file))))
13336 ;; use ange-ftp or efs
13337 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
13338 (setq folder (format "/%s@%s:%s" user host file))))))
13339 (when folder
13340 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
13341 (sit-for 0.1)
13342 (when article
13343 (vm-select-folder-buffer)
13344 (widen)
13345 (let ((case-fold-search t))
13346 (goto-char (point-min))
13347 (if (not (re-search-forward
13348 (concat "^" "message-id: *" (regexp-quote article))))
13349 (error "Could not find the specified message in this folder"))
13350 (vm-isearch-update)
13351 (vm-isearch-narrow)
13352 (vm-beginning-of-message)
13353 (vm-summarize)))))
13355 (defun org-follow-wl-link (folder article)
13356 "Follow a Wanderlust link to FOLDER and ARTICLE."
13357 (if (and (string= folder "%")
13358 article
13359 (string-match "^\\([^#]+\\)\\(#\\(.*\\)\\)?" article))
13360 ;; XXX: imap-uw supports folders starting with '#' such as "#mh/inbox".
13361 ;; Thus, we recompose folder and article ids.
13362 (setq folder (format "%s#%s" folder (match-string 1 article))
13363 article (match-string 3 article)))
13364 (if (not (elmo-folder-exists-p (wl-folder-get-elmo-folder folder)))
13365 (error "No such folder: %s" folder))
13366 (wl-summary-goto-folder-subr folder 'no-sync t nil t nil nil)
13367 (and article
13368 (wl-summary-jump-to-msg-by-message-id (org-add-angle-brackets article))
13369 (wl-summary-redisplay)))
13371 (defun org-follow-rmail-link (folder article)
13372 "Follow an RMAIL link to FOLDER and ARTICLE."
13373 (setq article (org-add-angle-brackets article))
13374 (let (message-number)
13375 (save-excursion
13376 (save-window-excursion
13377 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13378 (setq message-number
13379 (save-restriction
13380 (widen)
13381 (goto-char (point-max))
13382 (if (re-search-backward
13383 (concat "^Message-ID:\\s-+" (regexp-quote
13384 (or article "")))
13385 nil t)
13386 (rmail-what-message))))))
13387 (if message-number
13388 (progn
13389 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
13390 (rmail-show-message message-number)
13391 message-number)
13392 (error "Message not found"))))
13394 ;;; mh-e integration based on planner-mode
13395 (defun org-mhe-get-message-real-folder ()
13396 "Return the name of the current message real folder, so if you use
13397 sequences, it will now work."
13398 (save-excursion
13399 (let* ((folder
13400 (if (equal major-mode 'mh-folder-mode)
13401 mh-current-folder
13402 ;; Refer to the show buffer
13403 mh-show-folder-buffer))
13404 (end-index
13405 (if (boundp 'mh-index-folder)
13406 (min (length mh-index-folder) (length folder))))
13408 ;; a simple test on mh-index-data does not work, because
13409 ;; mh-index-data is always nil in a show buffer.
13410 (if (and (boundp 'mh-index-folder)
13411 (string= mh-index-folder (substring folder 0 end-index)))
13412 (if (equal major-mode 'mh-show-mode)
13413 (save-window-excursion
13414 (let (pop-up-frames)
13415 (when (buffer-live-p (get-buffer folder))
13416 (progn
13417 (pop-to-buffer folder)
13418 (org-mhe-get-message-folder-from-index)
13421 (org-mhe-get-message-folder-from-index)
13423 folder
13427 (defun org-mhe-get-message-folder-from-index ()
13428 "Returns the name of the message folder in a index folder buffer."
13429 (save-excursion
13430 (mh-index-previous-folder)
13431 (re-search-forward "^\\(+.*\\)$" nil t)
13432 (message "%s" (match-string 1))))
13434 (defun org-mhe-get-message-folder ()
13435 "Return the name of the current message folder. Be careful if you
13436 use sequences."
13437 (save-excursion
13438 (if (equal major-mode 'mh-folder-mode)
13439 mh-current-folder
13440 ;; Refer to the show buffer
13441 mh-show-folder-buffer)))
13443 (defun org-mhe-get-message-num ()
13444 "Return the number of the current message. Be careful if you
13445 use sequences."
13446 (save-excursion
13447 (if (equal major-mode 'mh-folder-mode)
13448 (mh-get-msg-num nil)
13449 ;; Refer to the show buffer
13450 (mh-show-buffer-message-number))))
13452 (defun org-mhe-get-header (header)
13453 "Return a header of the message in folder mode. This will create a
13454 show buffer for the corresponding message. If you have a more clever
13455 idea..."
13456 (let* ((folder (org-mhe-get-message-folder))
13457 (num (org-mhe-get-message-num))
13458 (buffer (get-buffer-create (concat "show-" folder)))
13459 (header-field))
13460 (with-current-buffer buffer
13461 (mh-display-msg num folder)
13462 (if (equal major-mode 'mh-folder-mode)
13463 (mh-header-display)
13464 (mh-show-header-display))
13465 (set-buffer buffer)
13466 (setq header-field (mh-get-header-field header))
13467 (if (equal major-mode 'mh-folder-mode)
13468 (mh-show)
13469 (mh-show-show))
13470 header-field)))
13472 (defun org-follow-mhe-link (folder article)
13473 "Follow an MHE link to FOLDER and ARTICLE.
13474 If ARTICLE is nil FOLDER is shown. If the configuration variable
13475 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
13476 ARTICLE is searched in all folders. Indexed searches (swish++,
13477 namazu, and others supported by MH-E) will always search in all
13478 folders."
13479 (require 'mh-e)
13480 (require 'mh-search)
13481 (require 'mh-utils)
13482 (mh-find-path)
13483 (if (not article)
13484 (mh-visit-folder (mh-normalize-folder-name folder))
13485 (setq article (org-add-angle-brackets article))
13486 (mh-search-choose)
13487 (if (equal mh-searcher 'pick)
13488 (progn
13489 (mh-search folder (list "--message-id" article))
13490 (when (and org-mhe-search-all-folders
13491 (not (org-mhe-get-message-real-folder)))
13492 (kill-this-buffer)
13493 (mh-search "+" (list "--message-id" article))))
13494 (mh-search "+" article))
13495 (if (org-mhe-get-message-real-folder)
13496 (mh-show-msg 1)
13497 (kill-this-buffer)
13498 (error "Message not found"))))
13500 ;;; BibTeX links
13502 ;; Use the custom search meachnism to construct and use search strings for
13503 ;; file links to BibTeX database entries.
13505 (defun org-create-file-search-in-bibtex ()
13506 "Create the search string and description for a BibTeX database entry."
13507 (when (eq major-mode 'bibtex-mode)
13508 ;; yes, we want to construct this search string.
13509 ;; Make a good description for this entry, using names, year and the title
13510 ;; Put it into the `description' variable which is dynamically scoped.
13511 (let ((bibtex-autokey-names 1)
13512 (bibtex-autokey-names-stretch 1)
13513 (bibtex-autokey-name-case-convert-function 'identity)
13514 (bibtex-autokey-name-separator " & ")
13515 (bibtex-autokey-additional-names " et al.")
13516 (bibtex-autokey-year-length 4)
13517 (bibtex-autokey-name-year-separator " ")
13518 (bibtex-autokey-titlewords 3)
13519 (bibtex-autokey-titleword-separator " ")
13520 (bibtex-autokey-titleword-case-convert-function 'identity)
13521 (bibtex-autokey-titleword-length 'infty)
13522 (bibtex-autokey-year-title-separator ": "))
13523 (setq description (bibtex-generate-autokey)))
13524 ;; Now parse the entry, get the key and return it.
13525 (save-excursion
13526 (bibtex-beginning-of-entry)
13527 (cdr (assoc "=key=" (bibtex-parse-entry))))))
13529 (defun org-execute-file-search-in-bibtex (s)
13530 "Find the link search string S as a key for a database entry."
13531 (when (eq major-mode 'bibtex-mode)
13532 ;; Yes, we want to do the search in this file.
13533 ;; We construct a regexp that searches for "@entrytype{" followed by the key
13534 (goto-char (point-min))
13535 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
13536 (regexp-quote s) "[ \t\n]*,") nil t)
13537 (goto-char (match-beginning 0)))
13538 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
13539 ;; Use double prefix to indicate that any web link should be browsed
13540 (let ((b (current-buffer)) (p (point)))
13541 ;; Restore the window configuration because we just use the web link
13542 (set-window-configuration org-window-config-before-follow-link)
13543 (save-excursion (set-buffer b) (goto-char p)
13544 (bibtex-url)))
13545 (recenter 0)) ; Move entry start to beginning of window
13546 ;; return t to indicate that the search is done.
13549 ;; Finally add the functions to the right hooks.
13550 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
13551 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
13553 ;; end of Bibtex link setup
13555 ;;; Following file links
13557 (defun org-open-file (path &optional in-emacs line search)
13558 "Open the file at PATH.
13559 First, this expands any special file name abbreviations. Then the
13560 configuration variable `org-file-apps' is checked if it contains an
13561 entry for this file type, and if yes, the corresponding command is launched.
13562 If no application is found, Emacs simply visits the file.
13563 With optional argument IN-EMACS, Emacs will visit the file.
13564 Optional LINE specifies a line to go to, optional SEARCH a string to
13565 search for. If LINE or SEARCH is given, the file will always be
13566 opened in Emacs.
13567 If the file does not exist, an error is thrown."
13568 (setq in-emacs (or in-emacs line search))
13569 (let* ((file (if (equal path "")
13570 buffer-file-name
13571 (substitute-in-file-name (expand-file-name path))))
13572 (apps (append org-file-apps (org-default-apps)))
13573 (remp (and (assq 'remote apps) (org-file-remote-p file)))
13574 (dirp (if remp nil (file-directory-p file)))
13575 (dfile (downcase file))
13576 (old-buffer (current-buffer))
13577 (old-pos (point))
13578 (old-mode major-mode)
13579 ext cmd)
13580 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
13581 (setq ext (match-string 1 dfile))
13582 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
13583 (setq ext (match-string 1 dfile))))
13584 (if in-emacs
13585 (setq cmd 'emacs)
13586 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
13587 (and dirp (cdr (assoc 'directory apps)))
13588 (cdr (assoc ext apps))
13589 (cdr (assoc t apps)))))
13590 (when (eq cmd 'mailcap)
13591 (require 'mailcap)
13592 (mailcap-parse-mailcaps)
13593 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
13594 (command (mailcap-mime-info mime-type)))
13595 (if (stringp command)
13596 (setq cmd command)
13597 (setq cmd 'emacs))))
13598 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
13599 (not (file-exists-p file))
13600 (not org-open-non-existing-files))
13601 (error "No such file: %s" file))
13602 (cond
13603 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
13604 ;; Remove quotes around the file name - we'll use shell-quote-argument.
13605 (while (string-match "['\"]%s['\"]" cmd)
13606 (setq cmd (replace-match "%s" t t cmd)))
13607 (while (string-match "%s" cmd)
13608 (setq cmd (replace-match
13609 (save-match-data (shell-quote-argument file))
13610 t t cmd)))
13611 (save-window-excursion
13612 (start-process-shell-command cmd nil cmd)))
13613 ((or (stringp cmd)
13614 (eq cmd 'emacs))
13615 (funcall (cdr (assq 'file org-link-frame-setup)) file)
13616 (widen)
13617 (if line (goto-line line)
13618 (if search (org-link-search search))))
13619 ((consp cmd)
13620 (eval cmd))
13621 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
13622 (and (org-mode-p) (eq old-mode 'org-mode)
13623 (or (not (equal old-buffer (current-buffer)))
13624 (not (equal old-pos (point))))
13625 (org-mark-ring-push old-pos old-buffer))))
13627 (defun org-default-apps ()
13628 "Return the default applications for this operating system."
13629 (cond
13630 ((eq system-type 'darwin)
13631 org-file-apps-defaults-macosx)
13632 ((eq system-type 'windows-nt)
13633 org-file-apps-defaults-windowsnt)
13634 (t org-file-apps-defaults-gnu)))
13636 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
13637 (defun org-file-remote-p (file)
13638 "Test whether FILE specifies a location on a remote system.
13639 Return non-nil if the location is indeed remote.
13641 For example, the filename \"/user@host:/foo\" specifies a location
13642 on the system \"/user@host:\"."
13643 (cond ((fboundp 'file-remote-p)
13644 (file-remote-p file))
13645 ((fboundp 'tramp-handle-file-remote-p)
13646 (tramp-handle-file-remote-p file))
13647 ((and (boundp 'ange-ftp-name-format)
13648 (string-match (car ange-ftp-name-format) file))
13650 (t nil)))
13653 ;;;; Hooks for remember.el, and refiling
13655 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
13656 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
13658 ;;;###autoload
13659 (defun org-remember-insinuate ()
13660 "Setup remember.el for use wiht Org-mode."
13661 (require 'remember)
13662 (setq remember-annotation-functions '(org-remember-annotation))
13663 (setq remember-handler-functions '(org-remember-handler))
13664 (add-hook 'remember-mode-hook 'org-remember-apply-template))
13666 ;;;###autoload
13667 (defun org-remember-annotation ()
13668 "Return a link to the current location as an annotation for remember.el.
13669 If you are using Org-mode files as target for data storage with
13670 remember.el, then the annotations should include a link compatible with the
13671 conventions in Org-mode. This function returns such a link."
13672 (org-store-link nil))
13674 (defconst org-remember-help
13675 "Select a destination location for the note.
13676 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
13677 RET on headline -> Store as sublevel entry to current headline
13678 RET at beg-of-buf -> Append to file as level 2 headline
13679 <left>/<right> -> before/after current headline, same headings level")
13681 (defvar org-remember-previous-location nil)
13682 (defvar org-force-remember-template-char) ;; dynamically scoped
13684 ;; Save the major mode of the buffer we called remember from
13685 (defvar org-select-template-temp-major-mode nil)
13687 ;; Temporary store the buffer where remember was called from
13688 (defvar org-select-template-original-buffer nil)
13690 (defun org-select-remember-template (&optional use-char)
13691 (when org-remember-templates
13692 (let* ((pre-selected-templates
13693 (mapcar
13694 (lambda (tpl)
13695 (let ((ctxt (nth 5 tpl))
13696 (mode org-select-template-temp-major-mode)
13697 (buf org-select-template-original-buffer))
13698 (if (or (and (functionp ctxt)
13699 (save-excursion
13700 (set-buffer buf)
13701 ;; Protect the user-defined function from error
13702 (condition-case nil (funcall ctxt) (error nil))))
13703 (and ctxt (listp ctxt)
13704 (delq nil (mapcar (lambda(x) (eq mode x)) ctxt))))
13705 tpl)))
13706 org-remember-templates))
13707 ;; If no template at this point, add the default templates:
13708 (pre-selected-templates1
13709 (if (not (delq nil pre-selected-templates))
13710 (mapcar (lambda(x) (if (not (nth 5 x)) x))
13711 org-remember-templates)
13712 pre-selected-templates))
13713 ;; Then unconditionnally add template for any contexts
13714 (pre-selected-templates2
13715 (append (mapcar (lambda(x) (if (eq (nth 5 x) t) x))
13716 org-remember-templates)
13717 (delq nil pre-selected-templates1)))
13718 (templates (mapcar (lambda (x)
13719 (if (stringp (car x))
13720 (append (list (nth 1 x) (car x)) (cddr x))
13721 (append (list (car x) "") (cdr x))))
13722 (delq nil pre-selected-templates2)))
13723 (char (or use-char
13724 (cond
13725 ((= (length templates) 1)
13726 (caar templates))
13727 ((and (boundp 'org-force-remember-template-char)
13728 org-force-remember-template-char)
13729 (if (stringp org-force-remember-template-char)
13730 (string-to-char org-force-remember-template-char)
13731 org-force-remember-template-char))
13733 (message "Select template: %s"
13734 (mapconcat
13735 (lambda (x)
13736 (cond
13737 ((not (string-match "\\S-" (nth 1 x)))
13738 (format "[%c]" (car x)))
13739 ((equal (downcase (car x))
13740 (downcase (aref (nth 1 x) 0)))
13741 (format "[%c]%s" (car x)
13742 (substring (nth 1 x) 1)))
13743 (t (format "[%c]%s" (car x) (nth 1 x)))))
13744 templates " "))
13745 (let ((inhibit-quit t) (char0 (read-char-exclusive)))
13746 (when (equal char0 ?\C-g)
13747 (jump-to-register remember-register)
13748 (kill-buffer remember-buffer))
13749 char0))))))
13750 (cddr (assoc char templates)))))
13752 (defvar x-last-selected-text)
13753 (defvar x-last-selected-text-primary)
13755 ;;;###autoload
13756 (defun org-remember-apply-template (&optional use-char skip-interactive)
13757 "Initialize *remember* buffer with template, invoke `org-mode'.
13758 This function should be placed into `remember-mode-hook' and in fact requires
13759 to be run from that hook to function properly."
13760 (if org-remember-templates
13761 (let* ((entry (org-select-remember-template use-char))
13762 (tpl (car entry))
13763 (plist-p (if org-store-link-plist t nil))
13764 (file (if (and (nth 1 entry) (stringp (nth 1 entry))
13765 (string-match "\\S-" (nth 1 entry)))
13766 (nth 1 entry)
13767 org-default-notes-file))
13768 (headline (nth 2 entry))
13769 (v-c (or (and (eq window-system 'x)
13770 (fboundp 'x-cut-buffer-or-selection-value)
13771 (x-cut-buffer-or-selection-value))
13772 (org-bound-and-true-p x-last-selected-text)
13773 (org-bound-and-true-p x-last-selected-text-primary)
13774 (and (> (length kill-ring) 0) (current-kill 0))))
13775 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
13776 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
13777 (v-u (concat "[" (substring v-t 1 -1) "]"))
13778 (v-U (concat "[" (substring v-T 1 -1) "]"))
13779 ;; `initial' and `annotation' are bound in `remember'
13780 (v-i (if (boundp 'initial) initial))
13781 (v-a (if (and (boundp 'annotation) annotation)
13782 (if (equal annotation "[[]]") "" annotation)
13783 ""))
13784 (v-A (if (and v-a
13785 (string-match "\\[\\(\\[.*?\\]\\)\\(\\[.*?\\]\\)?\\]" v-a))
13786 (replace-match "[\\1[%^{Link description}]]" nil nil v-a)
13787 v-a))
13788 (v-n user-full-name)
13789 (org-startup-folded nil)
13790 org-time-was-given org-end-time-was-given x
13791 prompt completions char time pos default histvar)
13792 (setq org-store-link-plist
13793 (append (list :annotation v-a :initial v-i)
13794 org-store-link-plist))
13795 (unless tpl (setq tpl "") (message "No template") (ding) (sit-for 1))
13796 (erase-buffer)
13797 (insert (substitute-command-keys
13798 (format
13799 "## Filing location: Select interactively, default, or last used:
13800 ## %s to select file and header location interactively.
13801 ## %s \"%s\" -> \"* %s\"
13802 ## C-u C-u C-c C-c \"%s\" -> \"* %s\"
13803 ## To switch templates, use `\\[org-remember]'. To abort use `C-c C-k'.\n\n"
13804 (if org-remember-store-without-prompt " C-u C-c C-c" " C-c C-c")
13805 (if org-remember-store-without-prompt " C-c C-c" " C-u C-c C-c")
13806 (abbreviate-file-name (or file org-default-notes-file))
13807 (or headline "")
13808 (or (car org-remember-previous-location) "???")
13809 (or (cdr org-remember-previous-location) "???"))))
13810 (insert tpl) (goto-char (point-min))
13811 ;; Simple %-escapes
13812 (while (re-search-forward "%\\([tTuUaiAc]\\)" nil t)
13813 (when (and initial (equal (match-string 0) "%i"))
13814 (save-match-data
13815 (let* ((lead (buffer-substring
13816 (point-at-bol) (match-beginning 0))))
13817 (setq v-i (mapconcat 'identity
13818 (org-split-string initial "\n")
13819 (concat "\n" lead))))))
13820 (replace-match
13821 (or (eval (intern (concat "v-" (match-string 1)))) "")
13822 t t))
13824 ;; %[] Insert contents of a file.
13825 (goto-char (point-min))
13826 (while (re-search-forward "%\\[\\(.+\\)\\]" nil t)
13827 (let ((start (match-beginning 0))
13828 (end (match-end 0))
13829 (filename (expand-file-name (match-string 1))))
13830 (goto-char start)
13831 (delete-region start end)
13832 (condition-case error
13833 (insert-file-contents filename)
13834 (error (insert (format "%%![Couldn't insert %s: %s]"
13835 filename error))))))
13836 ;; %() embedded elisp
13837 (goto-char (point-min))
13838 (while (re-search-forward "%\\((.+)\\)" nil t)
13839 (goto-char (match-beginning 0))
13840 (let ((template-start (point)))
13841 (forward-char 1)
13842 (let ((result
13843 (condition-case error
13844 (eval (read (current-buffer)))
13845 (error (format "%%![Error: %s]" error)))))
13846 (delete-region template-start (point))
13847 (insert result))))
13849 ;; From the property list
13850 (when plist-p
13851 (goto-char (point-min))
13852 (while (re-search-forward "%\\(:[-a-zA-Z]+\\)" nil t)
13853 (and (setq x (or (plist-get org-store-link-plist
13854 (intern (match-string 1))) ""))
13855 (replace-match x t t))))
13857 ;; Turn on org-mode in the remember buffer, set local variables
13858 (org-mode)
13859 (org-set-local 'org-finish-function 'org-remember-finalize)
13860 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
13861 (org-set-local 'org-default-notes-file file))
13862 (if (and headline (stringp headline) (string-match "\\S-" headline))
13863 (org-set-local 'org-remember-default-headline headline))
13864 ;; Interactive template entries
13865 (goto-char (point-min))
13866 (while (re-search-forward "%^\\({\\([^}]*\\)}\\)?\\([gGuUtT]\\)?" nil t)
13867 (setq char (if (match-end 3) (match-string 3))
13868 prompt (if (match-end 2) (match-string 2)))
13869 (goto-char (match-beginning 0))
13870 (replace-match "")
13871 (setq completions nil default nil)
13872 (when prompt
13873 (setq completions (org-split-string prompt "|")
13874 prompt (pop completions)
13875 default (car completions)
13876 histvar (intern (concat
13877 "org-remember-template-prompt-history::"
13878 (or prompt "")))
13879 completions (mapcar 'list completions)))
13880 (cond
13881 ((member char '("G" "g"))
13882 (let* ((org-last-tags-completion-table
13883 (org-global-tags-completion-table
13884 (if (equal char "G") (org-agenda-files) (and file (list file)))))
13885 (org-add-colon-after-tag-completion t)
13886 (ins (completing-read
13887 (if prompt (concat prompt ": ") "Tags: ")
13888 'org-tags-completion-function nil nil nil
13889 'org-tags-history)))
13890 (setq ins (mapconcat 'identity
13891 (org-split-string ins (org-re "[^[:alnum:]_@]+"))
13892 ":"))
13893 (when (string-match "\\S-" ins)
13894 (or (equal (char-before) ?:) (insert ":"))
13895 (insert ins)
13896 (or (equal (char-after) ?:) (insert ":")))))
13897 (char
13898 (setq org-time-was-given (equal (upcase char) char))
13899 (setq time (org-read-date (equal (upcase char) "U") t nil
13900 prompt))
13901 (org-insert-time-stamp time org-time-was-given
13902 (member char '("u" "U"))
13903 nil nil (list org-end-time-was-given)))
13905 (insert (org-completing-read
13906 (concat (if prompt prompt "Enter string")
13907 (if default (concat " [" default "]"))
13908 ": ")
13909 completions nil nil nil histvar default)))))
13910 (goto-char (point-min))
13911 (if (re-search-forward "%\\?" nil t)
13912 (replace-match "")
13913 (and (re-search-forward "^[^#\n]" nil t) (backward-char 1))))
13914 (org-mode)
13915 (org-set-local 'org-finish-function 'org-remember-finalize))
13916 (when (save-excursion
13917 (goto-char (point-min))
13918 (re-search-forward "%!" nil t))
13919 (replace-match "")
13920 (add-hook 'post-command-hook 'org-remember-finish-immediately 'append)))
13922 (defun org-remember-finish-immediately ()
13923 "File remember note immediately.
13924 This should be run in `post-command-hook' and will remove itself
13925 from that hook."
13926 (remove-hook 'post-command-hook 'org-remember-finish-immediately)
13927 (when org-finish-function
13928 (funcall org-finish-function)))
13930 (defvar org-clock-marker) ; Defined below
13931 (defun org-remember-finalize ()
13932 "Finalize the remember process."
13933 (unless (fboundp 'remember-finalize)
13934 (defalias 'remember-finalize 'remember-buffer))
13935 (when (and org-clock-marker
13936 (equal (marker-buffer org-clock-marker) (current-buffer)))
13937 ;; FIXME: test this, this is w/o notetaking!
13938 (let (org-log-note-clock-out) (org-clock-out)))
13939 (when buffer-file-name
13940 (save-buffer)
13941 (setq buffer-file-name nil))
13942 (remember-finalize))
13944 ;;;###autoload
13945 (defun org-remember (&optional goto org-force-remember-template-char)
13946 "Call `remember'. If this is already a remember buffer, re-apply template.
13947 If there is an active region, make sure remember uses it as initial content
13948 of the remember buffer.
13950 When called interactively with a `C-u' prefix argument GOTO, don't remember
13951 anything, just go to the file/headline where the selected template usually
13952 stores its notes. With a double prefix arg `C-u C-u', go to the last
13953 note stored by remember.
13955 Lisp programs can set ORG-FORCE-REMEMBER-TEMPLATE-CHAR to a character
13956 associated with a template in `org-remember-templates'."
13957 (interactive "P")
13958 (cond
13959 ((equal goto '(4)) (org-go-to-remember-target))
13960 ((equal goto '(16)) (org-remember-goto-last-stored))
13962 ;; set temporary variables that will be needed in
13963 ;; `org-select-remember-template'
13964 (setq org-select-template-temp-major-mode major-mode)
13965 (setq org-select-template-original-buffer (current-buffer))
13966 (if (memq org-finish-function '(remember-buffer remember-finalize))
13967 (progn
13968 (when (< (length org-remember-templates) 2)
13969 (error "No other template available"))
13970 (erase-buffer)
13971 (let ((annotation (plist-get org-store-link-plist :annotation))
13972 (initial (plist-get org-store-link-plist :initial)))
13973 (org-remember-apply-template))
13974 (message "Press C-c C-c to remember data"))
13975 (if (org-region-active-p)
13976 (remember (buffer-substring (point) (mark)))
13977 (call-interactively 'remember))))))
13979 (defun org-remember-goto-last-stored ()
13980 "Go to the location where the last remember note was stored."
13981 (interactive)
13982 (bookmark-jump "org-remember-last-stored")
13983 (message "This is the last note stored by remember"))
13985 (defun org-go-to-remember-target (&optional template-key)
13986 "Go to the target location of a remember template.
13987 The user is queried for the template."
13988 (interactive)
13989 (let* (org-select-template-temp-major-mode
13990 (entry (org-select-remember-template template-key))
13991 (file (nth 1 entry))
13992 (heading (nth 2 entry))
13993 visiting)
13994 (unless (and file (stringp file) (string-match "\\S-" file))
13995 (setq file org-default-notes-file))
13996 (unless (and heading (stringp heading) (string-match "\\S-" heading))
13997 (setq heading org-remember-default-headline))
13998 (setq visiting (org-find-base-buffer-visiting file))
13999 (if (not visiting) (find-file-noselect file))
14000 (switch-to-buffer (or visiting (get-file-buffer file)))
14001 (widen)
14002 (goto-char (point-min))
14003 (if (re-search-forward
14004 (concat "^\\*+[ \t]+" (regexp-quote heading)
14005 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14006 nil t)
14007 (goto-char (match-beginning 0))
14008 (error "Target headline not found: %s" heading))))
14010 (defvar org-note-abort nil) ; dynamically scoped
14012 ;;;###autoload
14013 (defun org-remember-handler ()
14014 "Store stuff from remember.el into an org file.
14015 First prompts for an org file. If the user just presses return, the value
14016 of `org-default-notes-file' is used.
14017 Then the command offers the headings tree of the selected file in order to
14018 file the text at a specific location.
14019 You can either immediately press RET to get the note appended to the
14020 file, or you can use vertical cursor motion and visibility cycling (TAB) to
14021 find a better place. Then press RET or <left> or <right> in insert the note.
14023 Key Cursor position Note gets inserted
14024 -----------------------------------------------------------------------------
14025 RET buffer-start as level 1 heading at end of file
14026 RET on headline as sublevel of the heading at cursor
14027 RET no heading at cursor position, level taken from context.
14028 Or use prefix arg to specify level manually.
14029 <left> on headline as same level, before current heading
14030 <right> on headline as same level, after current heading
14032 So the fastest way to store the note is to press RET RET to append it to
14033 the default file. This way your current train of thought is not
14034 interrupted, in accordance with the principles of remember.el.
14035 You can also get the fast execution without prompting by using
14036 C-u C-c C-c to exit the remember buffer. See also the variable
14037 `org-remember-store-without-prompt'.
14039 Before being stored away, the function ensures that the text has a
14040 headline, i.e. a first line that starts with a \"*\". If not, a headline
14041 is constructed from the current date and some additional data.
14043 If the variable `org-adapt-indentation' is non-nil, the entire text is
14044 also indented so that it starts in the same column as the headline
14045 \(i.e. after the stars).
14047 See also the variable `org-reverse-note-order'."
14048 (goto-char (point-min))
14049 (while (looking-at "^[ \t]*\n\\|^##.*\n")
14050 (replace-match ""))
14051 (goto-char (point-max))
14052 (beginning-of-line 1)
14053 (while (looking-at "[ \t]*$\\|##.*")
14054 (delete-region (1- (point)) (point-max))
14055 (beginning-of-line 1))
14056 (catch 'quit
14057 (if org-note-abort (throw 'quit nil))
14058 (let* ((txt (buffer-substring (point-min) (point-max)))
14059 (fastp (org-xor (equal current-prefix-arg '(4))
14060 org-remember-store-without-prompt))
14061 (file (cond
14062 (fastp org-default-notes-file)
14063 ((and (eq org-remember-interactive-interface 'refile)
14064 org-refile-targets)
14065 org-default-notes-file)
14066 ((not (and (equal current-prefix-arg '(16))
14067 org-remember-previous-location))
14068 (org-get-org-file))))
14069 (heading org-remember-default-headline)
14070 (visiting (and file (org-find-base-buffer-visiting file)))
14071 (org-startup-folded nil)
14072 (org-startup-align-all-tables nil)
14073 (org-goto-start-pos 1)
14074 spos exitcmd level indent reversed)
14075 (if (and (equal current-prefix-arg '(16)) org-remember-previous-location)
14076 (setq file (car org-remember-previous-location)
14077 heading (cdr org-remember-previous-location)
14078 fastp t))
14079 (setq current-prefix-arg nil)
14080 (if (string-match "[ \t\n]+\\'" txt)
14081 (setq txt (replace-match "" t t txt)))
14082 ;; Modify text so that it becomes a nice subtree which can be inserted
14083 ;; into an org tree.
14084 (let* ((lines (split-string txt "\n"))
14085 first)
14086 (setq first (car lines) lines (cdr lines))
14087 (if (string-match "^\\*+ " first)
14088 ;; Is already a headline
14089 (setq indent nil)
14090 ;; We need to add a headline: Use time and first buffer line
14091 (setq lines (cons first lines)
14092 first (concat "* " (current-time-string)
14093 " (" (remember-buffer-desc) ")")
14094 indent " "))
14095 (if (and org-adapt-indentation indent)
14096 (setq lines (mapcar
14097 (lambda (x)
14098 (if (string-match "\\S-" x)
14099 (concat indent x) x))
14100 lines)))
14101 (setq txt (concat first "\n"
14102 (mapconcat 'identity lines "\n"))))
14103 (if (string-match "\n[ \t]*\n[ \t\n]*\\'" txt)
14104 (setq txt (replace-match "\n\n" t t txt))
14105 (if (string-match "[ \t\n]*\\'" txt)
14106 (setq txt (replace-match "\n" t t txt))))
14107 ;; Put the modified text back into the remember buffer, for refile.
14108 (erase-buffer)
14109 (insert txt)
14110 (goto-char (point-min))
14111 (when (and (eq org-remember-interactive-interface 'refile)
14112 (not fastp))
14113 (org-refile nil (or visiting (find-file-noselect file)))
14114 (throw 'quit t))
14115 ;; Find the file
14116 (if (not visiting) (find-file-noselect file))
14117 (with-current-buffer (or visiting (get-file-buffer file))
14118 (unless (org-mode-p)
14119 (error "Target files for remember notes must be in Org-mode"))
14120 (save-excursion
14121 (save-restriction
14122 (widen)
14123 (and (goto-char (point-min))
14124 (not (re-search-forward "^\\* " nil t))
14125 (insert "\n* " (or heading "Notes") "\n"))
14126 (setq reversed (org-notes-order-reversed-p))
14128 ;; Find the default location
14129 (when (and heading (stringp heading) (string-match "\\S-" heading))
14130 (goto-char (point-min))
14131 (if (re-search-forward
14132 (concat "^\\*+[ \t]+" (regexp-quote heading)
14133 (org-re "\\([ \t]+:[[:alnum:]@_:]*\\)?[ \t]*$"))
14134 nil t)
14135 (setq org-goto-start-pos (match-beginning 0))
14136 (when fastp
14137 (goto-char (point-max))
14138 (unless (bolp) (newline))
14139 (insert "* " heading "\n")
14140 (setq org-goto-start-pos (point-at-bol 0)))))
14142 ;; Ask the User for a location, using the appropriate interface
14143 (cond
14144 (fastp (setq spos org-goto-start-pos
14145 exitcmd 'return))
14146 ((eq org-remember-interactive-interface 'outline)
14147 (setq spos (org-get-location (current-buffer)
14148 org-remember-help)
14149 exitcmd (cdr spos)
14150 spos (car spos)))
14151 ((eq org-remember-interactive-interface 'outline-path-completion)
14152 (let ((org-refile-targets '((nil . (:maxlevel . 10))))
14153 (org-refile-use-outline-path t))
14154 (setq spos (org-refile-get-location "Heading: ")
14155 exitcmd 'return
14156 spos (nth 3 spos))))
14157 (t (error "this should not hapen")))
14158 (if (not spos) (throw 'quit nil)) ; return nil to show we did
14159 ; not handle this note
14160 (goto-char spos)
14161 (cond ((org-on-heading-p t)
14162 (org-back-to-heading t)
14163 (setq level (funcall outline-level))
14164 (cond
14165 ((eq exitcmd 'return)
14166 ;; sublevel of current
14167 (setq org-remember-previous-location
14168 (cons (abbreviate-file-name file)
14169 (org-get-heading 'notags)))
14170 (if reversed
14171 (outline-next-heading)
14172 (org-end-of-subtree t)
14173 (if (not (bolp))
14174 (if (looking-at "[ \t]*\n")
14175 (beginning-of-line 2)
14176 (end-of-line 1)
14177 (insert "\n"))))
14178 (bookmark-set "org-remember-last-stored")
14179 (org-paste-subtree (org-get-valid-level level 1) txt))
14180 ((eq exitcmd 'left)
14181 ;; before current
14182 (bookmark-set "org-remember-last-stored")
14183 (org-paste-subtree level txt))
14184 ((eq exitcmd 'right)
14185 ;; after current
14186 (org-end-of-subtree t)
14187 (bookmark-set "org-remember-last-stored")
14188 (org-paste-subtree level txt))
14189 (t (error "This should not happen"))))
14191 ((and (bobp) (not reversed))
14192 ;; Put it at the end, one level below level 1
14193 (save-restriction
14194 (widen)
14195 (goto-char (point-max))
14196 (if (not (bolp)) (newline))
14197 (bookmark-set "org-remember-last-stored")
14198 (org-paste-subtree (org-get-valid-level 1 1) txt)))
14200 ((and (bobp) reversed)
14201 ;; Put it at the start, as level 1
14202 (save-restriction
14203 (widen)
14204 (goto-char (point-min))
14205 (re-search-forward "^\\*+ " nil t)
14206 (beginning-of-line 1)
14207 (bookmark-set "org-remember-last-stored")
14208 (org-paste-subtree 1 txt)))
14210 ;; Put it right there, with automatic level determined by
14211 ;; org-paste-subtree or from prefix arg
14212 (bookmark-set "org-remember-last-stored")
14213 (org-paste-subtree
14214 (if (numberp current-prefix-arg) current-prefix-arg)
14215 txt)))
14216 (when remember-save-after-remembering
14217 (save-buffer)
14218 (if (not visiting) (kill-buffer (current-buffer)))))))))
14220 t) ;; return t to indicate that we took care of this note.
14222 (defun org-get-org-file ()
14223 "Read a filename, with default directory `org-directory'."
14224 (let ((default (or org-default-notes-file remember-data-file)))
14225 (read-file-name (format "File name [%s]: " default)
14226 (file-name-as-directory org-directory)
14227 default)))
14229 (defun org-notes-order-reversed-p ()
14230 "Check if the current file should receive notes in reversed order."
14231 (cond
14232 ((not org-reverse-note-order) nil)
14233 ((eq t org-reverse-note-order) t)
14234 ((not (listp org-reverse-note-order)) nil)
14235 (t (catch 'exit
14236 (let ((all org-reverse-note-order)
14237 entry)
14238 (while (setq entry (pop all))
14239 (if (string-match (car entry) buffer-file-name)
14240 (throw 'exit (cdr entry))))
14241 nil)))))
14243 ;;; Refiling
14245 (defvar org-refile-target-table nil
14246 "The list of refile targets, created by `org-refile'.")
14248 (defvar org-agenda-new-buffers nil
14249 "Buffers created to visit agenda files.")
14251 (defun org-get-refile-targets (&optional default-buffer)
14252 "Produce a table with refile targets."
14253 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
14254 targets txt re files f desc descre)
14255 (with-current-buffer (or default-buffer (current-buffer))
14256 (while (setq entry (pop entries))
14257 (setq files (car entry) desc (cdr entry))
14258 (cond
14259 ((null files) (setq files (list (current-buffer))))
14260 ((eq files 'org-agenda-files)
14261 (setq files (org-agenda-files 'unrestricted)))
14262 ((and (symbolp files) (fboundp files))
14263 (setq files (funcall files)))
14264 ((and (symbolp files) (boundp files))
14265 (setq files (symbol-value files))))
14266 (if (stringp files) (setq files (list files)))
14267 (cond
14268 ((eq (car desc) :tag)
14269 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
14270 ((eq (car desc) :todo)
14271 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
14272 ((eq (car desc) :regexp)
14273 (setq descre (cdr desc)))
14274 ((eq (car desc) :level)
14275 (setq descre (concat "^\\*\\{" (number-to-string
14276 (if org-odd-levels-only
14277 (1- (* 2 (cdr desc)))
14278 (cdr desc)))
14279 "\\}[ \t]")))
14280 ((eq (car desc) :maxlevel)
14281 (setq descre (concat "^\\*\\{1," (number-to-string
14282 (if org-odd-levels-only
14283 (1- (* 2 (cdr desc)))
14284 (cdr desc)))
14285 "\\}[ \t]")))
14286 (t (error "Bad refiling target description %s" desc)))
14287 (while (setq f (pop files))
14288 (save-excursion
14289 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
14290 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
14291 (save-excursion
14292 (save-restriction
14293 (widen)
14294 (goto-char (point-min))
14295 (while (re-search-forward descre nil t)
14296 (goto-char (point-at-bol))
14297 (when (looking-at org-complex-heading-regexp)
14298 (setq txt (match-string 4)
14299 re (concat "^" (regexp-quote
14300 (buffer-substring (match-beginning 1)
14301 (match-end 4)))))
14302 (if (match-end 5) (setq re (concat re "[ \t]+"
14303 (regexp-quote
14304 (match-string 5)))))
14305 (setq re (concat re "[ \t]*$"))
14306 (when org-refile-use-outline-path
14307 (setq txt (mapconcat 'identity
14308 (append
14309 (if (eq org-refile-use-outline-path 'file)
14310 (list (file-name-nondirectory
14311 (buffer-file-name (buffer-base-buffer))))
14312 (if (eq org-refile-use-outline-path 'full-file-path)
14313 (list (buffer-file-name (buffer-base-buffer)))))
14314 (org-get-outline-path)
14315 (list txt))
14316 "/")))
14317 (push (list txt f re (point)) targets))
14318 (goto-char (point-at-eol))))))))
14319 (nreverse targets))))
14321 (defun org-get-outline-path ()
14322 "Return the outline path to the current entry, as a list."
14323 (let (rtn)
14324 (save-excursion
14325 (while (org-up-heading-safe)
14326 (when (looking-at org-complex-heading-regexp)
14327 (push (org-match-string-no-properties 4) rtn)))
14328 rtn)))
14330 (defvar org-refile-history nil
14331 "History for refiling operations.")
14333 (defun org-refile (&optional goto default-buffer)
14334 "Move the entry at point to another heading.
14335 The list of target headings is compiled using the information in
14336 `org-refile-targets', which see. This list is created upon first use, and
14337 you can update it by calling this command with a double prefix (`C-u C-u').
14338 FIXME: Can we find a better way of updating?
14340 At the target location, the entry is filed as a subitem of the target heading.
14341 Depending on `org-reverse-note-order', the new subitem will either be the
14342 first of the last subitem.
14344 With prefix arg GOTO, the command will only visit the target location,
14345 not actually move anything.
14346 With a double prefix `C-c C-c', go to the location where the last refiling
14347 operation has put the subtree.
14349 With a double prefix argument, the command can be used to jump to any
14350 heading in the current buffer."
14351 (interactive "P")
14352 (let* ((cbuf (current-buffer))
14353 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14354 pos it nbuf file re level reversed)
14355 (if (equal goto '(16))
14356 (org-refile-goto-last-stored)
14357 (when (setq it (org-refile-get-location
14358 (if goto "Goto: " "Refile to: ") default-buffer))
14359 (setq file (nth 1 it)
14360 re (nth 2 it)
14361 pos (nth 3 it))
14362 (setq nbuf (or (find-buffer-visiting file)
14363 (find-file-noselect file)))
14364 (if goto
14365 (progn
14366 (switch-to-buffer nbuf)
14367 (goto-char pos)
14368 (org-show-context 'org-goto))
14369 (org-copy-special)
14370 (save-excursion
14371 (set-buffer (setq nbuf (or (find-buffer-visiting file)
14372 (find-file-noselect file))))
14373 (setq reversed (org-notes-order-reversed-p))
14374 (save-excursion
14375 (save-restriction
14376 (widen)
14377 (goto-char pos)
14378 (looking-at outline-regexp)
14379 (setq level (org-get-valid-level (funcall outline-level) 1))
14380 (goto-char
14381 (if reversed
14382 (outline-next-heading)
14383 (or (save-excursion (outline-get-next-sibling))
14384 (org-end-of-subtree t t)
14385 (point-max))))
14386 (bookmark-set "org-refile-last-stored")
14387 (org-paste-subtree level))))
14388 (org-cut-special)
14389 (message "Entry refiled to \"%s\"" (car it)))))))
14391 (defun org-refile-goto-last-stored ()
14392 "Go to the location where the last refile was stored."
14393 (interactive)
14394 (bookmark-jump "org-refile-last-stored")
14395 (message "This is the location of the last refile"))
14397 (defun org-refile-get-location (&optional prompt default-buffer)
14398 "Prompt the user for a refile location, using PROMPT."
14399 (let ((org-refile-targets org-refile-targets)
14400 (org-refile-use-outline-path org-refile-use-outline-path))
14401 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
14402 (unless org-refile-target-table
14403 (error "No refile targets"))
14404 (let* ((cbuf (current-buffer))
14405 (filename (buffer-file-name (buffer-base-buffer cbuf)))
14406 (fname (and filename (file-truename filename)))
14407 (tbl (mapcar
14408 (lambda (x)
14409 (if (not (equal fname (file-truename (nth 1 x))))
14410 (cons (concat (car x) " (" (file-name-nondirectory
14411 (nth 1 x)) ")")
14412 (cdr x))
14414 org-refile-target-table))
14415 (completion-ignore-case t))
14416 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
14417 tbl)))
14419 ;;;; Dynamic blocks
14421 (defun org-find-dblock (name)
14422 "Find the first dynamic block with name NAME in the buffer.
14423 If not found, stay at current position and return nil."
14424 (let (pos)
14425 (save-excursion
14426 (goto-char (point-min))
14427 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
14428 nil t)
14429 (match-beginning 0))))
14430 (if pos (goto-char pos))
14431 pos))
14433 (defconst org-dblock-start-re
14434 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
14435 "Matches the startline of a dynamic block, with parameters.")
14437 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
14438 "Matches the end of a dyhamic block.")
14440 (defun org-create-dblock (plist)
14441 "Create a dynamic block section, with parameters taken from PLIST.
14442 PLIST must containe a :name entry which is used as name of the block."
14443 (unless (bolp) (newline))
14444 (let ((name (plist-get plist :name)))
14445 (insert "#+BEGIN: " name)
14446 (while plist
14447 (if (eq (car plist) :name)
14448 (setq plist (cddr plist))
14449 (insert " " (prin1-to-string (pop plist)))))
14450 (insert "\n\n#+END:\n")
14451 (beginning-of-line -2)))
14453 (defun org-prepare-dblock ()
14454 "Prepare dynamic block for refresh.
14455 This empties the block, puts the cursor at the insert position and returns
14456 the property list including an extra property :name with the block name."
14457 (unless (looking-at org-dblock-start-re)
14458 (error "Not at a dynamic block"))
14459 (let* ((begdel (1+ (match-end 0)))
14460 (name (org-no-properties (match-string 1)))
14461 (params (append (list :name name)
14462 (read (concat "(" (match-string 3) ")")))))
14463 (unless (re-search-forward org-dblock-end-re nil t)
14464 (error "Dynamic block not terminated"))
14465 (delete-region begdel (match-beginning 0))
14466 (goto-char begdel)
14467 (open-line 1)
14468 params))
14470 (defun org-map-dblocks (&optional command)
14471 "Apply COMMAND to all dynamic blocks in the current buffer.
14472 If COMMAND is not given, use `org-update-dblock'."
14473 (let ((cmd (or command 'org-update-dblock))
14474 pos)
14475 (save-excursion
14476 (goto-char (point-min))
14477 (while (re-search-forward org-dblock-start-re nil t)
14478 (goto-char (setq pos (match-beginning 0)))
14479 (condition-case nil
14480 (funcall cmd)
14481 (error (message "Error during update of dynamic block")))
14482 (goto-char pos)
14483 (unless (re-search-forward org-dblock-end-re nil t)
14484 (error "Dynamic block not terminated"))))))
14486 (defun org-dblock-update (&optional arg)
14487 "User command for updating dynamic blocks.
14488 Update the dynamic block at point. With prefix ARG, update all dynamic
14489 blocks in the buffer."
14490 (interactive "P")
14491 (if arg
14492 (org-update-all-dblocks)
14493 (or (looking-at org-dblock-start-re)
14494 (org-beginning-of-dblock))
14495 (org-update-dblock)))
14497 (defun org-update-dblock ()
14498 "Update the dynamic block at point
14499 This means to empty the block, parse for parameters and then call
14500 the correct writing function."
14501 (save-window-excursion
14502 (let* ((pos (point))
14503 (line (org-current-line))
14504 (params (org-prepare-dblock))
14505 (name (plist-get params :name))
14506 (cmd (intern (concat "org-dblock-write:" name))))
14507 (message "Updating dynamic block `%s' at line %d..." name line)
14508 (funcall cmd params)
14509 (message "Updating dynamic block `%s' at line %d...done" name line)
14510 (goto-char pos))))
14512 (defun org-beginning-of-dblock ()
14513 "Find the beginning of the dynamic block at point.
14514 Error if there is no scuh block at point."
14515 (let ((pos (point))
14516 beg)
14517 (end-of-line 1)
14518 (if (and (re-search-backward org-dblock-start-re nil t)
14519 (setq beg (match-beginning 0))
14520 (re-search-forward org-dblock-end-re nil t)
14521 (> (match-end 0) pos))
14522 (goto-char beg)
14523 (goto-char pos)
14524 (error "Not in a dynamic block"))))
14526 (defun org-update-all-dblocks ()
14527 "Update all dynamic blocks in the buffer.
14528 This function can be used in a hook."
14529 (when (org-mode-p)
14530 (org-map-dblocks 'org-update-dblock)))
14533 ;;;; Completion
14535 (defconst org-additional-option-like-keywords
14536 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
14537 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "DATE:" "TBLFM"
14538 "BEGIN_EXAMPLE" "END_EXAMPLE"))
14540 (defun org-complete (&optional arg)
14541 "Perform completion on word at point.
14542 At the beginning of a headline, this completes TODO keywords as given in
14543 `org-todo-keywords'.
14544 If the current word is preceded by a backslash, completes the TeX symbols
14545 that are supported for HTML support.
14546 If the current word is preceded by \"#+\", completes special words for
14547 setting file options.
14548 In the line after \"#+STARTUP:, complete valid keywords.\"
14549 At all other locations, this simply calls the value of
14550 `org-completion-fallback-command'."
14551 (interactive "P")
14552 (org-without-partial-completion
14553 (catch 'exit
14554 (let* ((end (point))
14555 (beg1 (save-excursion
14556 (skip-chars-backward (org-re "[:alnum:]_@"))
14557 (point)))
14558 (beg (save-excursion
14559 (skip-chars-backward "a-zA-Z0-9_:$")
14560 (point)))
14561 (confirm (lambda (x) (stringp (car x))))
14562 (searchhead (equal (char-before beg) ?*))
14563 (tag (and (equal (char-before beg1) ?:)
14564 (equal (char-after (point-at-bol)) ?*)))
14565 (prop (and (equal (char-before beg1) ?:)
14566 (not (equal (char-after (point-at-bol)) ?*))))
14567 (texp (equal (char-before beg) ?\\))
14568 (link (equal (char-before beg) ?\[))
14569 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
14570 beg)
14571 "#+"))
14572 (startup (string-match "^#\\+STARTUP:.*"
14573 (buffer-substring (point-at-bol) (point))))
14574 (completion-ignore-case opt)
14575 (type nil)
14576 (tbl nil)
14577 (table (cond
14578 (opt
14579 (setq type :opt)
14580 (append
14581 (mapcar
14582 (lambda (x)
14583 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
14584 (cons (match-string 2 x) (match-string 1 x)))
14585 (org-split-string (org-get-current-options) "\n"))
14586 (mapcar 'list org-additional-option-like-keywords)))
14587 (startup
14588 (setq type :startup)
14589 org-startup-options)
14590 (link (append org-link-abbrev-alist-local
14591 org-link-abbrev-alist))
14592 (texp
14593 (setq type :tex)
14594 org-html-entities)
14595 ((string-match "\\`\\*+[ \t]+\\'"
14596 (buffer-substring (point-at-bol) beg))
14597 (setq type :todo)
14598 (mapcar 'list org-todo-keywords-1))
14599 (searchhead
14600 (setq type :searchhead)
14601 (save-excursion
14602 (goto-char (point-min))
14603 (while (re-search-forward org-todo-line-regexp nil t)
14604 (push (list
14605 (org-make-org-heading-search-string
14606 (match-string 3) t))
14607 tbl)))
14608 tbl)
14609 (tag (setq type :tag beg beg1)
14610 (or org-tag-alist (org-get-buffer-tags)))
14611 (prop (setq type :prop beg beg1)
14612 (mapcar 'list (org-buffer-property-keys nil t t)))
14613 (t (progn
14614 (call-interactively org-completion-fallback-command)
14615 (throw 'exit nil)))))
14616 (pattern (buffer-substring-no-properties beg end))
14617 (completion (try-completion pattern table confirm)))
14618 (cond ((eq completion t)
14619 (if (not (assoc (upcase pattern) table))
14620 (message "Already complete")
14621 (if (equal type :opt)
14622 (insert (substring (cdr (assoc (upcase pattern) table))
14623 (length pattern)))
14624 (if (memq type '(:tag :prop)) (insert ":")))))
14625 ((null completion)
14626 (message "Can't find completion for \"%s\"" pattern)
14627 (ding))
14628 ((not (string= pattern completion))
14629 (delete-region beg end)
14630 (if (string-match " +$" completion)
14631 (setq completion (replace-match "" t t completion)))
14632 (insert completion)
14633 (if (get-buffer-window "*Completions*")
14634 (delete-window (get-buffer-window "*Completions*")))
14635 (if (assoc completion table)
14636 (if (eq type :todo) (insert " ")
14637 (if (memq type '(:tag :prop)) (insert ":"))))
14638 (if (and (equal type :opt) (assoc completion table))
14639 (message "%s" (substitute-command-keys
14640 "Press \\[org-complete] again to insert example settings"))))
14642 (message "Making completion list...")
14643 (let ((list (sort (all-completions pattern table confirm)
14644 'string<)))
14645 (with-output-to-temp-buffer "*Completions*"
14646 (condition-case nil
14647 ;; Protection needed for XEmacs and emacs 21
14648 (display-completion-list list pattern)
14649 (error (display-completion-list list)))))
14650 (message "Making completion list...%s" "done")))))))
14652 ;;;; TODO, DEADLINE, Comments
14654 (defun org-toggle-comment ()
14655 "Change the COMMENT state of an entry."
14656 (interactive)
14657 (save-excursion
14658 (org-back-to-heading)
14659 (let (case-fold-search)
14660 (if (looking-at (concat outline-regexp
14661 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
14662 (replace-match "" t t nil 1)
14663 (if (looking-at outline-regexp)
14664 (progn
14665 (goto-char (match-end 0))
14666 (insert org-comment-string " ")))))))
14668 (defvar org-last-todo-state-is-todo nil
14669 "This is non-nil when the last TODO state change led to a TODO state.
14670 If the last change removed the TODO tag or switched to DONE, then
14671 this is nil.")
14673 (defvar org-setting-tags nil) ; dynamically skiped
14675 ;; FIXME: better place
14676 (defun org-property-or-variable-value (var &optional inherit)
14677 "Check if there is a property fixing the value of VAR.
14678 If yes, return this value. If not, return the current value of the variable."
14679 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
14680 (if (and prop (stringp prop) (string-match "\\S-" prop))
14681 (read prop)
14682 (symbol-value var))))
14684 (defun org-parse-local-options (string var)
14685 "Parse STRING for startup setting relevant for variable VAR."
14686 (let ((rtn (symbol-value var))
14687 e opts)
14688 (save-match-data
14689 (if (or (not string) (not (string-match "\\S-" string)))
14691 (setq opts (delq nil (mapcar (lambda (x)
14692 (setq e (assoc x org-startup-options))
14693 (if (eq (nth 1 e) var) e nil))
14694 (org-split-string string "[ \t]+"))))
14695 (if (not opts)
14697 (setq rtn nil)
14698 (while (setq e (pop opts))
14699 (if (not (nth 3 e))
14700 (setq rtn (nth 2 e))
14701 (if (not (listp rtn)) (setq rtn nil))
14702 (push (nth 2 e) rtn)))
14703 rtn)))))
14705 (defvar org-blocker-hook nil
14706 "Hook for functions that are allowed to block a state change.
14708 Each function gets as its single argument a property list, see
14709 `org-trigger-hook' for more information about this list.
14711 If any of the functions in this hook returns nil, the state change
14712 is blocked.")
14714 (defvar org-trigger-hook nil
14715 "Hook for functions that are triggered by a state change.
14717 Each function gets as its single argument a property list with at least
14718 the following elements:
14720 (:type type-of-change :position pos-at-entry-start
14721 :from old-state :to new-state)
14723 Depending on the type, more properties may be present.
14725 This mechanism is currently implemented for:
14727 TODO state changes
14728 ------------------
14729 :type todo-state-change
14730 :from previous state (keyword as a string), or nil
14731 :to new state (keyword as a string), or nil")
14734 (defun org-todo (&optional arg)
14735 "Change the TODO state of an item.
14736 The state of an item is given by a keyword at the start of the heading,
14737 like
14738 *** TODO Write paper
14739 *** DONE Call mom
14741 The different keywords are specified in the variable `org-todo-keywords'.
14742 By default the available states are \"TODO\" and \"DONE\".
14743 So for this example: when the item starts with TODO, it is changed to DONE.
14744 When it starts with DONE, the DONE is removed. And when neither TODO nor
14745 DONE are present, add TODO at the beginning of the heading.
14747 With C-u prefix arg, use completion to determine the new state.
14748 With numeric prefix arg, switch to that state.
14750 For calling through lisp, arg is also interpreted in the following way:
14751 'none -> empty state
14752 \"\"(empty string) -> switch to empty state
14753 'done -> switch to DONE
14754 'nextset -> switch to the next set of keywords
14755 'previousset -> switch to the previous set of keywords
14756 \"WAITING\" -> switch to the specified keyword, but only if it
14757 really is a member of `org-todo-keywords'."
14758 (interactive "P")
14759 (save-excursion
14760 (catch 'exit
14761 (org-back-to-heading)
14762 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
14763 (or (looking-at (concat " +" org-todo-regexp " *"))
14764 (looking-at " *"))
14765 (let* ((match-data (match-data))
14766 (startpos (point-at-bol))
14767 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
14768 (org-log-done org-log-done)
14769 (org-log-repeat org-log-repeat)
14770 (org-todo-log-states org-todo-log-states)
14771 (this (match-string 1))
14772 (hl-pos (match-beginning 0))
14773 (head (org-get-todo-sequence-head this))
14774 (ass (assoc head org-todo-kwd-alist))
14775 (interpret (nth 1 ass))
14776 (done-word (nth 3 ass))
14777 (final-done-word (nth 4 ass))
14778 (last-state (or this ""))
14779 (completion-ignore-case t)
14780 (member (member this org-todo-keywords-1))
14781 (tail (cdr member))
14782 (state (cond
14783 ((and org-todo-key-trigger
14784 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
14785 (and (not arg) org-use-fast-todo-selection
14786 (not (eq org-use-fast-todo-selection 'prefix)))))
14787 ;; Use fast selection
14788 (org-fast-todo-selection))
14789 ((and (equal arg '(4))
14790 (or (not org-use-fast-todo-selection)
14791 (not org-todo-key-trigger)))
14792 ;; Read a state with completion
14793 (completing-read "State: " (mapcar (lambda(x) (list x))
14794 org-todo-keywords-1)
14795 nil t))
14796 ((eq arg 'right)
14797 (if this
14798 (if tail (car tail) nil)
14799 (car org-todo-keywords-1)))
14800 ((eq arg 'left)
14801 (if (equal member org-todo-keywords-1)
14803 (if this
14804 (nth (- (length org-todo-keywords-1) (length tail) 2)
14805 org-todo-keywords-1)
14806 (org-last org-todo-keywords-1))))
14807 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
14808 (setq arg nil))) ; hack to fall back to cycling
14809 (arg
14810 ;; user or caller requests a specific state
14811 (cond
14812 ((equal arg "") nil)
14813 ((eq arg 'none) nil)
14814 ((eq arg 'done) (or done-word (car org-done-keywords)))
14815 ((eq arg 'nextset)
14816 (or (car (cdr (member head org-todo-heads)))
14817 (car org-todo-heads)))
14818 ((eq arg 'previousset)
14819 (let ((org-todo-heads (reverse org-todo-heads)))
14820 (or (car (cdr (member head org-todo-heads)))
14821 (car org-todo-heads))))
14822 ((car (member arg org-todo-keywords-1)))
14823 ((nth (1- (prefix-numeric-value arg))
14824 org-todo-keywords-1))))
14825 ((null member) (or head (car org-todo-keywords-1)))
14826 ((equal this final-done-word) nil) ;; -> make empty
14827 ((null tail) nil) ;; -> first entry
14828 ((eq interpret 'sequence)
14829 (car tail))
14830 ((memq interpret '(type priority))
14831 (if (eq this-command last-command)
14832 (car tail)
14833 (if (> (length tail) 0)
14834 (or done-word (car org-done-keywords))
14835 nil)))
14836 (t nil)))
14837 (next (if state (concat " " state " ") " "))
14838 (change-plist (list :type 'todo-state-change :from this :to state
14839 :position startpos))
14840 dolog now-done-p)
14841 (when org-blocker-hook
14842 (unless (save-excursion
14843 (save-match-data
14844 (run-hook-with-args-until-failure
14845 'org-blocker-hook change-plist)))
14846 (if (interactive-p)
14847 (error "TODO state change from %s to %s blocked" this state)
14848 ;; fail silently
14849 (message "TODO state change from %s to %s blocked" this state)
14850 (throw 'exit nil))))
14851 (store-match-data match-data)
14852 (replace-match next t t)
14853 (unless (pos-visible-in-window-p hl-pos)
14854 (message "TODO state changed to %s" (org-trim next)))
14855 (unless head
14856 (setq head (org-get-todo-sequence-head state)
14857 ass (assoc head org-todo-kwd-alist)
14858 interpret (nth 1 ass)
14859 done-word (nth 3 ass)
14860 final-done-word (nth 4 ass)))
14861 (when (memq arg '(nextset previousset))
14862 (message "Keyword-Set %d/%d: %s"
14863 (- (length org-todo-sets) -1
14864 (length (memq (assoc state org-todo-sets) org-todo-sets)))
14865 (length org-todo-sets)
14866 (mapconcat 'identity (assoc state org-todo-sets) " ")))
14867 (setq org-last-todo-state-is-todo
14868 (not (member state org-done-keywords)))
14869 (setq now-done-p (and (member state org-done-keywords)
14870 (not (member this org-done-keywords))))
14871 (and logging (org-local-logging logging))
14872 (when (and (or org-todo-log-states org-log-done)
14873 (not (memq arg '(nextset previousset))))
14874 ;; we need to look at recording a time and note
14875 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
14876 (nth 2 (assoc this org-todo-log-states))))
14877 (when (and state
14878 (member state org-not-done-keywords)
14879 (not (member this org-not-done-keywords)))
14880 ;; This is now a todo state and was not one before
14881 ;; If there was a CLOSED time stamp, get rid of it.
14882 (org-add-planning-info nil nil 'closed))
14883 (when (and now-done-p org-log-done)
14884 ;; It is now done, and it was not done before
14885 (org-add-planning-info 'closed (org-current-time))
14886 (if (and (not dolog) (eq 'note org-log-done))
14887 (org-add-log-maybe 'done state 'findpos 'note)))
14888 (when (and state dolog)
14889 ;; This is a non-nil state, and we need to log it
14890 (org-add-log-maybe 'state state 'findpos dolog)))
14891 ;; Fixup tag positioning
14892 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
14893 (run-hooks 'org-after-todo-state-change-hook)
14894 (if (and arg (not (member state org-done-keywords)))
14895 (setq head (org-get-todo-sequence-head state)))
14896 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
14897 ;; Do we need to trigger a repeat?
14898 (when now-done-p (org-auto-repeat-maybe state))
14899 ;; Fixup cursor location if close to the keyword
14900 (if (and (outline-on-heading-p)
14901 (not (bolp))
14902 (save-excursion (beginning-of-line 1)
14903 (looking-at org-todo-line-regexp))
14904 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
14905 (progn
14906 (goto-char (or (match-end 2) (match-end 1)))
14907 (just-one-space)))
14908 (when org-trigger-hook
14909 (save-excursion
14910 (run-hook-with-args 'org-trigger-hook change-plist)))))))
14912 (defun org-local-logging (value)
14913 "Get logging settings from a property VALUE."
14914 (let* (words w a)
14915 ;; directly set the variables, they are already local.
14916 (setq org-log-done nil
14917 org-log-repeat nil
14918 org-todo-log-states nil)
14919 (setq words (org-split-string value))
14920 (while (setq w (pop words))
14921 (cond
14922 ((setq a (assoc w org-startup-options))
14923 (and (member (nth 1 a) '(org-log-done org-log-repeat))
14924 (set (nth 1 a) (nth 2 a))))
14925 ((setq a (org-extract-log-state-settings w))
14926 (and (member (car a) org-todo-keywords-1)
14927 (push a org-todo-log-states)))))))
14929 (defun org-get-todo-sequence-head (kwd)
14930 "Return the head of the TODO sequence to which KWD belongs.
14931 If KWD is not set, check if there is a text property remembering the
14932 right sequence."
14933 (let (p)
14934 (cond
14935 ((not kwd)
14936 (or (get-text-property (point-at-bol) 'org-todo-head)
14937 (progn
14938 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
14939 nil (point-at-eol)))
14940 (get-text-property p 'org-todo-head))))
14941 ((not (member kwd org-todo-keywords-1))
14942 (car org-todo-keywords-1))
14943 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
14945 (defun org-fast-todo-selection ()
14946 "Fast TODO keyword selection with single keys.
14947 Returns the new TODO keyword, or nil if no state change should occur."
14948 (let* ((fulltable org-todo-key-alist)
14949 (done-keywords org-done-keywords) ;; needed for the faces.
14950 (maxlen (apply 'max (mapcar
14951 (lambda (x)
14952 (if (stringp (car x)) (string-width (car x)) 0))
14953 fulltable)))
14954 (expert nil)
14955 (fwidth (+ maxlen 3 1 3))
14956 (ncol (/ (- (window-width) 4) fwidth))
14957 tg cnt e c tbl
14958 groups ingroup)
14959 (save-window-excursion
14960 (if expert
14961 (set-buffer (get-buffer-create " *Org todo*"))
14962 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
14963 (erase-buffer)
14964 (org-set-local 'org-done-keywords done-keywords)
14965 (setq tbl fulltable cnt 0)
14966 (while (setq e (pop tbl))
14967 (cond
14968 ((equal e '(:startgroup))
14969 (push '() groups) (setq ingroup t)
14970 (when (not (= cnt 0))
14971 (setq cnt 0)
14972 (insert "\n"))
14973 (insert "{ "))
14974 ((equal e '(:endgroup))
14975 (setq ingroup nil cnt 0)
14976 (insert "}\n"))
14978 (setq tg (car e) c (cdr e))
14979 (if ingroup (push tg (car groups)))
14980 (setq tg (org-add-props tg nil 'face
14981 (org-get-todo-face tg)))
14982 (if (and (= cnt 0) (not ingroup)) (insert " "))
14983 (insert "[" c "] " tg (make-string
14984 (- fwidth 4 (length tg)) ?\ ))
14985 (when (= (setq cnt (1+ cnt)) ncol)
14986 (insert "\n")
14987 (if ingroup (insert " "))
14988 (setq cnt 0)))))
14989 (insert "\n")
14990 (goto-char (point-min))
14991 (if (and (not expert) (fboundp 'fit-window-to-buffer))
14992 (fit-window-to-buffer))
14993 (message "[a-z..]:Set [SPC]:clear")
14994 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
14995 (cond
14996 ((or (= c ?\C-g)
14997 (and (= c ?q) (not (rassoc c fulltable))))
14998 (setq quit-flag t))
14999 ((= c ?\ ) nil)
15000 ((setq e (rassoc c fulltable) tg (car e))
15002 (t (setq quit-flag t))))))
15004 (defun org-get-repeat ()
15005 "Check if tere is a deadline/schedule with repeater in this entry."
15006 (save-match-data
15007 (save-excursion
15008 (org-back-to-heading t)
15009 (if (re-search-forward
15010 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
15011 (match-string 1)))))
15013 (defvar org-last-changed-timestamp)
15014 (defvar org-log-post-message)
15015 (defvar org-log-note-purpose)
15016 (defun org-auto-repeat-maybe (done-word)
15017 "Check if the current headline contains a repeated deadline/schedule.
15018 If yes, set TODO state back to what it was and change the base date
15019 of repeating deadline/scheduled time stamps to new date.
15020 This function is run automatically after each state change to a DONE state."
15021 ;; last-state is dynamically scoped into this function
15022 (let* ((repeat (org-get-repeat))
15023 (aa (assoc last-state org-todo-kwd-alist))
15024 (interpret (nth 1 aa))
15025 (head (nth 2 aa))
15026 (whata '(("d" . day) ("m" . month) ("y" . year)))
15027 (msg "Entry repeats: ")
15028 (org-log-done nil)
15029 (org-todo-log-states nil)
15030 (nshiftmax 10) (nshift 0)
15031 re type n what ts mb0 time)
15032 (when repeat
15033 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
15034 (org-todo (if (eq interpret 'type) last-state head))
15035 (when (and org-log-repeat
15036 (or (not (memq 'org-add-log-note
15037 (default-value 'post-command-hook)))
15038 (eq org-log-note-purpose 'done)))
15039 ;; Make sure a note is taken;
15040 (org-add-log-maybe 'state (or done-word (car org-done-keywords))
15041 'findpos org-log-repeat))
15042 (org-back-to-heading t)
15043 (org-add-planning-info nil nil 'closed)
15044 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
15045 org-deadline-time-regexp "\\)\\|\\("
15046 org-ts-regexp "\\)"))
15047 (while (re-search-forward
15048 re (save-excursion (outline-next-heading) (point)) t)
15049 (setq type (if (match-end 1) org-scheduled-string
15050 (if (match-end 3) org-deadline-string "Plain:"))
15051 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
15052 mb0 (match-beginning 0))
15053 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
15054 (setq n (string-to-number (match-string 2 ts))
15055 what (match-string 3 ts))
15056 (if (equal what "w") (setq n (* n 7) what "d"))
15057 ;; Preparation, see if we need to modify the start date for the change
15058 (when (match-end 1)
15059 (setq time (save-match-data (org-time-string-to-time ts)))
15060 (cond
15061 ((equal (match-string 1 ts) ".")
15062 ;; Shift starting date to today
15063 (org-timestamp-change
15064 (- (time-to-days (current-time)) (time-to-days time))
15065 'day))
15066 ((equal (match-string 1 ts) "+")
15067 (while (< (time-to-days time) (time-to-days (current-time)))
15068 (when (= (incf nshift) nshiftmax)
15069 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
15070 (error "Abort")))
15071 (org-timestamp-change n (cdr (assoc what whata)))
15072 (sit-for .0001) ;; so we can watch the date shifting
15073 (org-at-timestamp-p t)
15074 (setq ts (match-string 1))
15075 (setq time (save-match-data (org-time-string-to-time ts))))
15076 (org-timestamp-change (- n) (cdr (assoc what whata)))
15077 ;; rematch, so that we have everything in place for the real shift
15078 (org-at-timestamp-p t)
15079 (setq ts (match-string 1))
15080 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
15081 (org-timestamp-change n (cdr (assoc what whata)))
15082 (setq msg (concat msg type org-last-changed-timestamp " "))))
15083 (setq org-log-post-message msg)
15084 (message "%s" msg))))
15086 (defun org-show-todo-tree (arg)
15087 "Make a compact tree which shows all headlines marked with TODO.
15088 The tree will show the lines where the regexp matches, and all higher
15089 headlines above the match.
15090 With a \\[universal-argument] prefix, also show the DONE entries.
15091 With a numeric prefix N, construct a sparse tree for the Nth element
15092 of `org-todo-keywords-1'."
15093 (interactive "P")
15094 (let ((case-fold-search nil)
15095 (kwd-re
15096 (cond ((null arg) org-not-done-regexp)
15097 ((equal arg '(4))
15098 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
15099 (mapcar 'list org-todo-keywords-1))))
15100 (concat "\\("
15101 (mapconcat 'identity (org-split-string kwd "|") "\\|")
15102 "\\)\\>")))
15103 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
15104 (regexp-quote (nth (1- (prefix-numeric-value arg))
15105 org-todo-keywords-1)))
15106 (t (error "Invalid prefix argument: %s" arg)))))
15107 (message "%d TODO entries found"
15108 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
15110 (defun org-deadline (&optional remove)
15111 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
15112 With argument REMOVE, remove any deadline from the item."
15113 (interactive "P")
15114 (if remove
15115 (progn
15116 (org-remove-timestamp-with-keyword org-deadline-string)
15117 (message "Item no longer has a deadline."))
15118 (org-add-planning-info 'deadline nil 'closed)))
15120 (defun org-schedule (&optional remove)
15121 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
15122 With argument REMOVE, remove any scheduling date from the item."
15123 (interactive "P")
15124 (if remove
15125 (progn
15126 (org-remove-timestamp-with-keyword org-scheduled-string)
15127 (message "Item is no longer scheduled."))
15128 (org-add-planning-info 'scheduled nil 'closed)))
15130 (defun org-remove-timestamp-with-keyword (keyword)
15131 "Remove all time stamps with KEYWORD in the current entry."
15132 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
15133 beg)
15134 (save-excursion
15135 (org-back-to-heading t)
15136 (setq beg (point))
15137 (org-end-of-subtree t t)
15138 (while (re-search-backward re beg t)
15139 (replace-match "")
15140 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
15141 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
15143 (defun org-add-planning-info (what &optional time &rest remove)
15144 "Insert new timestamp with keyword in the line directly after the headline.
15145 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
15146 If non is given, the user is prompted for a date.
15147 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
15148 be removed."
15149 (interactive)
15150 (let (org-time-was-given org-end-time-was-given)
15151 (when what (setq time (or time (org-read-date nil 'to-time))))
15152 (when (and org-insert-labeled-timestamps-at-point
15153 (member what '(scheduled deadline)))
15154 (insert
15155 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
15156 (org-insert-time-stamp time org-time-was-given
15157 nil nil nil (list org-end-time-was-given))
15158 (setq what nil))
15159 (save-excursion
15160 (save-restriction
15161 (let (col list elt ts buffer-invisibility-spec)
15162 (org-back-to-heading t)
15163 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
15164 (goto-char (match-end 1))
15165 (setq col (current-column))
15166 (goto-char (match-end 0))
15167 (if (eobp) (insert "\n") (forward-char 1))
15168 (if (and (not (looking-at outline-regexp))
15169 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
15170 "[^\r\n]*"))
15171 (not (equal (match-string 1) org-clock-string)))
15172 (narrow-to-region (match-beginning 0) (match-end 0))
15173 (insert-before-markers "\n")
15174 (backward-char 1)
15175 (narrow-to-region (point) (point))
15176 (indent-to-column col))
15177 ;; Check if we have to remove something.
15178 (setq list (cons what remove))
15179 (while list
15180 (setq elt (pop list))
15181 (goto-char (point-min))
15182 (when (or (and (eq elt 'scheduled)
15183 (re-search-forward org-scheduled-time-regexp nil t))
15184 (and (eq elt 'deadline)
15185 (re-search-forward org-deadline-time-regexp nil t))
15186 (and (eq elt 'closed)
15187 (re-search-forward org-closed-time-regexp nil t)))
15188 (replace-match "")
15189 (if (looking-at "--+<[^>]+>") (replace-match ""))
15190 (if (looking-at " +") (replace-match ""))))
15191 (goto-char (point-max))
15192 (when what
15193 (insert
15194 (if (not (equal (char-before) ?\ )) " " "")
15195 (cond ((eq what 'scheduled) org-scheduled-string)
15196 ((eq what 'deadline) org-deadline-string)
15197 ((eq what 'closed) org-closed-string))
15198 " ")
15199 (setq ts (org-insert-time-stamp
15200 time
15201 (or org-time-was-given
15202 (and (eq what 'closed) org-log-done-with-time))
15203 (eq what 'closed)
15204 nil nil (list org-end-time-was-given)))
15205 (end-of-line 1))
15206 (goto-char (point-min))
15207 (widen)
15208 (if (looking-at "[ \t]+\r?\n")
15209 (replace-match ""))
15210 ts)))))
15212 (defvar org-log-note-marker (make-marker))
15213 (defvar org-log-note-purpose nil)
15214 (defvar org-log-note-state nil)
15215 (defvar org-log-note-how nil)
15216 (defvar org-log-note-window-configuration nil)
15217 (defvar org-log-note-return-to (make-marker))
15218 (defvar org-log-post-message nil
15219 "Message to be displayed after a log note has been stored.
15220 The auto-repeater uses this.")
15222 (defun org-add-log-maybe (&optional purpose state findpos how)
15223 "Set up the post command hook to take a note.
15224 If this is about to TODO state change, the new state is expected in STATE.
15225 When FINDPOS is non-nil, find the correct position for the note in
15226 the current entry. If not, assume that it can be inserted at point."
15227 (save-excursion
15228 (when findpos
15229 (org-back-to-heading t)
15230 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
15231 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
15232 "[^\r\n]*\\)?"))
15233 (goto-char (match-end 0))
15234 (unless org-log-states-order-reversed
15235 (and (= (char-after) ?\n) (forward-char 1))
15236 (org-skip-over-state-notes)
15237 (skip-chars-backward " \t\n\r")))
15238 (move-marker org-log-note-marker (point))
15239 (setq org-log-note-purpose purpose
15240 org-log-note-state state
15241 org-log-note-how how)
15242 (add-hook 'post-command-hook 'org-add-log-note 'append)))
15244 (defun org-skip-over-state-notes ()
15245 "Skip past the list of State notes in an entry."
15246 (if (looking-at "\n[ \t]*- State") (forward-char 1))
15247 (while (looking-at "[ \t]*- State")
15248 (condition-case nil
15249 (org-next-item)
15250 (error (org-end-of-item)))))
15252 (defun org-add-log-note (&optional purpose)
15253 "Pop up a window for taking a note, and add this note later at point."
15254 (remove-hook 'post-command-hook 'org-add-log-note)
15255 (setq org-log-note-window-configuration (current-window-configuration))
15256 (delete-other-windows)
15257 (move-marker org-log-note-return-to (point))
15258 (switch-to-buffer (marker-buffer org-log-note-marker))
15259 (goto-char org-log-note-marker)
15260 (org-switch-to-buffer-other-window "*Org Note*")
15261 (erase-buffer)
15262 (if (memq org-log-note-how '(time state)) ; FIXME: time or state????????????
15263 (org-store-log-note)
15264 (let ((org-inhibit-startup t)) (org-mode))
15265 (insert (format "# Insert note for %s.
15266 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
15267 (cond
15268 ((eq org-log-note-purpose 'clock-out) "stopped clock")
15269 ((eq org-log-note-purpose 'done) "closed todo item")
15270 ((eq org-log-note-purpose 'state)
15271 (format "state change to \"%s\"" org-log-note-state))
15272 (t (error "This should not happen")))))
15273 (org-set-local 'org-finish-function 'org-store-log-note)))
15275 (defun org-store-log-note ()
15276 "Finish taking a log note, and insert it to where it belongs."
15277 (let ((txt (buffer-string))
15278 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
15279 lines ind)
15280 (kill-buffer (current-buffer))
15281 (while (string-match "\\`#.*\n[ \t\n]*" txt)
15282 (setq txt (replace-match "" t t txt)))
15283 (if (string-match "\\s-+\\'" txt)
15284 (setq txt (replace-match "" t t txt)))
15285 (setq lines (org-split-string txt "\n"))
15286 (when (and note (string-match "\\S-" note))
15287 (setq note
15288 (org-replace-escapes
15289 note
15290 (list (cons "%u" (user-login-name))
15291 (cons "%U" user-full-name)
15292 (cons "%t" (format-time-string
15293 (org-time-stamp-format 'long 'inactive)
15294 (current-time)))
15295 (cons "%s" (if org-log-note-state
15296 (concat "\"" org-log-note-state "\"")
15297 "")))))
15298 (if lines (setq note (concat note " \\\\")))
15299 (push note lines))
15300 (when (or current-prefix-arg org-note-abort) (setq lines nil))
15301 (when lines
15302 (save-excursion
15303 (set-buffer (marker-buffer org-log-note-marker))
15304 (save-excursion
15305 (goto-char org-log-note-marker)
15306 (move-marker org-log-note-marker nil)
15307 (end-of-line 1)
15308 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
15309 (indent-relative nil)
15310 (insert "- " (pop lines))
15311 (org-indent-line-function)
15312 (beginning-of-line 1)
15313 (looking-at "[ \t]*")
15314 (setq ind (concat (match-string 0) " "))
15315 (end-of-line 1)
15316 (while lines (insert "\n" ind (pop lines)))))))
15317 (set-window-configuration org-log-note-window-configuration)
15318 (with-current-buffer (marker-buffer org-log-note-return-to)
15319 (goto-char org-log-note-return-to))
15320 (move-marker org-log-note-return-to nil)
15321 (and org-log-post-message (message "%s" org-log-post-message)))
15323 ;; FIXME: what else would be useful?
15324 ;; - priority
15325 ;; - date
15327 (defun org-sparse-tree (&optional arg)
15328 "Create a sparse tree, prompt for the details.
15329 This command can create sparse trees. You first need to select the type
15330 of match used to create the tree:
15332 t Show entries with a specific TODO keyword.
15333 T Show entries selected by a tags match.
15334 p Enter a property name and its value (both with completion on existing
15335 names/values) and show entries with that property.
15336 r Show entries matching a regular expression
15337 d Show deadlines due within `org-deadline-warning-days'."
15338 (interactive "P")
15339 (let (ans kwd value)
15340 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
15341 (setq ans (read-char-exclusive))
15342 (cond
15343 ((equal ans ?d)
15344 (call-interactively 'org-check-deadlines))
15345 ((equal ans ?b)
15346 (call-interactively 'org-check-before-date))
15347 ((equal ans ?t)
15348 (org-show-todo-tree '(4)))
15349 ((equal ans ?T)
15350 (call-interactively 'org-tags-sparse-tree))
15351 ((member ans '(?p ?P))
15352 (setq kwd (completing-read "Property: "
15353 (mapcar 'list (org-buffer-property-keys))))
15354 (setq value (completing-read "Value: "
15355 (mapcar 'list (org-property-values kwd))))
15356 (unless (string-match "\\`{.*}\\'" value)
15357 (setq value (concat "\"" value "\"")))
15358 (org-tags-sparse-tree arg (concat kwd "=" value)))
15359 ((member ans '(?r ?R ?/))
15360 (call-interactively 'org-occur))
15361 (t (error "No such sparse tree command \"%c\"" ans)))))
15363 (defvar org-occur-highlights nil
15364 "List of overlays used for occur matches.")
15365 (make-variable-buffer-local 'org-occur-highlights)
15366 (defvar org-occur-parameters nil
15367 "Parameters of the active org-occur calls.
15368 This is a list, each call to org-occur pushes as cons cell,
15369 containing the regular expression and the callback, onto the list.
15370 The list can contain several entries if `org-occur' has been called
15371 several time with the KEEP-PREVIOUS argument. Otherwise, this list
15372 will only contain one set of parameters. When the highlights are
15373 removed (for example with `C-c C-c', or with the next edit (depending
15374 on `org-remove-highlights-with-change'), this variable is emptied
15375 as well.")
15376 (make-variable-buffer-local 'org-occur-parameters)
15378 (defun org-occur (regexp &optional keep-previous callback)
15379 "Make a compact tree which shows all matches of REGEXP.
15380 The tree will show the lines where the regexp matches, and all higher
15381 headlines above the match. It will also show the heading after the match,
15382 to make sure editing the matching entry is easy.
15383 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
15384 call to `org-occur' will be kept, to allow stacking of calls to this
15385 command.
15386 If CALLBACK is non-nil, it is a function which is called to confirm
15387 that the match should indeed be shown."
15388 (interactive "sRegexp: \nP")
15389 (unless keep-previous
15390 (org-remove-occur-highlights nil nil t))
15391 (push (cons regexp callback) org-occur-parameters)
15392 (let ((cnt 0))
15393 (save-excursion
15394 (goto-char (point-min))
15395 (if (or (not keep-previous) ; do not want to keep
15396 (not org-occur-highlights)) ; no previous matches
15397 ;; hide everything
15398 (org-overview))
15399 (while (re-search-forward regexp nil t)
15400 (when (or (not callback)
15401 (save-match-data (funcall callback)))
15402 (setq cnt (1+ cnt))
15403 (when org-highlight-sparse-tree-matches
15404 (org-highlight-new-match (match-beginning 0) (match-end 0)))
15405 (org-show-context 'occur-tree))))
15406 (when org-remove-highlights-with-change
15407 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
15408 nil 'local))
15409 (unless org-sparse-tree-open-archived-trees
15410 (org-hide-archived-subtrees (point-min) (point-max)))
15411 (run-hooks 'org-occur-hook)
15412 (if (interactive-p)
15413 (message "%d match(es) for regexp %s" cnt regexp))
15414 cnt))
15416 (defun org-show-context (&optional key)
15417 "Make sure point and context and visible.
15418 How much context is shown depends upon the variables
15419 `org-show-hierarchy-above', `org-show-following-heading'. and
15420 `org-show-siblings'."
15421 (let ((heading-p (org-on-heading-p t))
15422 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
15423 (following-p (org-get-alist-option org-show-following-heading key))
15424 (entry-p (org-get-alist-option org-show-entry-below key))
15425 (siblings-p (org-get-alist-option org-show-siblings key)))
15426 (catch 'exit
15427 ;; Show heading or entry text
15428 (if (and heading-p (not entry-p))
15429 (org-flag-heading nil) ; only show the heading
15430 (and (or entry-p (org-invisible-p) (org-invisible-p2))
15431 (org-show-hidden-entry))) ; show entire entry
15432 (when following-p
15433 ;; Show next sibling, or heading below text
15434 (save-excursion
15435 (and (if heading-p (org-goto-sibling) (outline-next-heading))
15436 (org-flag-heading nil))))
15437 (when siblings-p (org-show-siblings))
15438 (when hierarchy-p
15439 ;; show all higher headings, possibly with siblings
15440 (save-excursion
15441 (while (and (condition-case nil
15442 (progn (org-up-heading-all 1) t)
15443 (error nil))
15444 (not (bobp)))
15445 (org-flag-heading nil)
15446 (when siblings-p (org-show-siblings))))))))
15448 (defun org-reveal (&optional siblings)
15449 "Show current entry, hierarchy above it, and the following headline.
15450 This can be used to show a consistent set of context around locations
15451 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
15452 not t for the search context.
15454 With optional argument SIBLINGS, on each level of the hierarchy all
15455 siblings are shown. This repairs the tree structure to what it would
15456 look like when opened with hierarchical calls to `org-cycle'."
15457 (interactive "P")
15458 (let ((org-show-hierarchy-above t)
15459 (org-show-following-heading t)
15460 (org-show-siblings (if siblings t org-show-siblings)))
15461 (org-show-context nil)))
15463 (defun org-highlight-new-match (beg end)
15464 "Highlight from BEG to END and mark the highlight is an occur headline."
15465 (let ((ov (org-make-overlay beg end)))
15466 (org-overlay-put ov 'face 'secondary-selection)
15467 (push ov org-occur-highlights)))
15469 (defun org-remove-occur-highlights (&optional beg end noremove)
15470 "Remove the occur highlights from the buffer.
15471 BEG and END are ignored. If NOREMOVE is nil, remove this function
15472 from the `before-change-functions' in the current buffer."
15473 (interactive)
15474 (unless org-inhibit-highlight-removal
15475 (mapc 'org-delete-overlay org-occur-highlights)
15476 (setq org-occur-highlights nil)
15477 (setq org-occur-parameters nil)
15478 (unless noremove
15479 (remove-hook 'before-change-functions
15480 'org-remove-occur-highlights 'local))))
15482 ;;;; Priorities
15484 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
15485 "Regular expression matching the priority indicator.")
15487 (defvar org-remove-priority-next-time nil)
15489 (defun org-priority-up ()
15490 "Increase the priority of the current item."
15491 (interactive)
15492 (org-priority 'up))
15494 (defun org-priority-down ()
15495 "Decrease the priority of the current item."
15496 (interactive)
15497 (org-priority 'down))
15499 (defun org-priority (&optional action)
15500 "Change the priority of an item by ARG.
15501 ACTION can be `set', `up', `down', or a character."
15502 (interactive)
15503 (setq action (or action 'set))
15504 (let (current new news have remove)
15505 (save-excursion
15506 (org-back-to-heading)
15507 (if (looking-at org-priority-regexp)
15508 (setq current (string-to-char (match-string 2))
15509 have t)
15510 (setq current org-default-priority))
15511 (cond
15512 ((or (eq action 'set) (integerp action))
15513 (if (integerp action)
15514 (setq new action)
15515 (message "Priority %c-%c, SPC to remove: " org-highest-priority org-lowest-priority)
15516 (setq new (read-char-exclusive)))
15517 (if (and (= (upcase org-highest-priority) org-highest-priority)
15518 (= (upcase org-lowest-priority) org-lowest-priority))
15519 (setq new (upcase new)))
15520 (cond ((equal new ?\ ) (setq remove t))
15521 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
15522 (error "Priority must be between `%c' and `%c'"
15523 org-highest-priority org-lowest-priority))))
15524 ((eq action 'up)
15525 (if (and (not have) (eq last-command this-command))
15526 (setq new org-lowest-priority)
15527 (setq new (if (and org-priority-start-cycle-with-default (not have))
15528 org-default-priority (1- current)))))
15529 ((eq action 'down)
15530 (if (and (not have) (eq last-command this-command))
15531 (setq new org-highest-priority)
15532 (setq new (if (and org-priority-start-cycle-with-default (not have))
15533 org-default-priority (1+ current)))))
15534 (t (error "Invalid action")))
15535 (if (or (< (upcase new) org-highest-priority)
15536 (> (upcase new) org-lowest-priority))
15537 (setq remove t))
15538 (setq news (format "%c" new))
15539 (if have
15540 (if remove
15541 (replace-match "" t t nil 1)
15542 (replace-match news t t nil 2))
15543 (if remove
15544 (error "No priority cookie found in line")
15545 (looking-at org-todo-line-regexp)
15546 (if (match-end 2)
15547 (progn
15548 (goto-char (match-end 2))
15549 (insert " [#" news "]"))
15550 (goto-char (match-beginning 3))
15551 (insert "[#" news "] ")))))
15552 (org-preserve-lc (org-set-tags nil 'align))
15553 (if remove
15554 (message "Priority removed")
15555 (message "Priority of current item set to %s" news))))
15558 (defun org-get-priority (s)
15559 "Find priority cookie and return priority."
15560 (save-match-data
15561 (if (not (string-match org-priority-regexp s))
15562 (* 1000 (- org-lowest-priority org-default-priority))
15563 (* 1000 (- org-lowest-priority
15564 (string-to-char (match-string 2 s)))))))
15566 ;;;; Tags
15568 (defun org-scan-tags (action matcher &optional todo-only)
15569 "Scan headline tags with inheritance and produce output ACTION.
15570 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
15571 evaluated, testing if a given set of tags qualifies a headline for
15572 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
15573 are included in the output."
15574 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
15575 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
15576 (org-re
15577 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
15578 (props (list 'face nil
15579 'done-face 'org-done
15580 'undone-face nil
15581 'mouse-face 'highlight
15582 'org-not-done-regexp org-not-done-regexp
15583 'org-todo-regexp org-todo-regexp
15584 'keymap org-agenda-keymap
15585 'help-echo
15586 (format "mouse-2 or RET jump to org file %s"
15587 (abbreviate-file-name
15588 (or (buffer-file-name (buffer-base-buffer))
15589 (buffer-name (buffer-base-buffer)))))))
15590 (case-fold-search nil)
15591 lspos
15592 tags tags-list tags-alist (llast 0) rtn level category i txt
15593 todo marker entry priority)
15594 (save-excursion
15595 (goto-char (point-min))
15596 (when (eq action 'sparse-tree)
15597 (org-overview)
15598 (org-remove-occur-highlights))
15599 (while (re-search-forward re nil t)
15600 (catch :skip
15601 (setq todo (if (match-end 1) (match-string 2))
15602 tags (if (match-end 4) (match-string 4)))
15603 (goto-char (setq lspos (1+ (match-beginning 0))))
15604 (setq level (org-reduced-level (funcall outline-level))
15605 category (org-get-category))
15606 (setq i llast llast level)
15607 ;; remove tag lists from same and sublevels
15608 (while (>= i level)
15609 (when (setq entry (assoc i tags-alist))
15610 (setq tags-alist (delete entry tags-alist)))
15611 (setq i (1- i)))
15612 ;; add the nex tags
15613 (when tags
15614 (setq tags (mapcar 'downcase (org-split-string tags ":"))
15615 tags-alist
15616 (cons (cons level tags) tags-alist)))
15617 ;; compile tags for current headline
15618 (setq tags-list
15619 (if org-use-tag-inheritance
15620 (apply 'append (mapcar 'cdr tags-alist))
15621 tags))
15622 (when (and (or (not todo-only) (member todo org-not-done-keywords))
15623 (eval matcher)
15624 (or (not org-agenda-skip-archived-trees)
15625 (not (member org-archive-tag tags-list))))
15626 (and (eq action 'agenda) (org-agenda-skip))
15627 ;; list this headline
15629 (if (eq action 'sparse-tree)
15630 (progn
15631 (and org-highlight-sparse-tree-matches
15632 (org-get-heading) (match-end 0)
15633 (org-highlight-new-match
15634 (match-beginning 0) (match-beginning 1)))
15635 (org-show-context 'tags-tree))
15636 (setq txt (org-format-agenda-item
15638 (concat
15639 (if org-tags-match-list-sublevels
15640 (make-string (1- level) ?.) "")
15641 (org-get-heading))
15642 category tags-list)
15643 priority (org-get-priority txt))
15644 (goto-char lspos)
15645 (setq marker (org-agenda-new-marker))
15646 (org-add-props txt props
15647 'org-marker marker 'org-hd-marker marker 'org-category category
15648 'priority priority 'type "tagsmatch")
15649 (push txt rtn))
15650 ;; if we are to skip sublevels, jump to end of subtree
15651 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
15652 (when (and (eq action 'sparse-tree)
15653 (not org-sparse-tree-open-archived-trees))
15654 (org-hide-archived-subtrees (point-min) (point-max)))
15655 (nreverse rtn)))
15657 (defvar todo-only) ;; dynamically scoped
15659 (defun org-tags-sparse-tree (&optional todo-only match)
15660 "Create a sparse tree according to tags string MATCH.
15661 MATCH can contain positive and negative selection of tags, like
15662 \"+WORK+URGENT-WITHBOSS\".
15663 If optional argument TODO_ONLY is non-nil, only select lines that are
15664 also TODO lines."
15665 (interactive "P")
15666 (org-prepare-agenda-buffers (list (current-buffer)))
15667 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
15669 (defvar org-cached-props nil)
15670 (defun org-cached-entry-get (pom property)
15671 (if (or (eq t org-use-property-inheritance)
15672 (member property org-use-property-inheritance))
15673 ;; Caching is not possible, check it directly
15674 (org-entry-get pom property 'inherit)
15675 ;; Get all properties, so that we can do complicated checks easily
15676 (cdr (assoc property (or org-cached-props
15677 (setq org-cached-props
15678 (org-entry-properties pom)))))))
15680 (defun org-global-tags-completion-table (&optional files)
15681 "Return the list of all tags in all agenda buffer/files."
15682 (save-excursion
15683 (org-uniquify
15684 (delq nil
15685 (apply 'append
15686 (mapcar
15687 (lambda (file)
15688 (set-buffer (find-file-noselect file))
15689 (append (org-get-buffer-tags)
15690 (mapcar (lambda (x) (if (stringp (car-safe x))
15691 (list (car-safe x)) nil))
15692 org-tag-alist)))
15693 (if (and files (car files))
15694 files
15695 (org-agenda-files))))))))
15697 (defun org-make-tags-matcher (match)
15698 "Create the TAGS//TODO matcher form for the selection string MATCH."
15699 ;; todo-only is scoped dynamically into this function, and the function
15700 ;; may change it it the matcher asksk for it.
15701 (unless match
15702 ;; Get a new match request, with completion
15703 (let ((org-last-tags-completion-table
15704 (org-global-tags-completion-table)))
15705 (setq match (completing-read
15706 "Match: " 'org-tags-completion-function nil nil nil
15707 'org-tags-history))))
15709 ;; Parse the string and create a lisp form
15710 (let ((match0 match)
15711 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL=\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)=\\({[^}]+}\\|\"[^\"]*\"\\)\\|[[:alnum:]_@]+\\)"))
15712 minus tag mm
15713 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
15714 orterms term orlist re-p level-p prop-p pn pv cat-p gv)
15715 (if (string-match "/+" match)
15716 ;; match contains also a todo-matching request
15717 (progn
15718 (setq tagsmatch (substring match 0 (match-beginning 0))
15719 todomatch (substring match (match-end 0)))
15720 (if (string-match "^!" todomatch)
15721 (setq todo-only t todomatch (substring todomatch 1)))
15722 (if (string-match "^\\s-*$" todomatch)
15723 (setq todomatch nil)))
15724 ;; only matching tags
15725 (setq tagsmatch match todomatch nil))
15727 ;; Make the tags matcher
15728 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
15729 (setq tagsmatcher t)
15730 (setq orterms (org-split-string tagsmatch "|") orlist nil)
15731 (while (setq term (pop orterms))
15732 (while (and (equal (substring term -1) "\\") orterms)
15733 (setq term (concat term "|" (pop orterms)))) ; repair bad split
15734 (while (string-match re term)
15735 (setq minus (and (match-end 1)
15736 (equal (match-string 1 term) "-"))
15737 tag (match-string 2 term)
15738 re-p (equal (string-to-char tag) ?{)
15739 level-p (match-end 3)
15740 prop-p (match-end 4)
15741 mm (cond
15742 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
15743 (level-p `(= level ,(string-to-number
15744 (match-string 3 term))))
15745 (prop-p
15746 (setq pn (match-string 4 term)
15747 pv (match-string 5 term)
15748 cat-p (equal pn "CATEGORY")
15749 re-p (equal (string-to-char pv) ?{)
15750 pv (substring pv 1 -1))
15751 (if (equal pn "CATEGORY")
15752 (setq gv '(get-text-property (point) 'org-category))
15753 (setq gv `(org-cached-entry-get nil ,pn)))
15754 (if re-p
15755 `(string-match ,pv (or ,gv ""))
15756 `(equal ,pv (or ,gv ""))))
15757 (t `(member ,(downcase tag) tags-list)))
15758 mm (if minus (list 'not mm) mm)
15759 term (substring term (match-end 0)))
15760 (push mm tagsmatcher))
15761 (push (if (> (length tagsmatcher) 1)
15762 (cons 'and tagsmatcher)
15763 (car tagsmatcher))
15764 orlist)
15765 (setq tagsmatcher nil))
15766 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
15767 (setq tagsmatcher
15768 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
15770 ;; Make the todo matcher
15771 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
15772 (setq todomatcher t)
15773 (setq orterms (org-split-string todomatch "|") orlist nil)
15774 (while (setq term (pop orterms))
15775 (while (string-match re term)
15776 (setq minus (and (match-end 1)
15777 (equal (match-string 1 term) "-"))
15778 kwd (match-string 2 term)
15779 re-p (equal (string-to-char kwd) ?{)
15780 term (substring term (match-end 0))
15781 mm (if re-p
15782 `(string-match ,(substring kwd 1 -1) todo)
15783 (list 'equal 'todo kwd))
15784 mm (if minus (list 'not mm) mm))
15785 (push mm todomatcher))
15786 (push (if (> (length todomatcher) 1)
15787 (cons 'and todomatcher)
15788 (car todomatcher))
15789 orlist)
15790 (setq todomatcher nil))
15791 (setq todomatcher (if (> (length orlist) 1)
15792 (cons 'or orlist) (car orlist))))
15794 ;; Return the string and lisp forms of the matcher
15795 (setq matcher (if todomatcher
15796 (list 'and tagsmatcher todomatcher)
15797 tagsmatcher))
15798 (cons match0 matcher)))
15800 (defun org-match-any-p (re list)
15801 "Does re match any element of list?"
15802 (setq list (mapcar (lambda (x) (string-match re x)) list))
15803 (delq nil list))
15805 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
15806 (defvar org-tags-overlay (org-make-overlay 1 1))
15807 (org-detach-overlay org-tags-overlay)
15809 (defun org-align-tags-here (to-col)
15810 ;; Assumes that this is a headline
15811 (let ((pos (point)) (col (current-column)) tags)
15812 (beginning-of-line 1)
15813 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15814 (< pos (match-beginning 2)))
15815 (progn
15816 (setq tags (match-string 2))
15817 (goto-char (match-beginning 1))
15818 (insert " ")
15819 (delete-region (point) (1+ (match-end 0)))
15820 (backward-char 1)
15821 (move-to-column
15822 (max (1+ (current-column))
15823 (1+ col)
15824 (if (> to-col 0)
15825 to-col
15826 (- (abs to-col) (length tags))))
15828 (insert tags)
15829 (move-to-column (min (current-column) col) t))
15830 (goto-char pos))))
15832 (defun org-set-tags (&optional arg just-align)
15833 "Set the tags for the current headline.
15834 With prefix ARG, realign all tags in headings in the current buffer."
15835 (interactive "P")
15836 (let* ((re (concat "^" outline-regexp))
15837 (current (org-get-tags-string))
15838 (col (current-column))
15839 (org-setting-tags t)
15840 table current-tags inherited-tags ; computed below when needed
15841 tags p0 c0 c1 rpl)
15842 (if arg
15843 (save-excursion
15844 (goto-char (point-min))
15845 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15846 (while (re-search-forward re nil t)
15847 (org-set-tags nil t)
15848 (end-of-line 1)))
15849 (message "All tags realigned to column %d" org-tags-column))
15850 (if just-align
15851 (setq tags current)
15852 ;; Get a new set of tags from the user
15853 (save-excursion
15854 (setq table (or org-tag-alist (org-get-buffer-tags))
15855 org-last-tags-completion-table table
15856 current-tags (org-split-string current ":")
15857 inherited-tags (nreverse
15858 (nthcdr (length current-tags)
15859 (nreverse (org-get-tags-at))))
15860 tags
15861 (if (or (eq t org-use-fast-tag-selection)
15862 (and org-use-fast-tag-selection
15863 (delq nil (mapcar 'cdr table))))
15864 (org-fast-tag-selection
15865 current-tags inherited-tags table
15866 (if org-fast-tag-selection-include-todo org-todo-key-alist))
15867 (let ((org-add-colon-after-tag-completion t))
15868 (org-trim
15869 (org-without-partial-completion
15870 (completing-read "Tags: " 'org-tags-completion-function
15871 nil nil current 'org-tags-history)))))))
15872 (while (string-match "[-+&]+" tags)
15873 ;; No boolean logic, just a list
15874 (setq tags (replace-match ":" t t tags))))
15876 (if (string-match "\\`[\t ]*\\'" tags)
15877 (setq tags "")
15878 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
15879 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
15881 ;; Insert new tags at the correct column
15882 (beginning-of-line 1)
15883 (cond
15884 ((and (equal current "") (equal tags "")))
15885 ((re-search-forward
15886 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15887 (point-at-eol) t)
15888 (if (equal tags "")
15889 (setq rpl "")
15890 (goto-char (match-beginning 0))
15891 (setq c0 (current-column) p0 (point)
15892 c1 (max (1+ c0) (if (> org-tags-column 0)
15893 org-tags-column
15894 (- (- org-tags-column) (length tags))))
15895 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
15896 (replace-match rpl t t)
15897 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
15898 tags)
15899 (t (error "Tags alignment failed")))
15900 (move-to-column col)
15901 (unless just-align
15902 (run-hooks 'org-after-tags-change-hook)))))
15904 (defun org-change-tag-in-region (beg end tag off)
15905 "Add or remove TAG for each entry in the region.
15906 This works in the agenda, and also in an org-mode buffer."
15907 (interactive
15908 (list (region-beginning) (region-end)
15909 (let ((org-last-tags-completion-table
15910 (if (org-mode-p)
15911 (org-get-buffer-tags)
15912 (org-global-tags-completion-table))))
15913 (completing-read
15914 "Tag: " 'org-tags-completion-function nil nil nil
15915 'org-tags-history))
15916 (progn
15917 (message "[s]et or [r]emove? ")
15918 (equal (read-char-exclusive) ?r))))
15919 (if (fboundp 'deactivate-mark) (deactivate-mark))
15920 (let ((agendap (equal major-mode 'org-agenda-mode))
15921 l1 l2 m buf pos newhead (cnt 0))
15922 (goto-char end)
15923 (setq l2 (1- (org-current-line)))
15924 (goto-char beg)
15925 (setq l1 (org-current-line))
15926 (loop for l from l1 to l2 do
15927 (goto-line l)
15928 (setq m (get-text-property (point) 'org-hd-marker))
15929 (when (or (and (org-mode-p) (org-on-heading-p))
15930 (and agendap m))
15931 (setq buf (if agendap (marker-buffer m) (current-buffer))
15932 pos (if agendap m (point)))
15933 (with-current-buffer buf
15934 (save-excursion
15935 (save-restriction
15936 (goto-char pos)
15937 (setq cnt (1+ cnt))
15938 (org-toggle-tag tag (if off 'off 'on))
15939 (setq newhead (org-get-heading)))))
15940 (and agendap (org-agenda-change-all-lines newhead m))))
15941 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15943 (defun org-tags-completion-function (string predicate &optional flag)
15944 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15945 (confirm (lambda (x) (stringp (car x)))))
15946 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
15947 (setq s1 (match-string 1 string)
15948 s2 (match-string 2 string))
15949 (setq s1 "" s2 string))
15950 (cond
15951 ((eq flag nil)
15952 ;; try completion
15953 (setq rtn (try-completion s2 ctable confirm))
15954 (if (stringp rtn)
15955 (setq rtn
15956 (concat s1 s2 (substring rtn (length s2))
15957 (if (and org-add-colon-after-tag-completion
15958 (assoc rtn ctable))
15959 ":" ""))))
15960 rtn)
15961 ((eq flag t)
15962 ;; all-completions
15963 (all-completions s2 ctable confirm)
15965 ((eq flag 'lambda)
15966 ;; exact match?
15967 (assoc s2 ctable)))
15970 (defun org-fast-tag-insert (kwd tags face &optional end)
15971 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
15972 (insert (format "%-12s" (concat kwd ":"))
15973 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15974 (or end "")))
15976 (defun org-fast-tag-show-exit (flag)
15977 (save-excursion
15978 (goto-line 3)
15979 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15980 (replace-match ""))
15981 (when flag
15982 (end-of-line 1)
15983 (move-to-column (- (window-width) 19) t)
15984 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15986 (defun org-set-current-tags-overlay (current prefix)
15987 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15988 (if (featurep 'xemacs)
15989 (org-overlay-display org-tags-overlay (concat prefix s)
15990 'secondary-selection)
15991 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15992 (org-overlay-display org-tags-overlay (concat prefix s)))))
15994 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15995 "Fast tag selection with single keys.
15996 CURRENT is the current list of tags in the headline, INHERITED is the
15997 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15998 possibly with grouping information. TODO-TABLE is a similar table with
15999 TODO keywords, should these have keys assigned to them.
16000 If the keys are nil, a-z are automatically assigned.
16001 Returns the new tags string, or nil to not change the current settings."
16002 (let* ((fulltable (append table todo-table))
16003 (maxlen (apply 'max (mapcar
16004 (lambda (x)
16005 (if (stringp (car x)) (string-width (car x)) 0))
16006 fulltable)))
16007 (buf (current-buffer))
16008 (expert (eq org-fast-tag-selection-single-key 'expert))
16009 (buffer-tags nil)
16010 (fwidth (+ maxlen 3 1 3))
16011 (ncol (/ (- (window-width) 4) fwidth))
16012 (i-face 'org-done)
16013 (c-face 'org-todo)
16014 tg cnt e c char c1 c2 ntable tbl rtn
16015 ov-start ov-end ov-prefix
16016 (exit-after-next org-fast-tag-selection-single-key)
16017 (done-keywords org-done-keywords)
16018 groups ingroup)
16019 (save-excursion
16020 (beginning-of-line 1)
16021 (if (looking-at
16022 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16023 (setq ov-start (match-beginning 1)
16024 ov-end (match-end 1)
16025 ov-prefix "")
16026 (setq ov-start (1- (point-at-eol))
16027 ov-end (1+ ov-start))
16028 (skip-chars-forward "^\n\r")
16029 (setq ov-prefix
16030 (concat
16031 (buffer-substring (1- (point)) (point))
16032 (if (> (current-column) org-tags-column)
16034 (make-string (- org-tags-column (current-column)) ?\ ))))))
16035 (org-move-overlay org-tags-overlay ov-start ov-end)
16036 (save-window-excursion
16037 (if expert
16038 (set-buffer (get-buffer-create " *Org tags*"))
16039 (delete-other-windows)
16040 (split-window-vertically)
16041 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
16042 (erase-buffer)
16043 (org-set-local 'org-done-keywords done-keywords)
16044 (org-fast-tag-insert "Inherited" inherited i-face "\n")
16045 (org-fast-tag-insert "Current" current c-face "\n\n")
16046 (org-fast-tag-show-exit exit-after-next)
16047 (org-set-current-tags-overlay current ov-prefix)
16048 (setq tbl fulltable char ?a cnt 0)
16049 (while (setq e (pop tbl))
16050 (cond
16051 ((equal e '(:startgroup))
16052 (push '() groups) (setq ingroup t)
16053 (when (not (= cnt 0))
16054 (setq cnt 0)
16055 (insert "\n"))
16056 (insert "{ "))
16057 ((equal e '(:endgroup))
16058 (setq ingroup nil cnt 0)
16059 (insert "}\n"))
16061 (setq tg (car e) c2 nil)
16062 (if (cdr e)
16063 (setq c (cdr e))
16064 ;; automatically assign a character.
16065 (setq c1 (string-to-char
16066 (downcase (substring
16067 tg (if (= (string-to-char tg) ?@) 1 0)))))
16068 (if (or (rassoc c1 ntable) (rassoc c1 table))
16069 (while (or (rassoc char ntable) (rassoc char table))
16070 (setq char (1+ char)))
16071 (setq c2 c1))
16072 (setq c (or c2 char)))
16073 (if ingroup (push tg (car groups)))
16074 (setq tg (org-add-props tg nil 'face
16075 (cond
16076 ((not (assoc tg table))
16077 (org-get-todo-face tg))
16078 ((member tg current) c-face)
16079 ((member tg inherited) i-face)
16080 (t nil))))
16081 (if (and (= cnt 0) (not ingroup)) (insert " "))
16082 (insert "[" c "] " tg (make-string
16083 (- fwidth 4 (length tg)) ?\ ))
16084 (push (cons tg c) ntable)
16085 (when (= (setq cnt (1+ cnt)) ncol)
16086 (insert "\n")
16087 (if ingroup (insert " "))
16088 (setq cnt 0)))))
16089 (setq ntable (nreverse ntable))
16090 (insert "\n")
16091 (goto-char (point-min))
16092 (if (and (not expert) (fboundp 'fit-window-to-buffer))
16093 (fit-window-to-buffer))
16094 (setq rtn
16095 (catch 'exit
16096 (while t
16097 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
16098 (if groups " [!] no groups" " [!]groups")
16099 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
16100 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
16101 (cond
16102 ((= c ?\r) (throw 'exit t))
16103 ((= c ?!)
16104 (setq groups (not groups))
16105 (goto-char (point-min))
16106 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
16107 ((= c ?\C-c)
16108 (if (not expert)
16109 (org-fast-tag-show-exit
16110 (setq exit-after-next (not exit-after-next)))
16111 (setq expert nil)
16112 (delete-other-windows)
16113 (split-window-vertically)
16114 (org-switch-to-buffer-other-window " *Org tags*")
16115 (and (fboundp 'fit-window-to-buffer)
16116 (fit-window-to-buffer))))
16117 ((or (= c ?\C-g)
16118 (and (= c ?q) (not (rassoc c ntable))))
16119 (org-detach-overlay org-tags-overlay)
16120 (setq quit-flag t))
16121 ((= c ?\ )
16122 (setq current nil)
16123 (if exit-after-next (setq exit-after-next 'now)))
16124 ((= c ?\t)
16125 (condition-case nil
16126 (setq tg (completing-read
16127 "Tag: "
16128 (or buffer-tags
16129 (with-current-buffer buf
16130 (org-get-buffer-tags)))))
16131 (quit (setq tg "")))
16132 (when (string-match "\\S-" tg)
16133 (add-to-list 'buffer-tags (list tg))
16134 (if (member tg current)
16135 (setq current (delete tg current))
16136 (push tg current)))
16137 (if exit-after-next (setq exit-after-next 'now)))
16138 ((setq e (rassoc c todo-table) tg (car e))
16139 (with-current-buffer buf
16140 (save-excursion (org-todo tg)))
16141 (if exit-after-next (setq exit-after-next 'now)))
16142 ((setq e (rassoc c ntable) tg (car e))
16143 (if (member tg current)
16144 (setq current (delete tg current))
16145 (loop for g in groups do
16146 (if (member tg g)
16147 (mapc (lambda (x)
16148 (setq current (delete x current)))
16149 g)))
16150 (push tg current))
16151 (if exit-after-next (setq exit-after-next 'now))))
16153 ;; Create a sorted list
16154 (setq current
16155 (sort current
16156 (lambda (a b)
16157 (assoc b (cdr (memq (assoc a ntable) ntable))))))
16158 (if (eq exit-after-next 'now) (throw 'exit t))
16159 (goto-char (point-min))
16160 (beginning-of-line 2)
16161 (delete-region (point) (point-at-eol))
16162 (org-fast-tag-insert "Current" current c-face)
16163 (org-set-current-tags-overlay current ov-prefix)
16164 (while (re-search-forward
16165 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
16166 (setq tg (match-string 1))
16167 (add-text-properties
16168 (match-beginning 1) (match-end 1)
16169 (list 'face
16170 (cond
16171 ((member tg current) c-face)
16172 ((member tg inherited) i-face)
16173 (t (get-text-property (match-beginning 1) 'face))))))
16174 (goto-char (point-min)))))
16175 (org-detach-overlay org-tags-overlay)
16176 (if rtn
16177 (mapconcat 'identity current ":")
16178 nil))))
16180 (defun org-get-tags-string ()
16181 "Get the TAGS string in the current headline."
16182 (unless (org-on-heading-p t)
16183 (error "Not on a heading"))
16184 (save-excursion
16185 (beginning-of-line 1)
16186 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16187 (org-match-string-no-properties 1)
16188 "")))
16190 (defun org-get-tags ()
16191 "Get the list of tags specified in the current headline."
16192 (org-split-string (org-get-tags-string) ":"))
16194 (defun org-get-buffer-tags ()
16195 "Get a table of all tags used in the buffer, for completion."
16196 (let (tags)
16197 (save-excursion
16198 (goto-char (point-min))
16199 (while (re-search-forward
16200 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
16201 (when (equal (char-after (point-at-bol 0)) ?*)
16202 (mapc (lambda (x) (add-to-list 'tags x))
16203 (org-split-string (org-match-string-no-properties 1) ":")))))
16204 (mapcar 'list tags)))
16207 ;;;; Properties
16209 ;;; Setting and retrieving properties
16211 (defconst org-special-properties
16212 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
16213 "TIMESTAMP" "TIMESTAMP_IA")
16214 "The special properties valid in Org-mode.
16216 These are properties that are not defined in the property drawer,
16217 but in some other way.")
16219 (defconst org-default-properties
16220 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
16221 "LOCATION" "LOGGING" "COLUMNS")
16222 "Some properties that are used by Org-mode for various purposes.
16223 Being in this list makes sure that they are offered for completion.")
16225 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
16226 "Regular expression matching the first line of a property drawer.")
16228 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
16229 "Regular expression matching the first line of a property drawer.")
16231 (defun org-property-action ()
16232 "Do an action on properties."
16233 (interactive)
16234 (let (c)
16235 (org-at-property-p)
16236 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
16237 (setq c (read-char-exclusive))
16238 (cond
16239 ((equal c ?s)
16240 (call-interactively 'org-set-property))
16241 ((equal c ?d)
16242 (call-interactively 'org-delete-property))
16243 ((equal c ?D)
16244 (call-interactively 'org-delete-property-globally))
16245 ((equal c ?c)
16246 (call-interactively 'org-compute-property-at-point))
16247 (t (error "No such property action %c" c)))))
16249 (defun org-at-property-p ()
16250 "Is the cursor in a property line?"
16251 ;; FIXME: Does not check if we are actually in the drawer.
16252 ;; FIXME: also returns true on any drawers.....
16253 ;; This is used by C-c C-c for property action.
16254 (save-excursion
16255 (beginning-of-line 1)
16256 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
16258 (defmacro org-with-point-at (pom &rest body)
16259 "Move to buffer and point of point-or-marker POM for the duration of BODY."
16260 (declare (indent 1) (debug t))
16261 `(save-excursion
16262 (if (markerp pom) (set-buffer (marker-buffer pom)))
16263 (save-excursion
16264 (goto-char (or pom (point)))
16265 ,@body)))
16267 (defun org-get-property-block (&optional beg end force)
16268 "Return the (beg . end) range of the body of the property drawer.
16269 BEG and END can be beginning and end of subtree, if not given
16270 they will be found.
16271 If the drawer does not exist and FORCE is non-nil, create the drawer."
16272 (catch 'exit
16273 (save-excursion
16274 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
16275 (end (or end (progn (outline-next-heading) (point)))))
16276 (goto-char beg)
16277 (if (re-search-forward org-property-start-re end t)
16278 (setq beg (1+ (match-end 0)))
16279 (if force
16280 (save-excursion
16281 (org-insert-property-drawer)
16282 (setq end (progn (outline-next-heading) (point))))
16283 (throw 'exit nil))
16284 (goto-char beg)
16285 (if (re-search-forward org-property-start-re end t)
16286 (setq beg (1+ (match-end 0)))))
16287 (if (re-search-forward org-property-end-re end t)
16288 (setq end (match-beginning 0))
16289 (or force (throw 'exit nil))
16290 (goto-char beg)
16291 (setq end beg)
16292 (org-indent-line-function)
16293 (insert ":END:\n"))
16294 (cons beg end)))))
16296 (defun org-entry-properties (&optional pom which)
16297 "Get all properties of the entry at point-or-marker POM.
16298 This includes the TODO keyword, the tags, time strings for deadline,
16299 scheduled, and clocking, and any additional properties defined in the
16300 entry. The return value is an alist, keys may occur multiple times
16301 if the property key was used several times.
16302 POM may also be nil, in which case the current entry is used.
16303 If WHICH is nil or `all', get all properties. If WHICH is
16304 `special' or `standard', only get that subclass."
16305 (setq which (or which 'all))
16306 (org-with-point-at pom
16307 (let ((clockstr (substring org-clock-string 0 -1))
16308 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
16309 beg end range props sum-props key value string clocksum)
16310 (save-excursion
16311 (when (condition-case nil (org-back-to-heading t) (error nil))
16312 (setq beg (point))
16313 (setq sum-props (get-text-property (point) 'org-summaries))
16314 (setq clocksum (get-text-property (point) :org-clock-minutes))
16315 (outline-next-heading)
16316 (setq end (point))
16317 (when (memq which '(all special))
16318 ;; Get the special properties, like TODO and tags
16319 (goto-char beg)
16320 (when (and (looking-at org-todo-line-regexp) (match-end 2))
16321 (push (cons "TODO" (org-match-string-no-properties 2)) props))
16322 (when (looking-at org-priority-regexp)
16323 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
16324 (when (and (setq value (org-get-tags-string))
16325 (string-match "\\S-" value))
16326 (push (cons "TAGS" value) props))
16327 (when (setq value (org-get-tags-at))
16328 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
16329 props))
16330 (while (re-search-forward org-maybe-keyword-time-regexp end t)
16331 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
16332 string (if (equal key clockstr)
16333 (org-no-properties
16334 (org-trim
16335 (buffer-substring
16336 (match-beginning 3) (goto-char (point-at-eol)))))
16337 (substring (org-match-string-no-properties 3) 1 -1)))
16338 (unless key
16339 (if (= (char-after (match-beginning 3)) ?\[)
16340 (setq key "TIMESTAMP_IA")
16341 (setq key "TIMESTAMP")))
16342 (when (or (equal key clockstr) (not (assoc key props)))
16343 (push (cons key string) props)))
16347 (when (memq which '(all standard))
16348 ;; Get the standard properties, like :PORP: ...
16349 (setq range (org-get-property-block beg end))
16350 (when range
16351 (goto-char (car range))
16352 (while (re-search-forward
16353 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
16354 (cdr range) t)
16355 (setq key (org-match-string-no-properties 1)
16356 value (org-trim (or (org-match-string-no-properties 2) "")))
16357 (unless (member key excluded)
16358 (push (cons key (or value "")) props)))))
16359 (if clocksum
16360 (push (cons "CLOCKSUM"
16361 (org-column-number-to-string (/ (float clocksum) 60.)
16362 'add_times))
16363 props))
16364 (append sum-props (nreverse props)))))))
16366 (defun org-entry-get (pom property &optional inherit)
16367 "Get value of PROPERTY for entry at point-or-marker POM.
16368 If INHERIT is non-nil and the entry does not have the property,
16369 then also check higher levels of the hierarchy.
16370 If the property is present but empty, the return value is the empty string.
16371 If the property is not present at all, nil is returned."
16372 (org-with-point-at pom
16373 (if inherit
16374 (org-entry-get-with-inheritance property)
16375 (if (member property org-special-properties)
16376 ;; We need a special property. Use brute force, get all properties.
16377 (cdr (assoc property (org-entry-properties nil 'special)))
16378 (let ((range (org-get-property-block)))
16379 (if (and range
16380 (goto-char (car range))
16381 (re-search-forward
16382 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
16383 (cdr range) t))
16384 ;; Found the property, return it.
16385 (if (match-end 1)
16386 (org-match-string-no-properties 1)
16387 "")))))))
16389 (defun org-entry-delete (pom property)
16390 "Delete the property PROPERTY from entry at point-or-marker POM."
16391 (org-with-point-at pom
16392 (if (member property org-special-properties)
16393 nil ; cannot delete these properties.
16394 (let ((range (org-get-property-block)))
16395 (if (and range
16396 (goto-char (car range))
16397 (re-search-forward
16398 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
16399 (cdr range) t))
16400 (progn
16401 (delete-region (match-beginning 0) (1+ (point-at-eol)))
16403 nil)))))
16405 ;; Multi-values properties are properties that contain multiple values
16406 ;; These values are assumed to be single words, separated by whitespace.
16407 (defun org-entry-add-to-multivalued-property (pom property value)
16408 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16409 (let* ((old (org-entry-get pom property))
16410 (values (and old (org-split-string old "[ \t]"))))
16411 (unless (member value values)
16412 (setq values (cons value values))
16413 (org-entry-put pom property
16414 (mapconcat 'identity values " ")))))
16416 (defun org-entry-remove-from-multivalued-property (pom property value)
16417 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16418 (let* ((old (org-entry-get pom property))
16419 (values (and old (org-split-string old "[ \t]"))))
16420 (when (member value values)
16421 (setq values (delete value values))
16422 (org-entry-put pom property
16423 (mapconcat 'identity values " ")))))
16425 (defun org-entry-member-in-multivalued-property (pom property value)
16426 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16427 (let* ((old (org-entry-get pom property))
16428 (values (and old (org-split-string old "[ \t]"))))
16429 (member value values)))
16431 (defvar org-entry-property-inherited-from (make-marker))
16433 (defun org-entry-get-with-inheritance (property)
16434 "Get entry property, and search higher levels if not present."
16435 (let (tmp)
16436 (save-excursion
16437 (save-restriction
16438 (widen)
16439 (catch 'ex
16440 (while t
16441 (when (setq tmp (org-entry-get nil property))
16442 (org-back-to-heading t)
16443 (move-marker org-entry-property-inherited-from (point))
16444 (throw 'ex tmp))
16445 (or (org-up-heading-safe) (throw 'ex nil)))))
16446 (or tmp (cdr (assoc property org-local-properties))
16447 (cdr (assoc property org-global-properties))))))
16449 (defun org-entry-put (pom property value)
16450 "Set PROPERTY to VALUE for entry at point-or-marker POM."
16451 (org-with-point-at pom
16452 (org-back-to-heading t)
16453 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
16454 range)
16455 (cond
16456 ((equal property "TODO")
16457 (when (and (stringp value) (string-match "\\S-" value)
16458 (not (member value org-todo-keywords-1)))
16459 (error "\"%s\" is not a valid TODO state" value))
16460 (if (or (not value)
16461 (not (string-match "\\S-" value)))
16462 (setq value 'none))
16463 (org-todo value)
16464 (org-set-tags nil 'align))
16465 ((equal property "PRIORITY")
16466 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
16467 (string-to-char value) ?\ ))
16468 (org-set-tags nil 'align))
16469 ((equal property "SCHEDULED")
16470 (if (re-search-forward org-scheduled-time-regexp end t)
16471 (cond
16472 ((eq value 'earlier) (org-timestamp-change -1 'day))
16473 ((eq value 'later) (org-timestamp-change 1 'day))
16474 (t (call-interactively 'org-schedule)))
16475 (call-interactively 'org-schedule)))
16476 ((equal property "DEADLINE")
16477 (if (re-search-forward org-deadline-time-regexp end t)
16478 (cond
16479 ((eq value 'earlier) (org-timestamp-change -1 'day))
16480 ((eq value 'later) (org-timestamp-change 1 'day))
16481 (t (call-interactively 'org-deadline)))
16482 (call-interactively 'org-deadline)))
16483 ((member property org-special-properties)
16484 (error "The %s property can not yet be set with `org-entry-put'"
16485 property))
16486 (t ; a non-special property
16487 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
16488 (setq range (org-get-property-block beg end 'force))
16489 (goto-char (car range))
16490 (if (re-search-forward
16491 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
16492 (progn
16493 (delete-region (match-beginning 1) (match-end 1))
16494 (goto-char (match-beginning 1)))
16495 (goto-char (cdr range))
16496 (insert "\n")
16497 (backward-char 1)
16498 (org-indent-line-function)
16499 (insert ":" property ":"))
16500 (and value (insert " " value))
16501 (org-indent-line-function)))))))
16503 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
16504 "Get all property keys in the current buffer.
16505 With INCLUDE-SPECIALS, also list the special properties that relect things
16506 like tags and TODO state.
16507 With INCLUDE-DEFAULTS, also include properties that has special meaning
16508 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
16509 With INCLUDE-COLUMNS, also include property names given in COLUMN
16510 formats in the current buffer."
16511 (let (rtn range cfmt cols s p)
16512 (save-excursion
16513 (save-restriction
16514 (widen)
16515 (goto-char (point-min))
16516 (while (re-search-forward org-property-start-re nil t)
16517 (setq range (org-get-property-block))
16518 (goto-char (car range))
16519 (while (re-search-forward
16520 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
16521 (cdr range) t)
16522 (add-to-list 'rtn (org-match-string-no-properties 1)))
16523 (outline-next-heading))))
16525 (when include-specials
16526 (setq rtn (append org-special-properties rtn)))
16528 (when include-defaults
16529 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
16531 (when include-columns
16532 (save-excursion
16533 (save-restriction
16534 (widen)
16535 (goto-char (point-min))
16536 (while (re-search-forward
16537 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
16538 nil t)
16539 (setq cfmt (match-string 2) s 0)
16540 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
16541 cfmt s)
16542 (setq s (match-end 0)
16543 p (match-string 1 cfmt))
16544 (unless (or (equal p "ITEM")
16545 (member p org-special-properties))
16546 (add-to-list 'rtn (match-string 1 cfmt))))))))
16548 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
16550 (defun org-property-values (key)
16551 "Return a list of all values of property KEY."
16552 (save-excursion
16553 (save-restriction
16554 (widen)
16555 (goto-char (point-min))
16556 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
16557 values)
16558 (while (re-search-forward re nil t)
16559 (add-to-list 'values (org-trim (match-string 1))))
16560 (delete "" values)))))
16562 (defun org-insert-property-drawer ()
16563 "Insert a property drawer into the current entry."
16564 (interactive)
16565 (org-back-to-heading t)
16566 (looking-at outline-regexp)
16567 (let ((indent (- (match-end 0)(match-beginning 0)))
16568 (beg (point))
16569 (re (concat "^[ \t]*" org-keyword-time-regexp))
16570 end hiddenp)
16571 (outline-next-heading)
16572 (setq end (point))
16573 (goto-char beg)
16574 (while (re-search-forward re end t))
16575 (setq hiddenp (org-invisible-p))
16576 (end-of-line 1)
16577 (and (equal (char-after) ?\n) (forward-char 1))
16578 (org-skip-over-state-notes)
16579 (skip-chars-backward " \t\n\r")
16580 (if (eq (char-before) ?*) (forward-char 1))
16581 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
16582 (beginning-of-line 0)
16583 (indent-to-column indent)
16584 (beginning-of-line 2)
16585 (indent-to-column indent)
16586 (beginning-of-line 0)
16587 (if hiddenp
16588 (save-excursion
16589 (org-back-to-heading t)
16590 (hide-entry))
16591 (org-flag-drawer t))))
16593 (defun org-set-property (property value)
16594 "In the current entry, set PROPERTY to VALUE.
16595 When called interactively, this will prompt for a property name, offering
16596 completion on existing and default properties. And then it will prompt
16597 for a value, offering competion either on allowed values (via an inherited
16598 xxx_ALL property) or on existing values in other instances of this property
16599 in the current file."
16600 (interactive
16601 (let* ((prop (completing-read
16602 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
16603 (cur (org-entry-get nil prop))
16604 (allowed (org-property-get-allowed-values nil prop 'table))
16605 (existing (mapcar 'list (org-property-values prop)))
16606 (val (if allowed
16607 (completing-read "Value: " allowed nil 'req-match)
16608 (completing-read
16609 (concat "Value" (if (and cur (string-match "\\S-" cur))
16610 (concat "[" cur "]") "")
16611 ": ")
16612 existing nil nil "" nil cur))))
16613 (list prop (if (equal val "") cur val))))
16614 (unless (equal (org-entry-get nil property) value)
16615 (org-entry-put nil property value)))
16617 (defun org-delete-property (property)
16618 "In the current entry, delete PROPERTY."
16619 (interactive
16620 (let* ((prop (completing-read
16621 "Property: " (org-entry-properties nil 'standard))))
16622 (list prop)))
16623 (message "Property %s %s" property
16624 (if (org-entry-delete nil property)
16625 "deleted"
16626 "was not present in the entry")))
16628 (defun org-delete-property-globally (property)
16629 "Remove PROPERTY globally, from all entries."
16630 (interactive
16631 (let* ((prop (completing-read
16632 "Globally remove property: "
16633 (mapcar 'list (org-buffer-property-keys)))))
16634 (list prop)))
16635 (save-excursion
16636 (save-restriction
16637 (widen)
16638 (goto-char (point-min))
16639 (let ((cnt 0))
16640 (while (re-search-forward
16641 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
16642 nil t)
16643 (setq cnt (1+ cnt))
16644 (replace-match ""))
16645 (message "Property \"%s\" removed from %d entries" property cnt)))))
16647 (defvar org-columns-current-fmt-compiled) ; defined below
16649 (defun org-compute-property-at-point ()
16650 "Compute the property at point.
16651 This looks for an enclosing column format, extracts the operator and
16652 then applies it to the proerty in the column format's scope."
16653 (interactive)
16654 (unless (org-at-property-p)
16655 (error "Not at a property"))
16656 (let ((prop (org-match-string-no-properties 2)))
16657 (org-columns-get-format-and-top-level)
16658 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
16659 (error "No operator defined for property %s" prop))
16660 (org-columns-compute prop)))
16662 (defun org-property-get-allowed-values (pom property &optional table)
16663 "Get allowed values for the property PROPERTY.
16664 When TABLE is non-nil, return an alist that can directly be used for
16665 completion."
16666 (let (vals)
16667 (cond
16668 ((equal property "TODO")
16669 (setq vals (org-with-point-at pom
16670 (append org-todo-keywords-1 '("")))))
16671 ((equal property "PRIORITY")
16672 (let ((n org-lowest-priority))
16673 (while (>= n org-highest-priority)
16674 (push (char-to-string n) vals)
16675 (setq n (1- n)))))
16676 ((member property org-special-properties))
16678 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16680 (when (and vals (string-match "\\S-" vals))
16681 (setq vals (car (read-from-string (concat "(" vals ")"))))
16682 (setq vals (mapcar (lambda (x)
16683 (cond ((stringp x) x)
16684 ((numberp x) (number-to-string x))
16685 ((symbolp x) (symbol-name x))
16686 (t "???")))
16687 vals)))))
16688 (if table (mapcar 'list vals) vals)))
16690 (defun org-property-previous-allowed-value (&optional previous)
16691 "Switch to the next allowed value for this property."
16692 (interactive)
16693 (org-property-next-allowed-value t))
16695 (defun org-property-next-allowed-value (&optional previous)
16696 "Switch to the next allowed value for this property."
16697 (interactive)
16698 (unless (org-at-property-p)
16699 (error "Not at a property"))
16700 (let* ((key (match-string 2))
16701 (value (match-string 3))
16702 (allowed (or (org-property-get-allowed-values (point) key)
16703 (and (member value '("[ ]" "[-]" "[X]"))
16704 '("[ ]" "[X]"))))
16705 nval)
16706 (unless allowed
16707 (error "Allowed values for this property have not been defined"))
16708 (if previous (setq allowed (reverse allowed)))
16709 (if (member value allowed)
16710 (setq nval (car (cdr (member value allowed)))))
16711 (setq nval (or nval (car allowed)))
16712 (if (equal nval value)
16713 (error "Only one allowed value for this property"))
16714 (org-at-property-p)
16715 (replace-match (concat " :" key ": " nval) t t)
16716 (org-indent-line-function)
16717 (beginning-of-line 1)
16718 (skip-chars-forward " \t")))
16720 (defun org-find-entry-with-id (ident)
16721 "Locate the entry that contains the ID property with exact value IDENT.
16722 IDENT can be a string, a symbol or a number, this function will search for
16723 the string representation of it.
16724 Return the position where this entry starts, or nil if there is no such entry."
16725 (let ((id (cond
16726 ((stringp ident) ident)
16727 ((symbol-name ident) (symbol-name ident))
16728 ((numberp ident) (number-to-string ident))
16729 (t (error "IDENT %s must be a string, symbol or number" ident))))
16730 (case-fold-search nil))
16731 (save-excursion
16732 (save-restriction
16733 (widen)
16734 (goto-char (point-min))
16735 (when (re-search-forward
16736 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
16737 nil t)
16738 (org-back-to-heading)
16739 (point))))))
16741 ;;; Column View
16743 (defvar org-columns-overlays nil
16744 "Holds the list of current column overlays.")
16746 (defvar org-columns-current-fmt nil
16747 "Local variable, holds the currently active column format.")
16748 (defvar org-columns-current-fmt-compiled nil
16749 "Local variable, holds the currently active column format.
16750 This is the compiled version of the format.")
16751 (defvar org-columns-current-widths nil
16752 "Loval variable, holds the currently widths of fields.")
16753 (defvar org-columns-current-maxwidths nil
16754 "Loval variable, holds the currently active maximum column widths.")
16755 (defvar org-columns-begin-marker (make-marker)
16756 "Points to the position where last a column creation command was called.")
16757 (defvar org-columns-top-level-marker (make-marker)
16758 "Points to the position where current columns region starts.")
16760 (defvar org-columns-map (make-sparse-keymap)
16761 "The keymap valid in column display.")
16763 (defun org-columns-content ()
16764 "Switch to contents view while in columns view."
16765 (interactive)
16766 (org-overview)
16767 (org-content))
16769 (org-defkey org-columns-map "c" 'org-columns-content)
16770 (org-defkey org-columns-map "o" 'org-overview)
16771 (org-defkey org-columns-map "e" 'org-columns-edit-value)
16772 (org-defkey org-columns-map "\C-c\C-t" 'org-columns-todo)
16773 (org-defkey org-columns-map "\C-c\C-c" 'org-columns-set-tags-or-toggle)
16774 (org-defkey org-columns-map "\C-c\C-o" 'org-columns-open-link)
16775 (org-defkey org-columns-map "v" 'org-columns-show-value)
16776 (org-defkey org-columns-map "q" 'org-columns-quit)
16777 (org-defkey org-columns-map "r" 'org-columns-redo)
16778 (org-defkey org-columns-map "g" 'org-columns-redo)
16779 (org-defkey org-columns-map [left] 'backward-char)
16780 (org-defkey org-columns-map "\M-b" 'backward-char)
16781 (org-defkey org-columns-map "a" 'org-columns-edit-allowed)
16782 (org-defkey org-columns-map "s" 'org-columns-edit-attributes)
16783 (org-defkey org-columns-map "\M-f" (lambda () (interactive) (goto-char (1+ (point)))))
16784 (org-defkey org-columns-map [right] (lambda () (interactive) (goto-char (1+ (point)))))
16785 (org-defkey org-columns-map [(shift right)] 'org-columns-next-allowed-value)
16786 (org-defkey org-columns-map "n" 'org-columns-next-allowed-value)
16787 (org-defkey org-columns-map [(shift left)] 'org-columns-previous-allowed-value)
16788 (org-defkey org-columns-map "p" 'org-columns-previous-allowed-value)
16789 (org-defkey org-columns-map "<" 'org-columns-narrow)
16790 (org-defkey org-columns-map ">" 'org-columns-widen)
16791 (org-defkey org-columns-map [(meta right)] 'org-columns-move-right)
16792 (org-defkey org-columns-map [(meta left)] 'org-columns-move-left)
16793 (org-defkey org-columns-map [(shift meta right)] 'org-columns-new)
16794 (org-defkey org-columns-map [(shift meta left)] 'org-columns-delete)
16796 (easy-menu-define org-columns-menu org-columns-map "Org Column Menu"
16797 '("Column"
16798 ["Edit property" org-columns-edit-value t]
16799 ["Next allowed value" org-columns-next-allowed-value t]
16800 ["Previous allowed value" org-columns-previous-allowed-value t]
16801 ["Show full value" org-columns-show-value t]
16802 ["Edit allowed values" org-columns-edit-allowed t]
16803 "--"
16804 ["Edit column attributes" org-columns-edit-attributes t]
16805 ["Increase column width" org-columns-widen t]
16806 ["Decrease column width" org-columns-narrow t]
16807 "--"
16808 ["Move column right" org-columns-move-right t]
16809 ["Move column left" org-columns-move-left t]
16810 ["Add column" org-columns-new t]
16811 ["Delete column" org-columns-delete t]
16812 "--"
16813 ["CONTENTS" org-columns-content t]
16814 ["OVERVIEW" org-overview t]
16815 ["Refresh columns display" org-columns-redo t]
16816 "--"
16817 ["Open link" org-columns-open-link t]
16818 "--"
16819 ["Quit" org-columns-quit t]))
16821 (defun org-columns-new-overlay (beg end &optional string face)
16822 "Create a new column overlay and add it to the list."
16823 (let ((ov (org-make-overlay beg end)))
16824 (org-overlay-put ov 'face (or face 'secondary-selection))
16825 (org-overlay-display ov string face)
16826 (push ov org-columns-overlays)
16827 ov))
16829 (defun org-columns-display-here (&optional props)
16830 "Overlay the current line with column display."
16831 (interactive)
16832 (let* ((fmt org-columns-current-fmt-compiled)
16833 (beg (point-at-bol))
16834 (level-face (save-excursion
16835 (beginning-of-line 1)
16836 (and (looking-at "\\(\\**\\)\\(\\* \\)")
16837 (org-get-level-face 2))))
16838 (color (list :foreground
16839 (face-attribute (or level-face 'default) :foreground)))
16840 props pom property ass width f string ov column val modval)
16841 ;; Check if the entry is in another buffer.
16842 (unless props
16843 (if (eq major-mode 'org-agenda-mode)
16844 (setq pom (or (get-text-property (point) 'org-hd-marker)
16845 (get-text-property (point) 'org-marker))
16846 props (if pom (org-entry-properties pom) nil))
16847 (setq props (org-entry-properties nil))))
16848 ;; Walk the format
16849 (while (setq column (pop fmt))
16850 (setq property (car column)
16851 ass (if (equal property "ITEM")
16852 (cons "ITEM"
16853 (save-match-data
16854 (org-no-properties
16855 (org-remove-tabs
16856 (buffer-substring-no-properties
16857 (point-at-bol) (point-at-eol))))))
16858 (assoc property props))
16859 width (or (cdr (assoc property org-columns-current-maxwidths))
16860 (nth 2 column)
16861 (length property))
16862 f (format "%%-%d.%ds | " width width)
16863 val (or (cdr ass) "")
16864 modval (if (equal property "ITEM")
16865 (org-columns-cleanup-item val org-columns-current-fmt-compiled))
16866 string (format f (or modval val)))
16867 ;; Create the overlay
16868 (org-unmodified
16869 (setq ov (org-columns-new-overlay
16870 beg (setq beg (1+ beg)) string
16871 (list color 'org-column)))
16872 ;;; (list (get-text-property (point-at-bol) 'face) 'org-column)))
16873 (org-overlay-put ov 'keymap org-columns-map)
16874 (org-overlay-put ov 'org-columns-key property)
16875 (org-overlay-put ov 'org-columns-value (cdr ass))
16876 (org-overlay-put ov 'org-columns-value-modified modval)
16877 (org-overlay-put ov 'org-columns-pom pom)
16878 (org-overlay-put ov 'org-columns-format f))
16879 (if (or (not (char-after beg))
16880 (equal (char-after beg) ?\n))
16881 (let ((inhibit-read-only t))
16882 (save-excursion
16883 (goto-char beg)
16884 (org-unmodified (insert " ")))))) ;; FIXME: add props and remove later?
16885 ;; Make the rest of the line disappear.
16886 (org-unmodified
16887 (setq ov (org-columns-new-overlay beg (point-at-eol)))
16888 (org-overlay-put ov 'invisible t)
16889 (org-overlay-put ov 'keymap org-columns-map)
16890 (org-overlay-put ov 'intangible t)
16891 (push ov org-columns-overlays)
16892 (setq ov (org-make-overlay (1- (point-at-eol)) (1+ (point-at-eol))))
16893 (org-overlay-put ov 'keymap org-columns-map)
16894 (push ov org-columns-overlays)
16895 (let ((inhibit-read-only t))
16896 (put-text-property (max (point-min) (1- (point-at-bol)))
16897 (min (point-max) (1+ (point-at-eol)))
16898 'read-only "Type `e' to edit property")))))
16900 (defvar org-previous-header-line-format nil
16901 "The header line format before column view was turned on.")
16902 (defvar org-columns-inhibit-recalculation nil
16903 "Inhibit recomputing of columns on column view startup.")
16906 (defvar header-line-format)
16907 (defun org-columns-display-here-title ()
16908 "Overlay the newline before the current line with the table title."
16909 (interactive)
16910 (let ((fmt org-columns-current-fmt-compiled)
16911 string (title "")
16912 property width f column str widths)
16913 (while (setq column (pop fmt))
16914 (setq property (car column)
16915 str (or (nth 1 column) property)
16916 width (or (cdr (assoc property org-columns-current-maxwidths))
16917 (nth 2 column)
16918 (length str))
16919 widths (push width widths)
16920 f (format "%%-%d.%ds | " width width)
16921 string (format f str)
16922 title (concat title string)))
16923 (setq title (concat
16924 (org-add-props " " nil 'display '(space :align-to 0))
16925 (org-add-props title nil 'face '(:weight bold :underline t))))
16926 (org-set-local 'org-previous-header-line-format header-line-format)
16927 (org-set-local 'org-columns-current-widths (nreverse widths))
16928 (setq header-line-format title)))
16930 (defun org-columns-remove-overlays ()
16931 "Remove all currently active column overlays."
16932 (interactive)
16933 (when (marker-buffer org-columns-begin-marker)
16934 (with-current-buffer (marker-buffer org-columns-begin-marker)
16935 (when (local-variable-p 'org-previous-header-line-format)
16936 (setq header-line-format org-previous-header-line-format)
16937 (kill-local-variable 'org-previous-header-line-format))
16938 (move-marker org-columns-begin-marker nil)
16939 (move-marker org-columns-top-level-marker nil)
16940 (org-unmodified
16941 (mapc 'org-delete-overlay org-columns-overlays)
16942 (setq org-columns-overlays nil)
16943 (let ((inhibit-read-only t))
16944 (remove-text-properties (point-min) (point-max) '(read-only t)))))))
16946 (defun org-columns-cleanup-item (item fmt)
16947 "Remove from ITEM what is a column in the format FMT."
16948 (if (not org-complex-heading-regexp)
16949 item
16950 (when (string-match org-complex-heading-regexp item)
16951 (concat
16952 (org-add-props (concat (match-string 1 item) " ") nil
16953 'org-whitespace (* 2 (1- (org-reduced-level (- (match-end 1) (match-beginning 1))))))
16954 (and (match-end 2) (not (assoc "TODO" fmt)) (concat " " (match-string 2 item)))
16955 (and (match-end 3) (not (assoc "PRIORITY" fmt)) (concat " " (match-string 3 item)))
16956 " " (match-string 4 item)
16957 (and (match-end 5) (not (assoc "TAGS" fmt)) (concat " " (match-string 5 item)))))))
16959 (defun org-columns-show-value ()
16960 "Show the full value of the property."
16961 (interactive)
16962 (let ((value (get-char-property (point) 'org-columns-value)))
16963 (message "Value is: %s" (or value ""))))
16965 (defun org-columns-quit ()
16966 "Remove the column overlays and in this way exit column editing."
16967 (interactive)
16968 (org-unmodified
16969 (org-columns-remove-overlays)
16970 (let ((inhibit-read-only t))
16971 (remove-text-properties (point-min) (point-max) '(read-only t))))
16972 (when (eq major-mode 'org-agenda-mode)
16973 (message
16974 "Modification not yet reflected in Agenda buffer, use `r' to refresh")))
16976 (defun org-columns-check-computed ()
16977 "Check if this column value is computed.
16978 If yes, throw an error indicating that changing it does not make sense."
16979 (let ((val (get-char-property (point) 'org-columns-value)))
16980 (when (and (stringp val)
16981 (get-char-property 0 'org-computed val))
16982 (error "This value is computed from the entry's children"))))
16984 (defun org-columns-todo (&optional arg)
16985 "Change the TODO state during column view."
16986 (interactive "P")
16987 (org-columns-edit-value "TODO"))
16989 (defun org-columns-set-tags-or-toggle (&optional arg)
16990 "Toggle checkbox at point, or set tags for current headline."
16991 (interactive "P")
16992 (if (string-match "\\`\\[[ xX-]\\]\\'"
16993 (get-char-property (point) 'org-columns-value))
16994 (org-columns-next-allowed-value)
16995 (org-columns-edit-value "TAGS")))
16997 (defun org-columns-edit-value (&optional key)
16998 "Edit the value of the property at point in column view.
16999 Where possible, use the standard interface for changing this line."
17000 (interactive)
17001 (org-columns-check-computed)
17002 (let* ((external-key key)
17003 (col (current-column))
17004 (key (or key (get-char-property (point) 'org-columns-key)))
17005 (value (get-char-property (point) 'org-columns-value))
17006 (bol (point-at-bol)) (eol (point-at-eol))
17007 (pom (or (get-text-property bol 'org-hd-marker)
17008 (point))) ; keep despite of compiler waring
17009 (line-overlays
17010 (delq nil (mapcar (lambda (x)
17011 (and (eq (overlay-buffer x) (current-buffer))
17012 (>= (overlay-start x) bol)
17013 (<= (overlay-start x) eol)
17015 org-columns-overlays)))
17016 nval eval allowed)
17017 (cond
17018 ((equal key "CLOCKSUM")
17019 (error "This special column cannot be edited"))
17020 ((equal key "ITEM")
17021 (setq eval '(org-with-point-at pom
17022 (org-edit-headline))))
17023 ((equal key "TODO")
17024 (setq eval '(org-with-point-at pom
17025 (let ((current-prefix-arg
17026 (if external-key current-prefix-arg '(4))))
17027 (call-interactively 'org-todo)))))
17028 ((equal key "PRIORITY")
17029 (setq eval '(org-with-point-at pom
17030 (call-interactively 'org-priority))))
17031 ((equal key "TAGS")
17032 (setq eval '(org-with-point-at pom
17033 (let ((org-fast-tag-selection-single-key
17034 (if (eq org-fast-tag-selection-single-key 'expert)
17035 t org-fast-tag-selection-single-key)))
17036 (call-interactively 'org-set-tags)))))
17037 ((equal key "DEADLINE")
17038 (setq eval '(org-with-point-at pom
17039 (call-interactively 'org-deadline))))
17040 ((equal key "SCHEDULED")
17041 (setq eval '(org-with-point-at pom
17042 (call-interactively 'org-schedule))))
17044 (setq allowed (org-property-get-allowed-values pom key 'table))
17045 (if allowed
17046 (setq nval (completing-read "Value: " allowed nil t))
17047 (setq nval (read-string "Edit: " value)))
17048 (setq nval (org-trim nval))
17049 (when (not (equal nval value))
17050 (setq eval '(org-entry-put pom key nval)))))
17051 (when eval
17052 (let ((inhibit-read-only t))
17053 (remove-text-properties (max (point-min) (1- bol)) eol '(read-only t))
17054 (unwind-protect
17055 (progn
17056 (setq org-columns-overlays
17057 (org-delete-all line-overlays org-columns-overlays))
17058 (mapc 'org-delete-overlay line-overlays)
17059 (org-columns-eval eval))
17060 (org-columns-display-here))))
17061 (move-to-column col)
17062 (if (and (org-mode-p)
17063 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17064 (org-columns-update key))))
17066 (defun org-edit-headline () ; FIXME: this is not columns specific
17067 "Edit the current headline, the part without TODO keyword, TAGS."
17068 (org-back-to-heading)
17069 (when (looking-at org-todo-line-regexp)
17070 (let ((pre (buffer-substring (match-beginning 0) (match-beginning 3)))
17071 (txt (match-string 3))
17072 (post "")
17073 txt2)
17074 (if (string-match (org-re "[ \t]+:[[:alnum:]:_@]+:[ \t]*$") txt)
17075 (setq post (match-string 0 txt)
17076 txt (substring txt 0 (match-beginning 0))))
17077 (setq txt2 (read-string "Edit: " txt))
17078 (when (not (equal txt txt2))
17079 (beginning-of-line 1)
17080 (insert pre txt2 post)
17081 (delete-region (point) (point-at-eol))
17082 (org-set-tags nil t)))))
17084 (defun org-columns-edit-allowed ()
17085 "Edit the list of allowed values for the current property."
17086 (interactive)
17087 (let* ((key (get-char-property (point) 'org-columns-key))
17088 (key1 (concat key "_ALL"))
17089 (allowed (org-entry-get (point) key1 t))
17090 nval)
17091 ;; FIXME: Cover editing TODO, TAGS etc in-buffer settings.????
17092 (setq nval (read-string "Allowed: " allowed))
17093 (org-entry-put
17094 (cond ((marker-position org-entry-property-inherited-from)
17095 org-entry-property-inherited-from)
17096 ((marker-position org-columns-top-level-marker)
17097 org-columns-top-level-marker))
17098 key1 nval)))
17100 (defmacro org-no-warnings (&rest body)
17101 (cons (if (fboundp 'with-no-warnings) 'with-no-warnings 'progn) body))
17103 (defun org-columns-eval (form)
17104 (let (hidep)
17105 (save-excursion
17106 (beginning-of-line 1)
17107 ;; `next-line' is needed here, because it skips invisible line.
17108 (condition-case nil (org-no-warnings (next-line 1)) (error nil))
17109 (setq hidep (org-on-heading-p 1)))
17110 (eval form)
17111 (and hidep (hide-entry))))
17113 (defun org-columns-previous-allowed-value ()
17114 "Switch to the previous allowed value for this column."
17115 (interactive)
17116 (org-columns-next-allowed-value t))
17118 (defun org-columns-next-allowed-value (&optional previous)
17119 "Switch to the next allowed value for this column."
17120 (interactive)
17121 (org-columns-check-computed)
17122 (let* ((col (current-column))
17123 (key (get-char-property (point) 'org-columns-key))
17124 (value (get-char-property (point) 'org-columns-value))
17125 (bol (point-at-bol)) (eol (point-at-eol))
17126 (pom (or (get-text-property bol 'org-hd-marker)
17127 (point))) ; keep despite of compiler waring
17128 (line-overlays
17129 (delq nil (mapcar (lambda (x)
17130 (and (eq (overlay-buffer x) (current-buffer))
17131 (>= (overlay-start x) bol)
17132 (<= (overlay-start x) eol)
17134 org-columns-overlays)))
17135 (allowed (or (org-property-get-allowed-values pom key)
17136 (and (memq
17137 (nth 4 (assoc key org-columns-current-fmt-compiled))
17138 '(checkbox checkbox-n-of-m checkbox-percent))
17139 '("[ ]" "[X]"))))
17140 nval)
17141 (when (equal key "ITEM")
17142 (error "Cannot edit item headline from here"))
17143 (unless (or allowed (member key '("SCHEDULED" "DEADLINE")))
17144 (error "Allowed values for this property have not been defined"))
17145 (if (member key '("SCHEDULED" "DEADLINE"))
17146 (setq nval (if previous 'earlier 'later))
17147 (if previous (setq allowed (reverse allowed)))
17148 (if (member value allowed)
17149 (setq nval (car (cdr (member value allowed)))))
17150 (setq nval (or nval (car allowed)))
17151 (if (equal nval value)
17152 (error "Only one allowed value for this property")))
17153 (let ((inhibit-read-only t))
17154 (remove-text-properties (1- bol) eol '(read-only t))
17155 (unwind-protect
17156 (progn
17157 (setq org-columns-overlays
17158 (org-delete-all line-overlays org-columns-overlays))
17159 (mapc 'org-delete-overlay line-overlays)
17160 (org-columns-eval '(org-entry-put pom key nval)))
17161 (org-columns-display-here)))
17162 (move-to-column col)
17163 (if (and (org-mode-p)
17164 (nth 3 (assoc key org-columns-current-fmt-compiled)))
17165 (org-columns-update key))))
17167 (defun org-verify-version (task)
17168 (cond
17169 ((eq task 'columns)
17170 (if (or (featurep 'xemacs)
17171 (< emacs-major-version 22))
17172 (error "Emacs 22 is required for the columns feature")))))
17174 (defun org-columns-open-link (&optional arg)
17175 (interactive "P")
17176 (let ((value (get-char-property (point) 'org-columns-value)))
17177 (org-open-link-from-string value arg)))
17179 (defun org-open-link-from-string (s &optional arg)
17180 "Open a link in the string S, as if it was in Org-mode."
17181 (interactive)
17182 (with-temp-buffer
17183 (let ((org-inhibit-startup t))
17184 (org-mode)
17185 (insert s)
17186 (goto-char (point-min))
17187 (org-open-at-point arg))))
17189 (defun org-columns-get-format-and-top-level ()
17190 (let (fmt)
17191 (when (condition-case nil (org-back-to-heading) (error nil))
17192 (move-marker org-entry-property-inherited-from nil)
17193 (setq fmt (org-entry-get nil "COLUMNS" t)))
17194 (setq fmt (or fmt org-columns-default-format))
17195 (org-set-local 'org-columns-current-fmt fmt)
17196 (org-columns-compile-format fmt)
17197 (if (marker-position org-entry-property-inherited-from)
17198 (move-marker org-columns-top-level-marker
17199 org-entry-property-inherited-from)
17200 (move-marker org-columns-top-level-marker (point)))
17201 fmt))
17203 (defun org-columns ()
17204 "Turn on column view on an org-mode file."
17205 (interactive)
17206 (org-verify-version 'columns)
17207 (org-columns-remove-overlays)
17208 (move-marker org-columns-begin-marker (point))
17209 (let (beg end fmt cache maxwidths)
17210 (setq fmt (org-columns-get-format-and-top-level))
17211 (save-excursion
17212 (goto-char org-columns-top-level-marker)
17213 (setq beg (point))
17214 (unless org-columns-inhibit-recalculation
17215 (org-columns-compute-all))
17216 (setq end (or (condition-case nil (org-end-of-subtree t t) (error nil))
17217 (point-max)))
17218 ;; Get and cache the properties
17219 (goto-char beg)
17220 (when (assoc "CLOCKSUM" org-columns-current-fmt-compiled)
17221 (save-excursion
17222 (save-restriction
17223 (narrow-to-region beg end)
17224 (org-clock-sum))))
17225 (while (re-search-forward (concat "^" outline-regexp) end t)
17226 (push (cons (org-current-line) (org-entry-properties)) cache))
17227 (when cache
17228 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17229 (org-set-local 'org-columns-current-maxwidths maxwidths)
17230 (org-columns-display-here-title)
17231 (mapc (lambda (x)
17232 (goto-line (car x))
17233 (org-columns-display-here (cdr x)))
17234 cache)))))
17236 (defun org-columns-new (&optional prop title width op fmt &rest rest)
17237 "Insert a new column, to the leeft o the current column."
17238 (interactive)
17239 (let ((editp (and prop (assoc prop org-columns-current-fmt-compiled)))
17240 cell)
17241 (setq prop (completing-read
17242 "Property: " (mapcar 'list (org-buffer-property-keys t nil t))
17243 nil nil prop))
17244 (setq title (read-string (concat "Column title [" prop "]: ") (or title prop)))
17245 (setq width (read-string "Column width: " (if width (number-to-string width))))
17246 (if (string-match "\\S-" width)
17247 (setq width (string-to-number width))
17248 (setq width nil))
17249 (setq fmt (completing-read "Summary [none]: "
17250 '(("none") ("add_numbers") ("currency") ("add_times") ("checkbox") ("checkbox-n-of-m") ("checkbox-percent"))
17251 nil t))
17252 (if (string-match "\\S-" fmt)
17253 (setq fmt (intern fmt))
17254 (setq fmt nil))
17255 (if (eq fmt 'none) (setq fmt nil))
17256 (if editp
17257 (progn
17258 (setcar editp prop)
17259 (setcdr editp (list title width nil fmt)))
17260 (setq cell (nthcdr (1- (current-column))
17261 org-columns-current-fmt-compiled))
17262 (setcdr cell (cons (list prop title width nil fmt)
17263 (cdr cell))))
17264 (org-columns-store-format)
17265 (org-columns-redo)))
17267 (defun org-columns-delete ()
17268 "Delete the column at point from columns view."
17269 (interactive)
17270 (let* ((n (current-column))
17271 (title (nth 1 (nth n org-columns-current-fmt-compiled))))
17272 (when (y-or-n-p
17273 (format "Are you sure you want to remove column \"%s\"? " title))
17274 (setq org-columns-current-fmt-compiled
17275 (delq (nth n org-columns-current-fmt-compiled)
17276 org-columns-current-fmt-compiled))
17277 (org-columns-store-format)
17278 (org-columns-redo)
17279 (if (>= (current-column) (length org-columns-current-fmt-compiled))
17280 (backward-char 1)))))
17282 (defun org-columns-edit-attributes ()
17283 "Edit the attributes of the current column."
17284 (interactive)
17285 (let* ((n (current-column))
17286 (info (nth n org-columns-current-fmt-compiled)))
17287 (apply 'org-columns-new info)))
17289 (defun org-columns-widen (arg)
17290 "Make the column wider by ARG characters."
17291 (interactive "p")
17292 (let* ((n (current-column))
17293 (entry (nth n org-columns-current-fmt-compiled))
17294 (width (or (nth 2 entry)
17295 (cdr (assoc (car entry) org-columns-current-maxwidths)))))
17296 (setq width (max 1 (+ width arg)))
17297 (setcar (nthcdr 2 entry) width)
17298 (org-columns-store-format)
17299 (org-columns-redo)))
17301 (defun org-columns-narrow (arg)
17302 "Make the column nrrower by ARG characters."
17303 (interactive "p")
17304 (org-columns-widen (- arg)))
17306 (defun org-columns-move-right ()
17307 "Swap this column with the one to the right."
17308 (interactive)
17309 (let* ((n (current-column))
17310 (cell (nthcdr n org-columns-current-fmt-compiled))
17312 (when (>= n (1- (length org-columns-current-fmt-compiled)))
17313 (error "Cannot shift this column further to the right"))
17314 (setq e (car cell))
17315 (setcar cell (car (cdr cell)))
17316 (setcdr cell (cons e (cdr (cdr cell))))
17317 (org-columns-store-format)
17318 (org-columns-redo)
17319 (forward-char 1)))
17321 (defun org-columns-move-left ()
17322 "Swap this column with the one to the left."
17323 (interactive)
17324 (let* ((n (current-column)))
17325 (when (= n 0)
17326 (error "Cannot shift this column further to the left"))
17327 (backward-char 1)
17328 (org-columns-move-right)
17329 (backward-char 1)))
17331 (defun org-columns-store-format ()
17332 "Store the text version of the current columns format in appropriate place.
17333 This is either in the COLUMNS property of the node starting the current column
17334 display, or in the #+COLUMNS line of the current buffer."
17335 (let (fmt (cnt 0))
17336 (setq fmt (org-columns-uncompile-format org-columns-current-fmt-compiled))
17337 (org-set-local 'org-columns-current-fmt fmt)
17338 (if (marker-position org-columns-top-level-marker)
17339 (save-excursion
17340 (goto-char org-columns-top-level-marker)
17341 (if (and (org-at-heading-p)
17342 (org-entry-get nil "COLUMNS"))
17343 (org-entry-put nil "COLUMNS" fmt)
17344 (goto-char (point-min))
17345 ;; Overwrite all #+COLUMNS lines....
17346 (while (re-search-forward "^#\\+COLUMNS:.*" nil t)
17347 (setq cnt (1+ cnt))
17348 (replace-match (concat "#+COLUMNS: " fmt) t t))
17349 (unless (> cnt 0)
17350 (goto-char (point-min))
17351 (or (org-on-heading-p t) (outline-next-heading))
17352 (let ((inhibit-read-only t))
17353 (insert-before-markers "#+COLUMNS: " fmt "\n")))
17354 (org-set-local 'org-columns-default-format fmt))))))
17356 (defvar org-overriding-columns-format nil
17357 "When set, overrides any other definition.")
17358 (defvar org-agenda-view-columns-initially nil
17359 "When set, switch to columns view immediately after creating the agenda.")
17361 (defun org-agenda-columns ()
17362 "Turn on column view in the agenda."
17363 (interactive)
17364 (org-verify-version 'columns)
17365 (org-columns-remove-overlays)
17366 (move-marker org-columns-begin-marker (point))
17367 (let (fmt cache maxwidths m)
17368 (cond
17369 ((and (local-variable-p 'org-overriding-columns-format)
17370 org-overriding-columns-format)
17371 (setq fmt org-overriding-columns-format))
17372 ((setq m (get-text-property (point-at-bol) 'org-hd-marker))
17373 (setq fmt (org-entry-get m "COLUMNS" t)))
17374 ((and (boundp 'org-columns-current-fmt)
17375 (local-variable-p 'org-columns-current-fmt)
17376 org-columns-current-fmt)
17377 (setq fmt org-columns-current-fmt))
17378 ((setq m (next-single-property-change (point-min) 'org-hd-marker))
17379 (setq m (get-text-property m 'org-hd-marker))
17380 (setq fmt (org-entry-get m "COLUMNS" t))))
17381 (setq fmt (or fmt org-columns-default-format))
17382 (org-set-local 'org-columns-current-fmt fmt)
17383 (org-columns-compile-format fmt)
17384 (save-excursion
17385 ;; Get and cache the properties
17386 (goto-char (point-min))
17387 (while (not (eobp))
17388 (when (setq m (or (get-text-property (point) 'org-hd-marker)
17389 (get-text-property (point) 'org-marker)))
17390 (push (cons (org-current-line) (org-entry-properties m)) cache))
17391 (beginning-of-line 2))
17392 (when cache
17393 (setq maxwidths (org-columns-get-autowidth-alist fmt cache))
17394 (org-set-local 'org-columns-current-maxwidths maxwidths)
17395 (org-columns-display-here-title)
17396 (mapc (lambda (x)
17397 (goto-line (car x))
17398 (org-columns-display-here (cdr x)))
17399 cache)))))
17401 (defun org-columns-get-autowidth-alist (s cache)
17402 "Derive the maximum column widths from the format and the cache."
17403 (let ((start 0) rtn)
17404 (while (string-match (org-re "%\\([[:alpha:]][[:alnum:]_-]*\\)") s start)
17405 (push (cons (match-string 1 s) 1) rtn)
17406 (setq start (match-end 0)))
17407 (mapc (lambda (x)
17408 (setcdr x (apply 'max
17409 (mapcar
17410 (lambda (y)
17411 (length (or (cdr (assoc (car x) (cdr y))) " ")))
17412 cache))))
17413 rtn)
17414 rtn))
17416 (defun org-columns-compute-all ()
17417 "Compute all columns that have operators defined."
17418 (org-unmodified
17419 (remove-text-properties (point-min) (point-max) '(org-summaries t)))
17420 (let ((columns org-columns-current-fmt-compiled) col)
17421 (while (setq col (pop columns))
17422 (when (nth 3 col)
17423 (save-excursion
17424 (org-columns-compute (car col)))))))
17426 (defun org-columns-update (property)
17427 "Recompute PROPERTY, and update the columns display for it."
17428 (org-columns-compute property)
17429 (let (fmt val pos)
17430 (save-excursion
17431 (mapc (lambda (ov)
17432 (when (equal (org-overlay-get ov 'org-columns-key) property)
17433 (setq pos (org-overlay-start ov))
17434 (goto-char pos)
17435 (when (setq val (cdr (assoc property
17436 (get-text-property
17437 (point-at-bol) 'org-summaries))))
17438 (setq fmt (org-overlay-get ov 'org-columns-format))
17439 (org-overlay-put ov 'org-columns-value val)
17440 (org-overlay-put ov 'display (format fmt val)))))
17441 org-columns-overlays))))
17443 (defun org-columns-compute (property)
17444 "Sum the values of property PROPERTY hierarchically, for the entire buffer."
17445 (interactive)
17446 (let* ((re (concat "^" outline-regexp))
17447 (lmax 30) ; Does anyone use deeper levels???
17448 (lsum (make-vector lmax 0))
17449 (lflag (make-vector lmax nil))
17450 (level 0)
17451 (ass (assoc property org-columns-current-fmt-compiled))
17452 (format (nth 4 ass))
17453 (printf (nth 5 ass))
17454 (beg org-columns-top-level-marker)
17455 last-level val valflag flag end sumpos sum-alist sum str str1 useval)
17456 (save-excursion
17457 ;; Find the region to compute
17458 (goto-char beg)
17459 (setq end (condition-case nil (org-end-of-subtree t) (error (point-max))))
17460 (goto-char end)
17461 ;; Walk the tree from the back and do the computations
17462 (while (re-search-backward re beg t)
17463 (setq sumpos (match-beginning 0)
17464 last-level level
17465 level (org-outline-level)
17466 val (org-entry-get nil property)
17467 valflag (and val (string-match "\\S-" val)))
17468 (cond
17469 ((< level last-level)
17470 ;; put the sum of lower levels here as a property
17471 (setq sum (aref lsum last-level) ; current sum
17472 flag (aref lflag last-level) ; any valid entries from children?
17473 str (org-column-number-to-string sum format printf)
17474 str1 (org-add-props (copy-sequence str) nil 'org-computed t 'face 'bold)
17475 useval (if flag str1 (if valflag val ""))
17476 sum-alist (get-text-property sumpos 'org-summaries))
17477 (if (assoc property sum-alist)
17478 (setcdr (assoc property sum-alist) useval)
17479 (push (cons property useval) sum-alist)
17480 (org-unmodified
17481 (add-text-properties sumpos (1+ sumpos)
17482 (list 'org-summaries sum-alist))))
17483 (when val
17484 (org-entry-put nil property (if flag str val)))
17485 ;; add current to current level accumulator
17486 (when (or flag valflag)
17487 (aset lsum level (+ (aref lsum level)
17488 (if flag sum (org-column-string-to-number
17489 (if flag str val) format))))
17490 (aset lflag level t))
17491 ;; clear accumulators for deeper levels
17492 (loop for l from (1+ level) to (1- lmax) do
17493 (aset lsum l 0)
17494 (aset lflag l nil)))
17495 ((>= level last-level)
17496 ;; add what we have here to the accumulator for this level
17497 (aset lsum level (+ (aref lsum level)
17498 (org-column-string-to-number (or val "0") format)))
17499 (and valflag (aset lflag level t)))
17500 (t (error "This should not happen")))))))
17502 (defun org-columns-redo ()
17503 "Construct the column display again."
17504 (interactive)
17505 (message "Recomputing columns...")
17506 (save-excursion
17507 (if (marker-position org-columns-begin-marker)
17508 (goto-char org-columns-begin-marker))
17509 (org-columns-remove-overlays)
17510 (if (org-mode-p)
17511 (call-interactively 'org-columns)
17512 (call-interactively 'org-agenda-columns)))
17513 (message "Recomputing columns...done"))
17515 (defun org-columns-not-in-agenda ()
17516 (if (eq major-mode 'org-agenda-mode)
17517 (error "This command is only allowed in Org-mode buffers")))
17520 (defun org-string-to-number (s)
17521 "Convert string to number, and interpret hh:mm:ss."
17522 (if (not (string-match ":" s))
17523 (string-to-number s)
17524 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17525 (while l
17526 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17527 sum)))
17529 (defun org-column-number-to-string (n fmt &optional printf)
17530 "Convert a computed column number to a string value, according to FMT."
17531 (cond
17532 ((eq fmt 'add_times)
17533 (let* ((h (floor n)) (m (floor (+ 0.5 (* 60 (- n h))))))
17534 (format "%d:%02d" h m)))
17535 ((eq fmt 'checkbox)
17536 (cond ((= n (floor n)) "[X]")
17537 ((> n 1.) "[-]")
17538 (t "[ ]")))
17539 ((memq fmt '(checkbox-n-of-m checkbox-percent))
17540 (let* ((n1 (floor n)) (n2 (floor (+ .5 (* 1000000 (- n n1))))))
17541 (org-nofm-to-completion n1 (+ n2 n1) (eq fmt 'checkbox-percent))))
17542 (printf (format printf n))
17543 ((eq fmt 'currency)
17544 (format "%.2f" n))
17545 (t (number-to-string n))))
17547 (defun org-nofm-to-completion (n m &optional percent)
17548 (if (not percent)
17549 (format "[%d/%d]" n m)
17550 (format "[%d%%]"(floor (+ 0.5 (* 100. (/ (* 1.0 n) m)))))))
17552 (defun org-column-string-to-number (s fmt)
17553 "Convert a column value to a number that can be used for column computing."
17554 (cond
17555 ((string-match ":" s)
17556 (let ((l (nreverse (org-split-string s ":"))) (sum 0.0))
17557 (while l
17558 (setq sum (+ (string-to-number (pop l)) (/ sum 60))))
17559 sum))
17560 ((memq fmt '(checkbox checkbox-n-of-m checkbox-percent))
17561 (if (equal s "[X]") 1. 0.000001))
17562 (t (string-to-number s))))
17564 (defun org-columns-uncompile-format (cfmt)
17565 "Turn the compiled columns format back into a string representation."
17566 (let ((rtn "") e s prop title op width fmt printf)
17567 (while (setq e (pop cfmt))
17568 (setq prop (car e)
17569 title (nth 1 e)
17570 width (nth 2 e)
17571 op (nth 3 e)
17572 fmt (nth 4 e)
17573 printf (nth 5 e))
17574 (cond
17575 ((eq fmt 'add_times) (setq op ":"))
17576 ((eq fmt 'checkbox) (setq op "X"))
17577 ((eq fmt 'checkbox-n-of-m) (setq op "X/"))
17578 ((eq fmt 'checkbox-percent) (setq op "X%"))
17579 ((eq fmt 'add_numbers) (setq op "+"))
17580 ((eq fmt 'currency) (setq op "$")))
17581 (if (and op printf) (setq op (concat op ";" printf)))
17582 (if (equal title prop) (setq title nil))
17583 (setq s (concat "%" (if width (number-to-string width))
17584 prop
17585 (if title (concat "(" title ")"))
17586 (if op (concat "{" op "}"))))
17587 (setq rtn (concat rtn " " s)))
17588 (org-trim rtn)))
17590 (defun org-columns-compile-format (fmt)
17591 "Turn a column format string into an alist of specifications.
17592 The alist has one entry for each column in the format. The elements of
17593 that list are:
17594 property the property
17595 title the title field for the columns
17596 width the column width in characters, can be nil for automatic
17597 operator the operator if any
17598 format the output format for computed results, derived from operator
17599 printf a printf format for computed values"
17600 (let ((start 0) width prop title op f printf)
17601 (setq org-columns-current-fmt-compiled nil)
17602 (while (string-match
17603 (org-re "%\\([0-9]+\\)?\\([[:alnum:]_-]+\\)\\(?:(\\([^)]+\\))\\)?\\(?:{\\([^}]+\\)}\\)?\\s-*")
17604 fmt start)
17605 (setq start (match-end 0)
17606 width (match-string 1 fmt)
17607 prop (match-string 2 fmt)
17608 title (or (match-string 3 fmt) prop)
17609 op (match-string 4 fmt)
17610 f nil
17611 printf nil)
17612 (if width (setq width (string-to-number width)))
17613 (when (and op (string-match ";" op))
17614 (setq printf (substring op (match-end 0))
17615 op (substring op 0 (match-beginning 0))))
17616 (cond
17617 ((equal op "+") (setq f 'add_numbers))
17618 ((equal op "$") (setq f 'currency))
17619 ((equal op ":") (setq f 'add_times))
17620 ((equal op "X") (setq f 'checkbox))
17621 ((equal op "X/") (setq f 'checkbox-n-of-m))
17622 ((equal op "X%") (setq f 'checkbox-percent))
17624 (push (list prop title width op f printf) org-columns-current-fmt-compiled))
17625 (setq org-columns-current-fmt-compiled
17626 (nreverse org-columns-current-fmt-compiled))))
17629 ;;; Dynamic block for Column view
17631 (defun org-columns-capture-view (&optional maxlevel skip-empty-rows)
17632 "Get the column view of the current buffer or subtree.
17633 The first optional argument MAXLEVEL sets the level limit. A
17634 second optional argument SKIP-EMPTY-ROWS tells whether to skip
17635 empty rows, an empty row being one where all the column view
17636 specifiers except ITEM are empty. This function returns a list
17637 containing the title row and all other rows. Each row is a list
17638 of fields."
17639 (save-excursion
17640 (let* ((title (mapcar 'cadr org-columns-current-fmt-compiled))
17641 (n (length title)) row tbl)
17642 (goto-char (point-min))
17643 (while (and (re-search-forward "^\\(\\*+\\) " nil t)
17644 (or (null maxlevel)
17645 (>= maxlevel
17646 (if org-odd-levels-only
17647 (/ (1+ (length (match-string 1))) 2)
17648 (length (match-string 1))))))
17649 (when (get-char-property (match-beginning 0) 'org-columns-key)
17650 (setq row nil)
17651 (loop for i from 0 to (1- n) do
17652 (push (or (get-char-property (+ (match-beginning 0) i) 'org-columns-value-modified)
17653 (get-char-property (+ (match-beginning 0) i) 'org-columns-value)
17655 row))
17656 (setq row (nreverse row))
17657 (unless (and skip-empty-rows
17658 (eq 1 (length (delete "" (delete-dups row)))))
17659 (push row tbl))))
17660 (append (list title 'hline) (nreverse tbl)))))
17662 (defun org-dblock-write:columnview (params)
17663 "Write the column view table.
17664 PARAMS is a property list of parameters:
17666 :width enforce same column widths with <N> specifiers.
17667 :id the :ID: property of the entry where the columns view
17668 should be built, as a string. When `local', call locally.
17669 When `global' call column view with the cursor at the beginning
17670 of the buffer (usually this means that the whole buffer switches
17671 to column view).
17672 :hlines When t, insert a hline before each item. When a number, insert
17673 a hline before each level <= that number.
17674 :vlines When t, make each column a colgroup to enforce vertical lines.
17675 :maxlevel When set to a number, don't capture headlines below this level.
17676 :skip-empty-rows
17677 When t, skip rows where all specifiers other than ITEM are empty."
17678 (let ((pos (move-marker (make-marker) (point)))
17679 (hlines (plist-get params :hlines))
17680 (vlines (plist-get params :vlines))
17681 (maxlevel (plist-get params :maxlevel))
17682 (skip-empty-rows (plist-get params :skip-empty-rows))
17683 tbl id idpos nfields tmp)
17684 (save-excursion
17685 (save-restriction
17686 (when (setq id (plist-get params :id))
17687 (cond ((not id) nil)
17688 ((eq id 'global) (goto-char (point-min)))
17689 ((eq id 'local) nil)
17690 ((setq idpos (org-find-entry-with-id id))
17691 (goto-char idpos))
17692 (t (error "Cannot find entry with :ID: %s" id))))
17693 (org-columns)
17694 (setq tbl (org-columns-capture-view maxlevel skip-empty-rows))
17695 (setq nfields (length (car tbl)))
17696 (org-columns-quit)))
17697 (goto-char pos)
17698 (move-marker pos nil)
17699 (when tbl
17700 (when (plist-get params :hlines)
17701 (setq tmp nil)
17702 (while tbl
17703 (if (eq (car tbl) 'hline)
17704 (push (pop tbl) tmp)
17705 (if (string-match "\\` *\\(\\*+\\)" (caar tbl))
17706 (if (and (not (eq (car tmp) 'hline))
17707 (or (eq hlines t)
17708 (and (numberp hlines) (<= (- (match-end 1) (match-beginning 1)) hlines))))
17709 (push 'hline tmp)))
17710 (push (pop tbl) tmp)))
17711 (setq tbl (nreverse tmp)))
17712 (when vlines
17713 (setq tbl (mapcar (lambda (x)
17714 (if (eq 'hline x) x (cons "" x)))
17715 tbl))
17716 (setq tbl (append tbl (list (cons "/" (make-list nfields "<>"))))))
17717 (setq pos (point))
17718 (insert (org-listtable-to-string tbl))
17719 (when (plist-get params :width)
17720 (insert "\n|" (mapconcat (lambda (x) (format "<%d>" (max 3 x)))
17721 org-columns-current-widths "|")))
17722 (goto-char pos)
17723 (org-table-align))))
17725 (defun org-listtable-to-string (tbl)
17726 "Convert a listtable TBL to a string that contains the Org-mode table.
17727 The table still need to be alligned. The resulting string has no leading
17728 and tailing newline characters."
17729 (mapconcat
17730 (lambda (x)
17731 (cond
17732 ((listp x)
17733 (concat "|" (mapconcat 'identity x "|") "|"))
17734 ((eq x 'hline) "|-|")
17735 (t (error "Garbage in listtable: %s" x))))
17736 tbl "\n"))
17738 (defun org-insert-columns-dblock ()
17739 "Create a dynamic block capturing a column view table."
17740 (interactive)
17741 (let ((defaults '(:name "columnview" :hlines 1))
17742 (id (completing-read
17743 "Capture columns (local, global, entry with :ID: property) [local]: "
17744 (append '(("global") ("local"))
17745 (mapcar 'list (org-property-values "ID"))))))
17746 (if (equal id "") (setq id 'local))
17747 (if (equal id "global") (setq id 'global))
17748 (setq defaults (append defaults (list :id id)))
17749 (org-create-dblock defaults)
17750 (org-update-dblock)))
17752 ;;;; Timestamps
17754 (defvar org-last-changed-timestamp nil)
17755 (defvar org-time-was-given) ; dynamically scoped parameter
17756 (defvar org-end-time-was-given) ; dynamically scoped parameter
17757 (defvar org-ts-what) ; dynamically scoped parameter
17759 (defun org-time-stamp (arg)
17760 "Prompt for a date/time and insert a time stamp.
17761 If the user specifies a time like HH:MM, or if this command is called
17762 with a prefix argument, the time stamp will contain date and time.
17763 Otherwise, only the date will be included. All parts of a date not
17764 specified by the user will be filled in from the current date/time.
17765 So if you press just return without typing anything, the time stamp
17766 will represent the current date/time. If there is already a timestamp
17767 at the cursor, it will be modified."
17768 (interactive "P")
17769 (let* ((ts nil)
17770 (default-time
17771 ;; Default time is either today, or, when entering a range,
17772 ;; the range start.
17773 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
17774 (save-excursion
17775 (re-search-backward
17776 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
17777 (- (point) 20) t)))
17778 (apply 'encode-time (org-parse-time-string (match-string 1)))
17779 (current-time)))
17780 (default-input (and ts (org-get-compact-tod ts)))
17781 org-time-was-given org-end-time-was-given time)
17782 (cond
17783 ((and (org-at-timestamp-p)
17784 (eq last-command 'org-time-stamp)
17785 (eq this-command 'org-time-stamp))
17786 (insert "--")
17787 (setq time (let ((this-command this-command))
17788 (org-read-date arg 'totime nil nil default-time default-input)))
17789 (org-insert-time-stamp time (or org-time-was-given arg)))
17790 ((org-at-timestamp-p)
17791 (setq time (let ((this-command this-command))
17792 (org-read-date arg 'totime nil nil default-time default-input)))
17793 (when (org-at-timestamp-p) ; just to get the match data
17794 (replace-match "")
17795 (setq org-last-changed-timestamp
17796 (org-insert-time-stamp
17797 time (or org-time-was-given arg)
17798 nil nil nil (list org-end-time-was-given))))
17799 (message "Timestamp updated"))
17801 (setq time (let ((this-command this-command))
17802 (org-read-date arg 'totime nil nil default-time default-input)))
17803 (org-insert-time-stamp time (or org-time-was-given arg)
17804 nil nil nil (list org-end-time-was-given))))))
17806 ;; FIXME: can we use this for something else????
17807 ;; like computing time differences?????
17808 (defun org-get-compact-tod (s)
17809 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
17810 (let* ((t1 (match-string 1 s))
17811 (h1 (string-to-number (match-string 2 s)))
17812 (m1 (string-to-number (match-string 3 s)))
17813 (t2 (and (match-end 4) (match-string 5 s)))
17814 (h2 (and t2 (string-to-number (match-string 6 s))))
17815 (m2 (and t2 (string-to-number (match-string 7 s))))
17816 dh dm)
17817 (if (not t2)
17819 (setq dh (- h2 h1) dm (- m2 m1))
17820 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
17821 (concat t1 "+" (number-to-string dh)
17822 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
17824 (defun org-time-stamp-inactive (&optional arg)
17825 "Insert an inactive time stamp.
17826 An inactive time stamp is enclosed in square brackets instead of angle
17827 brackets. It is inactive in the sense that it does not trigger agenda entries,
17828 does not link to the calendar and cannot be changed with the S-cursor keys.
17829 So these are more for recording a certain time/date."
17830 (interactive "P")
17831 (let (org-time-was-given org-end-time-was-given time)
17832 (setq time (org-read-date arg 'totime))
17833 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
17834 nil nil (list org-end-time-was-given))))
17836 (defvar org-date-ovl (org-make-overlay 1 1))
17837 (org-overlay-put org-date-ovl 'face 'org-warning)
17838 (org-detach-overlay org-date-ovl)
17840 (defvar org-ans1) ; dynamically scoped parameter
17841 (defvar org-ans2) ; dynamically scoped parameter
17843 (defvar org-plain-time-of-day-regexp) ; defined below
17845 (defvar org-read-date-overlay nil)
17846 (defvar org-dcst nil) ; dynamically scoped
17848 (defun org-read-date (&optional with-time to-time from-string prompt
17849 default-time default-input)
17850 "Read a date, possibly a time, and make things smooth for the user.
17851 The prompt will suggest to enter an ISO date, but you can also enter anything
17852 which will at least partially be understood by `parse-time-string'.
17853 Unrecognized parts of the date will default to the current day, month, year,
17854 hour and minute. If this command is called to replace a timestamp at point,
17855 of to enter the second timestamp of a range, the default time is taken from the
17856 existing stamp. For example,
17857 3-2-5 --> 2003-02-05
17858 feb 15 --> currentyear-02-15
17859 sep 12 9 --> 2009-09-12
17860 12:45 --> today 12:45
17861 22 sept 0:34 --> currentyear-09-22 0:34
17862 12 --> currentyear-currentmonth-12
17863 Fri --> nearest Friday (today or later)
17864 etc.
17866 Furthermore you can specify a relative date by giving, as the *first* thing
17867 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
17868 change in days weeks, months, years.
17869 With a single plus or minus, the date is relative to today. With a double
17870 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17871 +4d --> four days from today
17872 +4 --> same as above
17873 +2w --> two weeks from today
17874 ++5 --> five days from default date
17876 The function understands only English month and weekday abbreviations,
17877 but this can be configured with the variables `parse-time-months' and
17878 `parse-time-weekdays'.
17880 While prompting, a calendar is popped up - you can also select the
17881 date with the mouse (button 1). The calendar shows a period of three
17882 months. To scroll it to other months, use the keys `>' and `<'.
17883 If you don't like the calendar, turn it off with
17884 \(setq org-read-date-popup-calendar nil)
17886 With optional argument TO-TIME, the date will immediately be converted
17887 to an internal time.
17888 With an optional argument WITH-TIME, the prompt will suggest to also
17889 insert a time. Note that when WITH-TIME is not set, you can still
17890 enter a time, and this function will inform the calling routine about
17891 this change. The calling routine may then choose to change the format
17892 used to insert the time stamp into the buffer to include the time.
17893 With optional argument FROM-STRING, read from this string instead from
17894 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17895 the time/date that is used for everything that is not specified by the
17896 user."
17897 (require 'parse-time)
17898 (let* ((org-time-stamp-rounding-minutes
17899 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
17900 (org-dcst org-display-custom-times)
17901 (ct (org-current-time))
17902 (def (or default-time ct))
17903 (defdecode (decode-time def))
17904 (dummy (progn
17905 (when (< (nth 2 defdecode) org-extend-today-until)
17906 (setcar (nthcdr 2 defdecode) -1)
17907 (setcar (nthcdr 1 defdecode) 59)
17908 (setq def (apply 'encode-time defdecode)
17909 defdecode (decode-time def)))))
17910 (calendar-move-hook nil)
17911 (view-diary-entries-initially nil)
17912 (view-calendar-holidays-initially nil)
17913 (timestr (format-time-string
17914 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
17915 (prompt (concat (if prompt (concat prompt " ") "")
17916 (format "Date+time [%s]: " timestr)))
17917 ans (org-ans0 "") org-ans1 org-ans2 final)
17919 (cond
17920 (from-string (setq ans from-string))
17921 (org-read-date-popup-calendar
17922 (save-excursion
17923 (save-window-excursion
17924 (calendar)
17925 (calendar-forward-day (- (time-to-days def)
17926 (calendar-absolute-from-gregorian
17927 (calendar-current-date))))
17928 (org-eval-in-calendar nil t)
17929 (let* ((old-map (current-local-map))
17930 (map (copy-keymap calendar-mode-map))
17931 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
17932 (org-defkey map (kbd "RET") 'org-calendar-select)
17933 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
17934 'org-calendar-select-mouse)
17935 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
17936 'org-calendar-select-mouse)
17937 (org-defkey minibuffer-local-map [(meta shift left)]
17938 (lambda () (interactive)
17939 (org-eval-in-calendar '(calendar-backward-month 1))))
17940 (org-defkey minibuffer-local-map [(meta shift right)]
17941 (lambda () (interactive)
17942 (org-eval-in-calendar '(calendar-forward-month 1))))
17943 (org-defkey minibuffer-local-map [(meta shift up)]
17944 (lambda () (interactive)
17945 (org-eval-in-calendar '(calendar-backward-year 1))))
17946 (org-defkey minibuffer-local-map [(meta shift down)]
17947 (lambda () (interactive)
17948 (org-eval-in-calendar '(calendar-forward-year 1))))
17949 (org-defkey minibuffer-local-map [(shift up)]
17950 (lambda () (interactive)
17951 (org-eval-in-calendar '(calendar-backward-week 1))))
17952 (org-defkey minibuffer-local-map [(shift down)]
17953 (lambda () (interactive)
17954 (org-eval-in-calendar '(calendar-forward-week 1))))
17955 (org-defkey minibuffer-local-map [(shift left)]
17956 (lambda () (interactive)
17957 (org-eval-in-calendar '(calendar-backward-day 1))))
17958 (org-defkey minibuffer-local-map [(shift right)]
17959 (lambda () (interactive)
17960 (org-eval-in-calendar '(calendar-forward-day 1))))
17961 (org-defkey minibuffer-local-map ">"
17962 (lambda () (interactive)
17963 (org-eval-in-calendar '(scroll-calendar-left 1))))
17964 (org-defkey minibuffer-local-map "<"
17965 (lambda () (interactive)
17966 (org-eval-in-calendar '(scroll-calendar-right 1))))
17967 (unwind-protect
17968 (progn
17969 (use-local-map map)
17970 (add-hook 'post-command-hook 'org-read-date-display)
17971 (setq org-ans0 (read-string prompt default-input nil nil))
17972 ;; org-ans0: from prompt
17973 ;; org-ans1: from mouse click
17974 ;; org-ans2: from calendar motion
17975 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
17976 (remove-hook 'post-command-hook 'org-read-date-display)
17977 (use-local-map old-map)
17978 (when org-read-date-overlay
17979 (org-delete-overlay org-read-date-overlay)
17980 (setq org-read-date-overlay nil)))))))
17982 (t ; Naked prompt only
17983 (unwind-protect
17984 (setq ans (read-string prompt default-input nil timestr))
17985 (when org-read-date-overlay
17986 (org-delete-overlay org-read-date-overlay)
17987 (setq org-read-date-overlay nil)))))
17989 (setq final (org-read-date-analyze ans def defdecode))
17991 (if to-time
17992 (apply 'encode-time final)
17993 (if (and (boundp 'org-time-was-given) org-time-was-given)
17994 (format "%04d-%02d-%02d %02d:%02d"
17995 (nth 5 final) (nth 4 final) (nth 3 final)
17996 (nth 2 final) (nth 1 final))
17997 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17998 (defvar def)
17999 (defvar defdecode)
18000 (defvar with-time)
18001 (defun org-read-date-display ()
18002 "Display the currrent date prompt interpretation in the minibuffer."
18003 (when org-read-date-display-live
18004 (when org-read-date-overlay
18005 (org-delete-overlay org-read-date-overlay))
18006 (let ((p (point)))
18007 (end-of-line 1)
18008 (while (not (equal (buffer-substring
18009 (max (point-min) (- (point) 4)) (point))
18010 " "))
18011 (insert " "))
18012 (goto-char p))
18013 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
18014 " " (or org-ans1 org-ans2)))
18015 (org-end-time-was-given nil)
18016 (f (org-read-date-analyze ans def defdecode))
18017 (fmts (if org-dcst
18018 org-time-stamp-custom-formats
18019 org-time-stamp-formats))
18020 (fmt (if (or with-time
18021 (and (boundp 'org-time-was-given) org-time-was-given))
18022 (cdr fmts)
18023 (car fmts)))
18024 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
18025 (when (and org-end-time-was-given
18026 (string-match org-plain-time-of-day-regexp txt))
18027 (setq txt (concat (substring txt 0 (match-end 0)) "-"
18028 org-end-time-was-given
18029 (substring txt (match-end 0)))))
18030 (setq org-read-date-overlay
18031 (make-overlay (1- (point-at-eol)) (point-at-eol)))
18032 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
18034 (defun org-read-date-analyze (ans def defdecode)
18035 "Analyze the combined answer of the date prompt."
18036 ;; FIXME: cleanup and comment
18037 (let (delta deltan deltaw deltadef year month day
18038 hour minute second wday pm h2 m2 tl wday1)
18040 (when (setq delta (org-read-date-get-relative ans (current-time) def))
18041 (setq ans (replace-match "" t t ans)
18042 deltan (car delta)
18043 deltaw (nth 1 delta)
18044 deltadef (nth 2 delta)))
18046 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
18047 (when (string-match
18048 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
18049 (setq year (if (match-end 2)
18050 (string-to-number (match-string 2 ans))
18051 (string-to-number (format-time-string "%Y")))
18052 month (string-to-number (match-string 3 ans))
18053 day (string-to-number (match-string 4 ans)))
18054 (if (< year 100) (setq year (+ 2000 year)))
18055 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
18056 t nil ans)))
18057 ;; Help matching am/pm times, because `parse-time-string' does not do that.
18058 ;; If there is a time with am/pm, and *no* time without it, we convert
18059 ;; so that matching will be successful.
18060 (loop for i from 1 to 2 do ; twice, for end time as well
18061 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
18062 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
18063 (setq hour (string-to-number (match-string 1 ans))
18064 minute (if (match-end 3)
18065 (string-to-number (match-string 3 ans))
18067 pm (equal ?p
18068 (string-to-char (downcase (match-string 4 ans)))))
18069 (if (and (= hour 12) (not pm))
18070 (setq hour 0)
18071 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
18072 (setq ans (replace-match (format "%02d:%02d" hour minute)
18073 t t ans))))
18075 ;; Check if a time range is given as a duration
18076 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
18077 (setq hour (string-to-number (match-string 1 ans))
18078 h2 (+ hour (string-to-number (match-string 3 ans)))
18079 minute (string-to-number (match-string 2 ans))
18080 m2 (+ minute (if (match-end 5) (string-to-number (match-string 5 ans))0)))
18081 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
18082 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2) t t ans)))
18084 ;; Check if there is a time range
18085 (when (boundp 'org-end-time-was-given)
18086 (setq org-time-was-given nil)
18087 (when (and (string-match org-plain-time-of-day-regexp ans)
18088 (match-end 8))
18089 (setq org-end-time-was-given (match-string 8 ans))
18090 (setq ans (concat (substring ans 0 (match-beginning 7))
18091 (substring ans (match-end 7))))))
18093 (setq tl (parse-time-string ans)
18094 day (or (nth 3 tl) (nth 3 defdecode))
18095 month (or (nth 4 tl)
18096 (if (and org-read-date-prefer-future
18097 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
18098 (1+ (nth 4 defdecode))
18099 (nth 4 defdecode)))
18100 year (or (nth 5 tl)
18101 (if (and org-read-date-prefer-future
18102 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
18103 (1+ (nth 5 defdecode))
18104 (nth 5 defdecode)))
18105 hour (or (nth 2 tl) (nth 2 defdecode))
18106 minute (or (nth 1 tl) (nth 1 defdecode))
18107 second (or (nth 0 tl) 0)
18108 wday (nth 6 tl))
18109 (when deltan
18110 (unless deltadef
18111 (let ((now (decode-time (current-time))))
18112 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
18113 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
18114 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
18115 ((equal deltaw "m") (setq month (+ month deltan)))
18116 ((equal deltaw "y") (setq year (+ year deltan)))))
18117 (when (and wday (not (nth 3 tl)))
18118 ;; Weekday was given, but no day, so pick that day in the week
18119 ;; on or after the derived date.
18120 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
18121 (unless (equal wday wday1)
18122 (setq day (+ day (% (- wday wday1 -7) 7)))))
18123 (if (and (boundp 'org-time-was-given)
18124 (nth 2 tl))
18125 (setq org-time-was-given t))
18126 (if (< year 100) (setq year (+ 2000 year)))
18127 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
18128 (list second minute hour day month year)))
18130 (defvar parse-time-weekdays)
18132 (defun org-read-date-get-relative (s today default)
18133 "Check string S for special relative date string.
18134 TODAY and DEFAULT are internal times, for today and for a default.
18135 Return shift list (N what def-flag)
18136 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
18137 N is the number of WHATs to shift.
18138 DEF-FLAG is t when a double ++ or -- indicates shift relative to
18139 the DEFAULT date rather than TODAY."
18140 (when (string-match
18141 (concat
18142 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
18143 "\\([0-9]+\\)?"
18144 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
18145 "\\([ \t]\\|$\\)") s)
18146 (let* ((dir (if (match-end 1)
18147 (string-to-char (substring (match-string 1 s) -1))
18148 ?+))
18149 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
18150 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
18151 (what (if (match-end 3) (match-string 3 s) "d"))
18152 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
18153 (date (if rel default today))
18154 (wday (nth 6 (decode-time date)))
18155 delta)
18156 (if wday1
18157 (progn
18158 (setq delta (mod (+ 7 (- wday1 wday)) 7))
18159 (if (= dir ?-) (setq delta (- delta 7)))
18160 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
18161 (list delta "d" rel))
18162 (list (* n (if (= dir ?-) -1 1)) what rel)))))
18164 (defun org-eval-in-calendar (form &optional keepdate)
18165 "Eval FORM in the calendar window and return to current window.
18166 Also, store the cursor date in variable org-ans2."
18167 (let ((sw (selected-window)))
18168 (select-window (get-buffer-window "*Calendar*"))
18169 (eval form)
18170 (when (and (not keepdate) (calendar-cursor-to-date))
18171 (let* ((date (calendar-cursor-to-date))
18172 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18173 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
18174 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
18175 (select-window sw)))
18177 ; ;; Update the prompt to show new default date
18178 ; (save-excursion
18179 ; (goto-char (point-min))
18180 ; (when (and org-ans2
18181 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
18182 ; (get-text-property (match-end 0) 'field))
18183 ; (let ((inhibit-read-only t))
18184 ; (replace-match (concat "[" org-ans2 "]") t t)
18185 ; (add-text-properties (point-min) (1+ (match-end 0))
18186 ; (text-properties-at (1+ (point-min)))))))))
18188 (defun org-calendar-select ()
18189 "Return to `org-read-date' with the date currently selected.
18190 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18191 (interactive)
18192 (when (calendar-cursor-to-date)
18193 (let* ((date (calendar-cursor-to-date))
18194 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18195 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18196 (if (active-minibuffer-window) (exit-minibuffer))))
18198 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
18199 "Insert a date stamp for the date given by the internal TIME.
18200 WITH-HM means, use the stamp format that includes the time of the day.
18201 INACTIVE means use square brackets instead of angular ones, so that the
18202 stamp will not contribute to the agenda.
18203 PRE and POST are optional strings to be inserted before and after the
18204 stamp.
18205 The command returns the inserted time stamp."
18206 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
18207 stamp)
18208 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
18209 (insert-before-markers (or pre ""))
18210 (insert-before-markers (setq stamp (format-time-string fmt time)))
18211 (when (listp extra)
18212 (setq extra (car extra))
18213 (if (and (stringp extra)
18214 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
18215 (setq extra (format "-%02d:%02d"
18216 (string-to-number (match-string 1 extra))
18217 (string-to-number (match-string 2 extra))))
18218 (setq extra nil)))
18219 (when extra
18220 (backward-char 1)
18221 (insert-before-markers extra)
18222 (forward-char 1))
18223 (insert-before-markers (or post ""))
18224 stamp))
18226 (defun org-toggle-time-stamp-overlays ()
18227 "Toggle the use of custom time stamp formats."
18228 (interactive)
18229 (setq org-display-custom-times (not org-display-custom-times))
18230 (unless org-display-custom-times
18231 (let ((p (point-min)) (bmp (buffer-modified-p)))
18232 (while (setq p (next-single-property-change p 'display))
18233 (if (and (get-text-property p 'display)
18234 (eq (get-text-property p 'face) 'org-date))
18235 (remove-text-properties
18236 p (setq p (next-single-property-change p 'display))
18237 '(display t))))
18238 (set-buffer-modified-p bmp)))
18239 (if (featurep 'xemacs)
18240 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
18241 (org-restart-font-lock)
18242 (setq org-table-may-need-update t)
18243 (if org-display-custom-times
18244 (message "Time stamps are overlayed with custom format")
18245 (message "Time stamp overlays removed")))
18247 (defun org-display-custom-time (beg end)
18248 "Overlay modified time stamp format over timestamp between BED and END."
18249 (let* ((ts (buffer-substring beg end))
18250 t1 w1 with-hm tf time str w2 (off 0))
18251 (save-match-data
18252 (setq t1 (org-parse-time-string ts t))
18253 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
18254 (setq off (- (match-end 0) (match-beginning 0)))))
18255 (setq end (- end off))
18256 (setq w1 (- end beg)
18257 with-hm (and (nth 1 t1) (nth 2 t1))
18258 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
18259 time (org-fix-decoded-time t1)
18260 str (org-add-props
18261 (format-time-string
18262 (substring tf 1 -1) (apply 'encode-time time))
18263 nil 'mouse-face 'highlight)
18264 w2 (length str))
18265 (if (not (= w2 w1))
18266 (add-text-properties (1+ beg) (+ 2 beg)
18267 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
18268 (if (featurep 'xemacs)
18269 (progn
18270 (put-text-property beg end 'invisible t)
18271 (put-text-property beg end 'end-glyph (make-glyph str)))
18272 (put-text-property beg end 'display str))))
18274 (defun org-translate-time (string)
18275 "Translate all timestamps in STRING to custom format.
18276 But do this only if the variable `org-display-custom-times' is set."
18277 (when org-display-custom-times
18278 (save-match-data
18279 (let* ((start 0)
18280 (re org-ts-regexp-both)
18281 t1 with-hm inactive tf time str beg end)
18282 (while (setq start (string-match re string start))
18283 (setq beg (match-beginning 0)
18284 end (match-end 0)
18285 t1 (save-match-data
18286 (org-parse-time-string (substring string beg end) t))
18287 with-hm (and (nth 1 t1) (nth 2 t1))
18288 inactive (equal (substring string beg (1+ beg)) "[")
18289 tf (funcall (if with-hm 'cdr 'car)
18290 org-time-stamp-custom-formats)
18291 time (org-fix-decoded-time t1)
18292 str (format-time-string
18293 (concat
18294 (if inactive "[" "<") (substring tf 1 -1)
18295 (if inactive "]" ">"))
18296 (apply 'encode-time time))
18297 string (replace-match str t t string)
18298 start (+ start (length str)))))))
18299 string)
18301 (defun org-fix-decoded-time (time)
18302 "Set 0 instead of nil for the first 6 elements of time.
18303 Don't touch the rest."
18304 (let ((n 0))
18305 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
18307 (defun org-days-to-time (timestamp-string)
18308 "Difference between TIMESTAMP-STRING and now in days."
18309 (- (time-to-days (org-time-string-to-time timestamp-string))
18310 (time-to-days (current-time))))
18312 (defun org-deadline-close (timestamp-string &optional ndays)
18313 "Is the time in TIMESTAMP-STRING close to the current date?"
18314 (setq ndays (or ndays (org-get-wdays timestamp-string)))
18315 (and (< (org-days-to-time timestamp-string) ndays)
18316 (not (org-entry-is-done-p))))
18318 (defun org-get-wdays (ts)
18319 "Get the deadline lead time appropriate for timestring TS."
18320 (cond
18321 ((<= org-deadline-warning-days 0)
18322 ;; 0 or negative, enforce this value no matter what
18323 (- org-deadline-warning-days))
18324 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
18325 ;; lead time is specified.
18326 (floor (* (string-to-number (match-string 1 ts))
18327 (cdr (assoc (match-string 2 ts)
18328 '(("d" . 1) ("w" . 7)
18329 ("m" . 30.4) ("y" . 365.25)))))))
18330 ;; go for the default.
18331 (t org-deadline-warning-days)))
18333 (defun org-calendar-select-mouse (ev)
18334 "Return to `org-read-date' with the date currently selected.
18335 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
18336 (interactive "e")
18337 (mouse-set-point ev)
18338 (when (calendar-cursor-to-date)
18339 (let* ((date (calendar-cursor-to-date))
18340 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
18341 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
18342 (if (active-minibuffer-window) (exit-minibuffer))))
18344 (defun org-check-deadlines (ndays)
18345 "Check if there are any deadlines due or past due.
18346 A deadline is considered due if it happens within `org-deadline-warning-days'
18347 days from today's date. If the deadline appears in an entry marked DONE,
18348 it is not shown. The prefix arg NDAYS can be used to test that many
18349 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
18350 (interactive "P")
18351 (let* ((org-warn-days
18352 (cond
18353 ((equal ndays '(4)) 100000)
18354 (ndays (prefix-numeric-value ndays))
18355 (t (abs org-deadline-warning-days))))
18356 (case-fold-search nil)
18357 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
18358 (callback
18359 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
18361 (message "%d deadlines past-due or due within %d days"
18362 (org-occur regexp nil callback)
18363 org-warn-days)))
18365 (defun org-check-before-date (date)
18366 "Check if there are deadlines or scheduled entries before DATE."
18367 (interactive (list (org-read-date)))
18368 (let ((case-fold-search nil)
18369 (regexp (concat "\\<\\(" org-deadline-string
18370 "\\|" org-scheduled-string
18371 "\\) *<\\([^>]+\\)>"))
18372 (callback
18373 (lambda () (time-less-p
18374 (org-time-string-to-time (match-string 2))
18375 (org-time-string-to-time date)))))
18376 (message "%d entries before %s"
18377 (org-occur regexp nil callback) date)))
18379 (defun org-evaluate-time-range (&optional to-buffer)
18380 "Evaluate a time range by computing the difference between start and end.
18381 Normally the result is just printed in the echo area, but with prefix arg
18382 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
18383 If the time range is actually in a table, the result is inserted into the
18384 next column.
18385 For time difference computation, a year is assumed to be exactly 365
18386 days in order to avoid rounding problems."
18387 (interactive "P")
18389 (org-clock-update-time-maybe)
18390 (save-excursion
18391 (unless (org-at-date-range-p t)
18392 (goto-char (point-at-bol))
18393 (re-search-forward org-tr-regexp-both (point-at-eol) t))
18394 (if (not (org-at-date-range-p t))
18395 (error "Not at a time-stamp range, and none found in current line")))
18396 (let* ((ts1 (match-string 1))
18397 (ts2 (match-string 2))
18398 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
18399 (match-end (match-end 0))
18400 (time1 (org-time-string-to-time ts1))
18401 (time2 (org-time-string-to-time ts2))
18402 (t1 (time-to-seconds time1))
18403 (t2 (time-to-seconds time2))
18404 (diff (abs (- t2 t1)))
18405 (negative (< (- t2 t1) 0))
18406 ;; (ys (floor (* 365 24 60 60)))
18407 (ds (* 24 60 60))
18408 (hs (* 60 60))
18409 (fy "%dy %dd %02d:%02d")
18410 (fy1 "%dy %dd")
18411 (fd "%dd %02d:%02d")
18412 (fd1 "%dd")
18413 (fh "%02d:%02d")
18414 y d h m align)
18415 (if havetime
18416 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18418 d (floor (/ diff ds)) diff (mod diff ds)
18419 h (floor (/ diff hs)) diff (mod diff hs)
18420 m (floor (/ diff 60)))
18421 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
18423 d (floor (+ (/ diff ds) 0.5))
18424 h 0 m 0))
18425 (if (not to-buffer)
18426 (message "%s" (org-make-tdiff-string y d h m))
18427 (if (org-at-table-p)
18428 (progn
18429 (goto-char match-end)
18430 (setq align t)
18431 (and (looking-at " *|") (goto-char (match-end 0))))
18432 (goto-char match-end))
18433 (if (looking-at
18434 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
18435 (replace-match ""))
18436 (if negative (insert " -"))
18437 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
18438 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
18439 (insert " " (format fh h m))))
18440 (if align (org-table-align))
18441 (message "Time difference inserted")))))
18443 (defun org-make-tdiff-string (y d h m)
18444 (let ((fmt "")
18445 (l nil))
18446 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
18447 l (push y l)))
18448 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
18449 l (push d l)))
18450 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
18451 l (push h l)))
18452 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
18453 l (push m l)))
18454 (apply 'format fmt (nreverse l))))
18456 (defun org-time-string-to-time (s)
18457 (apply 'encode-time (org-parse-time-string s)))
18459 (defun org-time-string-to-absolute (s &optional daynr prefer)
18460 "Convert a time stamp to an absolute day number.
18461 If there is a specifyer for a cyclic time stamp, get the closest date to
18462 DAYNR."
18463 (cond
18464 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
18465 (if (org-diary-sexp-entry (match-string 1 s) "" date)
18466 daynr
18467 (+ daynr 1000)))
18468 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
18469 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
18470 (time-to-days (current-time))) (match-string 0 s)
18471 prefer))
18472 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
18474 (defun org-time-from-absolute (d)
18475 "Return the time corresponding to date D.
18476 D may be an absolute day number, or a calendar-type list (month day year)."
18477 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
18478 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
18480 (defun org-calendar-holiday ()
18481 "List of holidays, for Diary display in Org-mode."
18482 (require 'holidays)
18483 (let ((hl (funcall
18484 (if (fboundp 'calendar-check-holidays)
18485 'calendar-check-holidays 'check-calendar-holidays) date)))
18486 (if hl (mapconcat 'identity hl "; "))))
18488 (defun org-diary-sexp-entry (sexp entry date)
18489 "Process a SEXP diary ENTRY for DATE."
18490 (require 'diary-lib)
18491 (let ((result (if calendar-debug-sexp
18492 (let ((stack-trace-on-error t))
18493 (eval (car (read-from-string sexp))))
18494 (condition-case nil
18495 (eval (car (read-from-string sexp)))
18496 (error
18497 (beep)
18498 (message "Bad sexp at line %d in %s: %s"
18499 (org-current-line)
18500 (buffer-file-name) sexp)
18501 (sleep-for 2))))))
18502 (cond ((stringp result) result)
18503 ((and (consp result)
18504 (stringp (cdr result))) (cdr result))
18505 (result entry)
18506 (t nil))))
18508 (defun org-diary-to-ical-string (frombuf)
18509 "Get iCalendar entries from diary entries in buffer FROMBUF.
18510 This uses the icalendar.el library."
18511 (let* ((tmpdir (if (featurep 'xemacs)
18512 (temp-directory)
18513 temporary-file-directory))
18514 (tmpfile (make-temp-name
18515 (expand-file-name "orgics" tmpdir)))
18516 buf rtn b e)
18517 (save-excursion
18518 (set-buffer frombuf)
18519 (icalendar-export-region (point-min) (point-max) tmpfile)
18520 (setq buf (find-buffer-visiting tmpfile))
18521 (set-buffer buf)
18522 (goto-char (point-min))
18523 (if (re-search-forward "^BEGIN:VEVENT" nil t)
18524 (setq b (match-beginning 0)))
18525 (goto-char (point-max))
18526 (if (re-search-backward "^END:VEVENT" nil t)
18527 (setq e (match-end 0)))
18528 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
18529 (kill-buffer buf)
18530 (kill-buffer frombuf)
18531 (delete-file tmpfile)
18532 rtn))
18534 (defun org-closest-date (start current change prefer)
18535 "Find the date closest to CURRENT that is consistent with START and CHANGE.
18536 When PREFER is `past' return a date that is either CURRENT or past.
18537 When PREFER is `future', return a date that is either CURRENT or future."
18538 ;; Make the proper lists from the dates
18539 (catch 'exit
18540 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
18541 dn dw sday cday n1 n2
18542 d m y y1 y2 date1 date2 nmonths nm ny m2)
18544 (setq start (org-date-to-gregorian start)
18545 current (org-date-to-gregorian
18546 (if org-agenda-repeating-timestamp-show-all
18547 current
18548 (time-to-days (current-time))))
18549 sday (calendar-absolute-from-gregorian start)
18550 cday (calendar-absolute-from-gregorian current))
18552 (if (<= cday sday) (throw 'exit sday))
18554 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
18555 (setq dn (string-to-number (match-string 1 change))
18556 dw (cdr (assoc (match-string 2 change) a1)))
18557 (error "Invalid change specifyer: %s" change))
18558 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
18559 (cond
18560 ((eq dw 'day)
18561 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
18562 n2 (+ n1 dn)))
18563 ((eq dw 'year)
18564 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
18565 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
18566 (setq date1 (list m d y1)
18567 n1 (calendar-absolute-from-gregorian date1)
18568 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
18569 n2 (calendar-absolute-from-gregorian date2)))
18570 ((eq dw 'month)
18571 ;; approx number of month between the tow dates
18572 (setq nmonths (floor (/ (- cday sday) 30.436875)))
18573 ;; How often does dn fit in there?
18574 (setq d (nth 1 start) m (car start) y (nth 2 start)
18575 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
18576 m (+ m nm)
18577 ny (floor (/ m 12))
18578 y (+ y ny)
18579 m (- m (* ny 12)))
18580 (while (> m 12) (setq m (- m 12) y (1+ y)))
18581 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
18582 (setq m2 (+ m dn) y2 y)
18583 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18584 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
18585 (while (< n2 cday)
18586 (setq n1 n2 m m2 y y2)
18587 (setq m2 (+ m dn) y2 y)
18588 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
18589 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
18591 (if org-agenda-repeating-timestamp-show-all
18592 (cond
18593 ((eq prefer 'past) n1)
18594 ((eq prefer 'future) (if (= cday n1) n1 n2))
18595 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
18596 (cond
18597 ((eq prefer 'past) n1)
18598 ((eq prefer 'future) (if (= cday n1) n1 n2))
18599 (t (if (= cday n1) n1 n2)))))))
18601 (defun org-date-to-gregorian (date)
18602 "Turn any specification of DATE into a gregorian date for the calendar."
18603 (cond ((integerp date) (calendar-gregorian-from-absolute date))
18604 ((and (listp date) (= (length date) 3)) date)
18605 ((stringp date)
18606 (setq date (org-parse-time-string date))
18607 (list (nth 4 date) (nth 3 date) (nth 5 date)))
18608 ((listp date)
18609 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
18611 (defun org-parse-time-string (s &optional nodefault)
18612 "Parse the standard Org-mode time string.
18613 This should be a lot faster than the normal `parse-time-string'.
18614 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18615 hour and minute fields will be nil if not given."
18616 (if (string-match org-ts-regexp0 s)
18617 (list 0
18618 (if (or (match-beginning 8) (not nodefault))
18619 (string-to-number (or (match-string 8 s) "0")))
18620 (if (or (match-beginning 7) (not nodefault))
18621 (string-to-number (or (match-string 7 s) "0")))
18622 (string-to-number (match-string 4 s))
18623 (string-to-number (match-string 3 s))
18624 (string-to-number (match-string 2 s))
18625 nil nil nil)
18626 (make-list 9 0)))
18628 (defun org-timestamp-up (&optional arg)
18629 "Increase the date item at the cursor by one.
18630 If the cursor is on the year, change the year. If it is on the month or
18631 the day, change that.
18632 With prefix ARG, change by that many units."
18633 (interactive "p")
18634 (org-timestamp-change (prefix-numeric-value arg)))
18636 (defun org-timestamp-down (&optional arg)
18637 "Decrease the date item at the cursor by one.
18638 If the cursor is on the year, change the year. If it is on the month or
18639 the day, change that.
18640 With prefix ARG, change by that many units."
18641 (interactive "p")
18642 (org-timestamp-change (- (prefix-numeric-value arg))))
18644 (defun org-timestamp-up-day (&optional arg)
18645 "Increase the date in the time stamp by one day.
18646 With prefix ARG, change that many days."
18647 (interactive "p")
18648 (if (and (not (org-at-timestamp-p t))
18649 (org-on-heading-p))
18650 (org-todo 'up)
18651 (org-timestamp-change (prefix-numeric-value arg) 'day)))
18653 (defun org-timestamp-down-day (&optional arg)
18654 "Decrease the date in the time stamp by one day.
18655 With prefix ARG, change that many days."
18656 (interactive "p")
18657 (if (and (not (org-at-timestamp-p t))
18658 (org-on-heading-p))
18659 (org-todo 'down)
18660 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
18662 (defsubst org-pos-in-match-range (pos n)
18663 (and (match-beginning n)
18664 (<= (match-beginning n) pos)
18665 (>= (match-end n) pos)))
18667 (defun org-at-timestamp-p (&optional inactive-ok)
18668 "Determine if the cursor is in or at a timestamp."
18669 (interactive)
18670 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18671 (pos (point))
18672 (ans (or (looking-at tsr)
18673 (save-excursion
18674 (skip-chars-backward "^[<\n\r\t")
18675 (if (> (point) (point-min)) (backward-char 1))
18676 (and (looking-at tsr)
18677 (> (- (match-end 0) pos) -1))))))
18678 (and ans
18679 (boundp 'org-ts-what)
18680 (setq org-ts-what
18681 (cond
18682 ((= pos (match-beginning 0)) 'bracket)
18683 ((= pos (1- (match-end 0))) 'bracket)
18684 ((org-pos-in-match-range pos 2) 'year)
18685 ((org-pos-in-match-range pos 3) 'month)
18686 ((org-pos-in-match-range pos 7) 'hour)
18687 ((org-pos-in-match-range pos 8) 'minute)
18688 ((or (org-pos-in-match-range pos 4)
18689 (org-pos-in-match-range pos 5)) 'day)
18690 ((and (> pos (or (match-end 8) (match-end 5)))
18691 (< pos (match-end 0)))
18692 (- pos (or (match-end 8) (match-end 5))))
18693 (t 'day))))
18694 ans))
18696 (defun org-toggle-timestamp-type ()
18697 "Toggle the type (<active> or [inactive]) of a time stamp."
18698 (interactive)
18699 (when (org-at-timestamp-p t)
18700 (save-excursion
18701 (goto-char (match-beginning 0))
18702 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
18703 (goto-char (1- (match-end 0)))
18704 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
18705 (message "Timestamp is now %sactive"
18706 (if (equal (char-before) ?>) "in" ""))))
18708 (defun org-timestamp-change (n &optional what)
18709 "Change the date in the time stamp at point.
18710 The date will be changed by N times WHAT. WHAT can be `day', `month',
18711 `year', `minute', `second'. If WHAT is not given, the cursor position
18712 in the timestamp determines what will be changed."
18713 (let ((pos (point))
18714 with-hm inactive
18715 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18716 org-ts-what
18717 extra rem
18718 ts time time0)
18719 (if (not (org-at-timestamp-p t))
18720 (error "Not at a timestamp"))
18721 (if (and (not what) (eq org-ts-what 'bracket))
18722 (org-toggle-timestamp-type)
18723 (if (and (not what) (not (eq org-ts-what 'day))
18724 org-display-custom-times
18725 (get-text-property (point) 'display)
18726 (not (get-text-property (1- (point)) 'display)))
18727 (setq org-ts-what 'day))
18728 (setq org-ts-what (or what org-ts-what)
18729 inactive (= (char-after (match-beginning 0)) ?\[)
18730 ts (match-string 0))
18731 (replace-match "")
18732 (if (string-match
18733 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
18735 (setq extra (match-string 1 ts)))
18736 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18737 (setq with-hm t))
18738 (setq time0 (org-parse-time-string ts))
18739 (when (and (eq org-ts-what 'minute)
18740 (eq current-prefix-arg nil))
18741 (setq n (* dm (org-no-warnings (signum n))))
18742 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
18743 (setcar (cdr time0) (+ (nth 1 time0)
18744 (if (> n 0) (- rem) (- dm rem))))))
18745 (setq time
18746 (encode-time (or (car time0) 0)
18747 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18748 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18749 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18750 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18751 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18752 (nthcdr 6 time0)))
18753 (when (integerp org-ts-what)
18754 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18755 (if (eq what 'calendar)
18756 (let ((cal-date (org-get-date-from-calendar)))
18757 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18758 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18759 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18760 (setcar time0 (or (car time0) 0))
18761 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18762 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18763 (setq time (apply 'encode-time time0))))
18764 (setq org-last-changed-timestamp
18765 (org-insert-time-stamp time with-hm inactive nil nil extra))
18766 (org-clock-update-time-maybe)
18767 (goto-char pos)
18768 ;; Try to recenter the calendar window, if any
18769 (if (and org-calendar-follow-timestamp-change
18770 (get-buffer-window "*Calendar*" t)
18771 (memq org-ts-what '(day month year)))
18772 (org-recenter-calendar (time-to-days time))))))
18774 ;; FIXME: does not yet work for lead times
18775 (defun org-modify-ts-extra (s pos n dm)
18776 "Change the different parts of the lead-time and repeat fields in timestamp."
18777 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18778 ng h m new rem)
18779 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18780 (cond
18781 ((or (org-pos-in-match-range pos 2)
18782 (org-pos-in-match-range pos 3))
18783 (setq m (string-to-number (match-string 3 s))
18784 h (string-to-number (match-string 2 s)))
18785 (if (org-pos-in-match-range pos 2)
18786 (setq h (+ h n))
18787 (setq n (* dm (org-no-warnings (signum n))))
18788 (when (not (= 0 (setq rem (% m dm))))
18789 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18790 (setq m (+ m n)))
18791 (if (< m 0) (setq m (+ m 60) h (1- h)))
18792 (if (> m 59) (setq m (- m 60) h (1+ h)))
18793 (setq h (min 24 (max 0 h)))
18794 (setq ng 1 new (format "-%02d:%02d" h m)))
18795 ((org-pos-in-match-range pos 6)
18796 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18797 ((org-pos-in-match-range pos 5)
18798 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18800 ((org-pos-in-match-range pos 9)
18801 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18802 ((org-pos-in-match-range pos 8)
18803 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18805 (when ng
18806 (setq s (concat
18807 (substring s 0 (match-beginning ng))
18809 (substring s (match-end ng))))))
18812 (defun org-recenter-calendar (date)
18813 "If the calendar is visible, recenter it to DATE."
18814 (let* ((win (selected-window))
18815 (cwin (get-buffer-window "*Calendar*" t))
18816 (calendar-move-hook nil))
18817 (when cwin
18818 (select-window cwin)
18819 (calendar-goto-date (if (listp date) date
18820 (calendar-gregorian-from-absolute date)))
18821 (select-window win))))
18823 (defun org-goto-calendar (&optional arg)
18824 "Go to the Emacs calendar at the current date.
18825 If there is a time stamp in the current line, go to that date.
18826 A prefix ARG can be used to force the current date."
18827 (interactive "P")
18828 (let ((tsr org-ts-regexp) diff
18829 (calendar-move-hook nil)
18830 (view-calendar-holidays-initially nil)
18831 (view-diary-entries-initially nil))
18832 (if (or (org-at-timestamp-p)
18833 (save-excursion
18834 (beginning-of-line 1)
18835 (looking-at (concat ".*" tsr))))
18836 (let ((d1 (time-to-days (current-time)))
18837 (d2 (time-to-days
18838 (org-time-string-to-time (match-string 1)))))
18839 (setq diff (- d2 d1))))
18840 (calendar)
18841 (calendar-goto-today)
18842 (if (and diff (not arg)) (calendar-forward-day diff))))
18844 (defun org-get-date-from-calendar ()
18845 "Return a list (month day year) of date at point in calendar."
18846 (with-current-buffer "*Calendar*"
18847 (save-match-data
18848 (calendar-cursor-to-date))))
18850 (defun org-date-from-calendar ()
18851 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18852 If there is already a time stamp at the cursor position, update it."
18853 (interactive)
18854 (if (org-at-timestamp-p t)
18855 (org-timestamp-change 0 'calendar)
18856 (let ((cal-date (org-get-date-from-calendar)))
18857 (org-insert-time-stamp
18858 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18860 (defvar appt-time-msg-list)
18862 ;;;###autoload
18863 (defun org-agenda-to-appt (&optional refresh filter)
18864 "Activate appointments found in `org-agenda-files'.
18865 With a \\[universal-argument] prefix, refresh the list of
18866 appointements.
18868 If FILTER is t, interactively prompt the user for a regular
18869 expression, and filter out entries that don't match it.
18871 If FILTER is a string, use this string as a regular expression
18872 for filtering entries out.
18874 FILTER can also be an alist with the car of each cell being
18875 either 'headline or 'category. For example:
18877 '((headline \"IMPORTANT\")
18878 (category \"Work\"))
18880 will only add headlines containing IMPORTANT or headlines
18881 belonging to the \"Work\" category."
18882 (interactive "P")
18883 (require 'calendar)
18884 (if refresh (setq appt-time-msg-list nil))
18885 (if (eq filter t)
18886 (setq filter (read-from-minibuffer "Regexp filter: ")))
18887 (let* ((cnt 0) ; count added events
18888 (org-agenda-new-buffers nil)
18889 (org-deadline-warning-days 0)
18890 (today (org-date-to-gregorian
18891 (time-to-days (current-time))))
18892 (files (org-agenda-files)) entries file)
18893 ;; Get all entries which may contain an appt
18894 (while (setq file (pop files))
18895 (setq entries
18896 (append entries
18897 (org-agenda-get-day-entries
18898 file today :timestamp :scheduled :deadline))))
18899 (setq entries (delq nil entries))
18900 ;; Map thru entries and find if we should filter them out
18901 (mapc
18902 (lambda(x)
18903 (let* ((evt (org-trim (get-text-property 1 'txt x)))
18904 (cat (get-text-property 1 'org-category x))
18905 (tod (get-text-property 1 'time-of-day x))
18906 (ok (or (null filter)
18907 (and (stringp filter) (string-match filter evt))
18908 (and (listp filter)
18909 (or (string-match
18910 (cadr (assoc 'category filter)) cat)
18911 (string-match
18912 (cadr (assoc 'headline filter)) evt))))))
18913 ;; FIXME: Shall we remove text-properties for the appt text?
18914 ;; (setq evt (set-text-properties 0 (length evt) nil evt))
18915 (when (and ok tod)
18916 (setq tod (number-to-string tod)
18917 tod (when (string-match
18918 "\\([0-9]\\{1,2\\}\\)\\([0-9]\\{2\\}\\)" tod)
18919 (concat (match-string 1 tod) ":"
18920 (match-string 2 tod))))
18921 (appt-add tod evt)
18922 (setq cnt (1+ cnt))))) entries)
18923 (org-release-buffers org-agenda-new-buffers)
18924 (if (eq cnt 0)
18925 (message "No event to add")
18926 (message "Added %d event%s for today" cnt (if (> cnt 1) "s" "")))))
18928 ;;; The clock for measuring work time.
18930 (defvar org-mode-line-string "")
18931 (put 'org-mode-line-string 'risky-local-variable t)
18933 (defvar org-mode-line-timer nil)
18934 (defvar org-clock-heading "")
18935 (defvar org-clock-start-time "")
18937 (defun org-update-mode-line ()
18938 (let* ((delta (- (time-to-seconds (current-time))
18939 (time-to-seconds org-clock-start-time)))
18940 (h (floor delta 3600))
18941 (m (floor (- delta (* 3600 h)) 60)))
18942 (setq org-mode-line-string
18943 (propertize (format "-[%d:%02d (%s)]" h m org-clock-heading)
18944 'help-echo "Org-mode clock is running"))
18945 (force-mode-line-update)))
18947 (defvar org-clock-marker (make-marker)
18948 "Marker recording the last clock-in.")
18949 (defvar org-clock-mode-line-entry nil
18950 "Information for the modeline about the running clock.")
18952 (defun org-clock-in ()
18953 "Start the clock on the current item.
18954 If necessary, clock-out of the currently active clock."
18955 (interactive)
18956 (org-clock-out t)
18957 (let (ts)
18958 (save-excursion
18959 (org-back-to-heading t)
18960 (when (and org-clock-in-switch-to-state
18961 (not (looking-at (concat outline-regexp "[ \t]*"
18962 org-clock-in-switch-to-state
18963 "\\>"))))
18964 (org-todo org-clock-in-switch-to-state))
18965 (if (and org-clock-heading-function
18966 (functionp org-clock-heading-function))
18967 (setq org-clock-heading (funcall org-clock-heading-function))
18968 (if (looking-at org-complex-heading-regexp)
18969 (setq org-clock-heading (match-string 4))
18970 (setq org-clock-heading "???")))
18971 (setq org-clock-heading (propertize org-clock-heading 'face nil))
18972 (org-clock-find-position)
18974 (insert "\n") (backward-char 1)
18975 (indent-relative)
18976 (insert org-clock-string " ")
18977 (setq org-clock-start-time (current-time))
18978 (setq ts (org-insert-time-stamp (current-time) 'with-hm 'inactive))
18979 (move-marker org-clock-marker (point) (buffer-base-buffer))
18980 (or global-mode-string (setq global-mode-string '("")))
18981 (or (memq 'org-mode-line-string global-mode-string)
18982 (setq global-mode-string
18983 (append global-mode-string '(org-mode-line-string))))
18984 (org-update-mode-line)
18985 (setq org-mode-line-timer (run-with-timer 60 60 'org-update-mode-line))
18986 (message "Clock started at %s" ts))))
18988 (defun org-clock-find-position ()
18989 "Find the location where the next clock line should be inserted."
18990 (org-back-to-heading t)
18991 (catch 'exit
18992 (let ((beg (point-at-bol 2)) (end (progn (outline-next-heading) (point)))
18993 (re (concat "^[ \t]*" org-clock-string))
18994 (cnt 0)
18995 first last)
18996 (goto-char beg)
18997 (when (eobp) (newline) (setq end (max (point) end)))
18998 (when (re-search-forward "^[ \t]*:CLOCK:" end t)
18999 ;; we seem to have a CLOCK drawer, so go there.
19000 (beginning-of-line 2)
19001 (throw 'exit t))
19002 ;; Lets count the CLOCK lines
19003 (goto-char beg)
19004 (while (re-search-forward re end t)
19005 (setq first (or first (match-beginning 0))
19006 last (match-beginning 0)
19007 cnt (1+ cnt)))
19008 (when (and (integerp org-clock-into-drawer)
19009 (>= (1+ cnt) org-clock-into-drawer))
19010 ;; Wrap current entries into a new drawer
19011 (goto-char last)
19012 (beginning-of-line 2)
19013 (if (org-at-item-p) (org-end-of-item))
19014 (insert ":END:\n")
19015 (beginning-of-line 0)
19016 (org-indent-line-function)
19017 (goto-char first)
19018 (insert ":CLOCK:\n")
19019 (beginning-of-line 0)
19020 (org-indent-line-function)
19021 (org-flag-drawer t)
19022 (beginning-of-line 2)
19023 (throw 'exit nil))
19025 (goto-char beg)
19026 (while (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19027 (not (equal (match-string 1) org-clock-string)))
19028 ;; Planning info, skip to after it
19029 (beginning-of-line 2)
19030 (or (bolp) (newline)))
19031 (when (eq t org-clock-into-drawer)
19032 (insert ":CLOCK:\n:END:\n")
19033 (beginning-of-line -1)
19034 (org-indent-line-function)
19035 (org-flag-drawer t)
19036 (beginning-of-line 2)
19037 (org-indent-line-function)))))
19039 (defun org-clock-out (&optional fail-quietly)
19040 "Stop the currently running clock.
19041 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
19042 (interactive)
19043 (catch 'exit
19044 (if (not (marker-buffer org-clock-marker))
19045 (if fail-quietly (throw 'exit t) (error "No active clock")))
19046 (let (ts te s h m)
19047 (save-excursion
19048 (set-buffer (marker-buffer org-clock-marker))
19049 (goto-char org-clock-marker)
19050 (beginning-of-line 1)
19051 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
19052 (equal (match-string 1) org-clock-string))
19053 (setq ts (match-string 2))
19054 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
19055 (goto-char (match-end 0))
19056 (delete-region (point) (point-at-eol))
19057 (insert "--")
19058 (setq te (org-insert-time-stamp (current-time) 'with-hm 'inactive))
19059 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
19060 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
19061 h (floor (/ s 3600))
19062 s (- s (* 3600 h))
19063 m (floor (/ s 60))
19064 s (- s (* 60 s)))
19065 (insert " => " (format "%2d:%02d" h m))
19066 (move-marker org-clock-marker nil)
19067 (when org-log-note-clock-out
19068 (org-add-log-maybe 'clock-out))
19069 (when org-mode-line-timer
19070 (cancel-timer org-mode-line-timer)
19071 (setq org-mode-line-timer nil))
19072 (setq global-mode-string
19073 (delq 'org-mode-line-string global-mode-string))
19074 (force-mode-line-update)
19075 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
19077 (defun org-clock-cancel ()
19078 "Cancel the running clock be removing the start timestamp."
19079 (interactive)
19080 (if (not (marker-buffer org-clock-marker))
19081 (error "No active clock"))
19082 (save-excursion
19083 (set-buffer (marker-buffer org-clock-marker))
19084 (goto-char org-clock-marker)
19085 (delete-region (1- (point-at-bol)) (point-at-eol)))
19086 (setq global-mode-string
19087 (delq 'org-mode-line-string global-mode-string))
19088 (force-mode-line-update)
19089 (message "Clock canceled"))
19091 (defun org-clock-goto (&optional delete-windows)
19092 "Go to the currently clocked-in entry."
19093 (interactive "P")
19094 (if (not (marker-buffer org-clock-marker))
19095 (error "No active clock"))
19096 (switch-to-buffer-other-window
19097 (marker-buffer org-clock-marker))
19098 (if delete-windows (delete-other-windows))
19099 (goto-char org-clock-marker)
19100 (org-show-entry)
19101 (org-back-to-heading)
19102 (recenter))
19104 (defvar org-clock-file-total-minutes nil
19105 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
19106 (make-variable-buffer-local 'org-clock-file-total-minutes)
19108 (defun org-clock-sum (&optional tstart tend)
19109 "Sum the times for each subtree.
19110 Puts the resulting times in minutes as a text property on each headline."
19111 (interactive)
19112 (let* ((bmp (buffer-modified-p))
19113 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
19114 org-clock-string
19115 "[ \t]*\\(?:\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)\\|=>[ \t]+\\([0-9]+\\):\\([0-9]+\\)\\)"))
19116 (lmax 30)
19117 (ltimes (make-vector lmax 0))
19118 (t1 0)
19119 (level 0)
19120 ts te dt
19121 time)
19122 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
19123 (save-excursion
19124 (goto-char (point-max))
19125 (while (re-search-backward re nil t)
19126 (cond
19127 ((match-end 2)
19128 ;; Two time stamps
19129 (setq ts (match-string 2)
19130 te (match-string 3)
19131 ts (time-to-seconds
19132 (apply 'encode-time (org-parse-time-string ts)))
19133 te (time-to-seconds
19134 (apply 'encode-time (org-parse-time-string te)))
19135 ts (if tstart (max ts tstart) ts)
19136 te (if tend (min te tend) te)
19137 dt (- te ts)
19138 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1)))
19139 ((match-end 4)
19140 ;; A naket time
19141 (setq t1 (+ t1 (string-to-number (match-string 5))
19142 (* 60 (string-to-number (match-string 4))))))
19143 (t ;; A headline
19144 (setq level (- (match-end 1) (match-beginning 1)))
19145 (when (or (> t1 0) (> (aref ltimes level) 0))
19146 (loop for l from 0 to level do
19147 (aset ltimes l (+ (aref ltimes l) t1)))
19148 (setq t1 0 time (aref ltimes level))
19149 (loop for l from level to (1- lmax) do
19150 (aset ltimes l 0))
19151 (goto-char (match-beginning 0))
19152 (put-text-property (point) (point-at-eol) :org-clock-minutes time)))))
19153 (setq org-clock-file-total-minutes (aref ltimes 0)))
19154 (set-buffer-modified-p bmp)))
19156 (defun org-clock-display (&optional total-only)
19157 "Show subtree times in the entire buffer.
19158 If TOTAL-ONLY is non-nil, only show the total time for the entire file
19159 in the echo area."
19160 (interactive)
19161 (org-remove-clock-overlays)
19162 (let (time h m p)
19163 (org-clock-sum)
19164 (unless total-only
19165 (save-excursion
19166 (goto-char (point-min))
19167 (while (or (and (equal (setq p (point)) (point-min))
19168 (get-text-property p :org-clock-minutes))
19169 (setq p (next-single-property-change
19170 (point) :org-clock-minutes)))
19171 (goto-char p)
19172 (when (setq time (get-text-property p :org-clock-minutes))
19173 (org-put-clock-overlay time (funcall outline-level))))
19174 (setq h (/ org-clock-file-total-minutes 60)
19175 m (- org-clock-file-total-minutes (* 60 h)))
19176 ;; Arrange to remove the overlays upon next change.
19177 (when org-remove-highlights-with-change
19178 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
19179 nil 'local))))
19180 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
19182 (defvar org-clock-overlays nil)
19183 (make-variable-buffer-local 'org-clock-overlays)
19185 (defun org-put-clock-overlay (time &optional level)
19186 "Put an overlays on the current line, displaying TIME.
19187 If LEVEL is given, prefix time with a corresponding number of stars.
19188 This creates a new overlay and stores it in `org-clock-overlays', so that it
19189 will be easy to remove."
19190 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
19191 (l (if level (org-get-valid-level level 0) 0))
19192 (off 0)
19193 ov tx)
19194 (move-to-column c)
19195 (unless (eolp) (skip-chars-backward "^ \t"))
19196 (skip-chars-backward " \t")
19197 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
19198 tx (concat (buffer-substring (1- (point)) (point))
19199 (make-string (+ off (max 0 (- c (current-column)))) ?.)
19200 (org-add-props (format "%s %2d:%02d%s"
19201 (make-string l ?*) h m
19202 (make-string (- 16 l) ?\ ))
19203 '(face secondary-selection))
19204 ""))
19205 (if (not (featurep 'xemacs))
19206 (org-overlay-put ov 'display tx)
19207 (org-overlay-put ov 'invisible t)
19208 (org-overlay-put ov 'end-glyph (make-glyph tx)))
19209 (push ov org-clock-overlays)))
19211 (defun org-remove-clock-overlays (&optional beg end noremove)
19212 "Remove the occur highlights from the buffer.
19213 BEG and END are ignored. If NOREMOVE is nil, remove this function
19214 from the `before-change-functions' in the current buffer."
19215 (interactive)
19216 (unless org-inhibit-highlight-removal
19217 (mapc 'org-delete-overlay org-clock-overlays)
19218 (setq org-clock-overlays nil)
19219 (unless noremove
19220 (remove-hook 'before-change-functions
19221 'org-remove-clock-overlays 'local))))
19223 (defun org-clock-out-if-current ()
19224 "Clock out if the current entry contains the running clock.
19225 This is used to stop the clock after a TODO entry is marked DONE,
19226 and is only done if the variable `org-clock-out-when-done' is not nil."
19227 (when (and org-clock-out-when-done
19228 (member state org-done-keywords)
19229 (equal (marker-buffer org-clock-marker) (current-buffer))
19230 (< (point) org-clock-marker)
19231 (> (save-excursion (outline-next-heading) (point))
19232 org-clock-marker))
19233 ;; Clock out, but don't accept a logging message for this.
19234 (let ((org-log-note-clock-out nil))
19235 (org-clock-out))))
19237 (add-hook 'org-after-todo-state-change-hook
19238 'org-clock-out-if-current)
19240 (defun org-check-running-clock ()
19241 "Check if the current buffer contains the running clock.
19242 If yes, offer to stop it and to save the buffer with the changes."
19243 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
19244 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
19245 (buffer-name))))
19246 (org-clock-out)
19247 (when (y-or-n-p "Save changed buffer?")
19248 (save-buffer))))
19250 (defun org-clock-report (&optional arg)
19251 "Create a table containing a report about clocked time.
19252 If the cursor is inside an existing clocktable block, then the table
19253 will be updated. If not, a new clocktable will be inserted.
19254 When called with a prefix argument, move to the first clock table in the
19255 buffer and update it."
19256 (interactive "P")
19257 (org-remove-clock-overlays)
19258 (when arg
19259 (org-find-dblock "clocktable")
19260 (org-show-entry))
19261 (if (org-in-clocktable-p)
19262 (goto-char (org-in-clocktable-p))
19263 (org-create-dblock (list :name "clocktable"
19264 :maxlevel 2 :scope 'file)))
19265 (org-update-dblock))
19267 (defun org-in-clocktable-p ()
19268 "Check if the cursor is in a clocktable."
19269 (let ((pos (point)) start)
19270 (save-excursion
19271 (end-of-line 1)
19272 (and (re-search-backward "^#\\+BEGIN:[ \t]+clocktable" nil t)
19273 (setq start (match-beginning 0))
19274 (re-search-forward "^#\\+END:.*" nil t)
19275 (>= (match-end 0) pos)
19276 start))))
19278 (defun org-clock-update-time-maybe ()
19279 "If this is a CLOCK line, update it and return t.
19280 Otherwise, return nil."
19281 (interactive)
19282 (save-excursion
19283 (beginning-of-line 1)
19284 (skip-chars-forward " \t")
19285 (when (looking-at org-clock-string)
19286 (let ((re (concat "[ \t]*" org-clock-string
19287 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
19288 "\\([ \t]*=>.*\\)?"))
19289 ts te h m s)
19290 (if (not (looking-at re))
19292 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
19293 (end-of-line 1)
19294 (setq ts (match-string 1)
19295 te (match-string 2))
19296 (setq s (- (time-to-seconds
19297 (apply 'encode-time (org-parse-time-string te)))
19298 (time-to-seconds
19299 (apply 'encode-time (org-parse-time-string ts))))
19300 h (floor (/ s 3600))
19301 s (- s (* 3600 h))
19302 m (floor (/ s 60))
19303 s (- s (* 60 s)))
19304 (insert " => " (format "%2d:%02d" h m))
19305 t)))))
19307 (defun org-clock-special-range (key &optional time as-strings)
19308 "Return two times bordering a special time range.
19309 Key is a symbol specifying the range and can be one of `today', `yesterday',
19310 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
19311 A week starts Monday 0:00 and ends Sunday 24:00.
19312 The range is determined relative to TIME. TIME defaults to the current time.
19313 The return value is a cons cell with two internal times like the ones
19314 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
19315 the returned times will be formatted strings."
19316 (let* ((tm (decode-time (or time (current-time))))
19317 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
19318 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
19319 (dow (nth 6 tm))
19320 s1 m1 h1 d1 month1 y1 diff ts te fm)
19321 (cond
19322 ((eq key 'today)
19323 (setq h 0 m 0 h1 24 m1 0))
19324 ((eq key 'yesterday)
19325 (setq d (1- d) h 0 m 0 h1 24 m1 0))
19326 ((eq key 'thisweek)
19327 (setq diff (if (= dow 0) 6 (1- dow))
19328 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19329 ((eq key 'lastweek)
19330 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
19331 m 0 h 0 d (- d diff) d1 (+ 7 d)))
19332 ((eq key 'thismonth)
19333 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
19334 ((eq key 'lastmonth)
19335 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
19336 ((eq key 'thisyear)
19337 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
19338 ((eq key 'lastyear)
19339 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
19340 (t (error "No such time block %s" key)))
19341 (setq ts (encode-time s m h d month y)
19342 te (encode-time (or s1 s) (or m1 m) (or h1 h)
19343 (or d1 d) (or month1 month) (or y1 y)))
19344 (setq fm (cdr org-time-stamp-formats))
19345 (if as-strings
19346 (cons (format-time-string fm ts) (format-time-string fm te))
19347 (cons ts te))))
19349 (defun org-dblock-write:clocktable (params)
19350 "Write the standard clocktable."
19351 (catch 'exit
19352 (let* ((hlchars '((1 . "*") (2 . "/")))
19353 (ins (make-marker))
19354 (total-time nil)
19355 (scope (plist-get params :scope))
19356 (tostring (plist-get params :tostring))
19357 (multifile (plist-get params :multifile))
19358 (header (plist-get params :header))
19359 (maxlevel (or (plist-get params :maxlevel) 3))
19360 (step (plist-get params :step))
19361 (emph (plist-get params :emphasize))
19362 (ts (plist-get params :tstart))
19363 (te (plist-get params :tend))
19364 (block (plist-get params :block))
19365 (link (plist-get params :link))
19366 ipos time h m p level hlc hdl
19367 cc beg end pos tbl)
19368 (when step
19369 (org-clocktable-steps params)
19370 (throw 'exit nil))
19371 (when block
19372 (setq cc (org-clock-special-range block nil t)
19373 ts (car cc) te (cdr cc)))
19374 (if ts (setq ts (time-to-seconds
19375 (apply 'encode-time (org-parse-time-string ts)))))
19376 (if te (setq te (time-to-seconds
19377 (apply 'encode-time (org-parse-time-string te)))))
19378 (move-marker ins (point))
19379 (setq ipos (point))
19381 ;; Get the right scope
19382 (setq pos (point))
19383 (save-restriction
19384 (cond
19385 ((not scope))
19386 ((eq scope 'file) (widen))
19387 ((eq scope 'subtree) (org-narrow-to-subtree))
19388 ((eq scope 'tree)
19389 (while (org-up-heading-safe))
19390 (org-narrow-to-subtree))
19391 ((and (symbolp scope) (string-match "^tree\\([0-9]+\\)$"
19392 (symbol-name scope)))
19393 (setq level (string-to-number (match-string 1 (symbol-name scope))))
19394 (catch 'exit
19395 (while (org-up-heading-safe)
19396 (looking-at outline-regexp)
19397 (if (<= (org-reduced-level (funcall outline-level)) level)
19398 (throw 'exit nil))))
19399 (org-narrow-to-subtree))
19400 ((or (listp scope) (eq scope 'agenda))
19401 (let* ((files (if (listp scope) scope (org-agenda-files)))
19402 (scope 'agenda)
19403 (p1 (copy-sequence params))
19404 file)
19405 (plist-put p1 :tostring t)
19406 (plist-put p1 :multifile t)
19407 (plist-put p1 :scope 'file)
19408 (org-prepare-agenda-buffers files)
19409 (while (setq file (pop files))
19410 (with-current-buffer (find-buffer-visiting file)
19411 (push (org-clocktable-add-file
19412 file (org-dblock-write:clocktable p1)) tbl)
19413 (setq total-time (+ (or total-time 0)
19414 org-clock-file-total-minutes)))))))
19415 (goto-char pos)
19417 (unless (eq scope 'agenda)
19418 (org-clock-sum ts te)
19419 (goto-char (point-min))
19420 (while (setq p (next-single-property-change (point) :org-clock-minutes))
19421 (goto-char p)
19422 (when (setq time (get-text-property p :org-clock-minutes))
19423 (save-excursion
19424 (beginning-of-line 1)
19425 (when (and (looking-at (org-re "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[[:alnum:]_@:]+:\\)?[ \t]*$"))
19426 (setq level (org-reduced-level
19427 (- (match-end 1) (match-beginning 1))))
19428 (<= level maxlevel))
19429 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
19430 hdl (if (not link)
19431 (match-string 2)
19432 (org-make-link-string
19433 (format "file:%s::%s"
19434 (buffer-file-name)
19435 (save-match-data
19436 (org-make-org-heading-search-string
19437 (match-string 2))))
19438 (match-string 2)))
19439 h (/ time 60)
19440 m (- time (* 60 h)))
19441 (if (and (not multifile) (= level 1)) (push "|-" tbl))
19442 (push (concat
19443 "| " (int-to-string level) "|" hlc hdl hlc " |"
19444 (make-string (1- level) ?|)
19445 hlc (format "%d:%02d" h m) hlc
19446 " |") tbl))))))
19447 (setq tbl (nreverse tbl))
19448 (if tostring
19449 (if tbl (mapconcat 'identity tbl "\n") nil)
19450 (goto-char ins)
19451 (insert-before-markers
19452 (or header
19453 (concat
19454 "Clock summary at ["
19455 (substring
19456 (format-time-string (cdr org-time-stamp-formats))
19457 1 -1)
19458 "]."
19459 (if block
19460 (format " Considered range is /%s/." block)
19462 "\n\n"))
19463 (if (eq scope 'agenda) "|File" "")
19464 "|L|Headline|Time|\n")
19465 (setq total-time (or total-time org-clock-file-total-minutes)
19466 h (/ total-time 60)
19467 m (- total-time (* 60 h)))
19468 (insert-before-markers
19469 "|-\n|"
19470 (if (eq scope 'agenda) "|" "")
19472 "*Total time*| "
19473 (format "*%d:%02d*" h m)
19474 "|\n|-\n")
19475 (setq tbl (delq nil tbl))
19476 (if (and (stringp (car tbl)) (> (length (car tbl)) 1)
19477 (equal (substring (car tbl) 0 2) "|-"))
19478 (pop tbl))
19479 (insert-before-markers (mapconcat
19480 'identity (delq nil tbl)
19481 (if (eq scope 'agenda) "\n|-\n" "\n")))
19482 (backward-delete-char 1)
19483 (goto-char ipos)
19484 (skip-chars-forward "^|")
19485 (org-table-align))))))
19487 (defun org-clocktable-steps (params)
19488 (let* ((p1 (copy-sequence params))
19489 (ts (plist-get p1 :tstart))
19490 (te (plist-get p1 :tend))
19491 (step0 (plist-get p1 :step))
19492 (step (cdr (assoc step0 '((day . 86400) (week . 604800)))))
19493 (block (plist-get p1 :block))
19495 (when block
19496 (setq cc (org-clock-special-range block nil t)
19497 ts (car cc) te (cdr cc)))
19498 (if ts (setq ts (time-to-seconds
19499 (apply 'encode-time (org-parse-time-string ts)))))
19500 (if te (setq te (time-to-seconds
19501 (apply 'encode-time (org-parse-time-string te)))))
19502 (plist-put p1 :header "")
19503 (plist-put p1 :step nil)
19504 (plist-put p1 :block nil)
19505 (while (< ts te)
19506 (or (bolp) (insert "\n"))
19507 (plist-put p1 :tstart (format-time-string
19508 (car org-time-stamp-formats)
19509 (seconds-to-time ts)))
19510 (plist-put p1 :tend (format-time-string
19511 (car org-time-stamp-formats)
19512 (seconds-to-time (setq ts (+ ts step)))))
19513 (insert "\n" (if (eq step0 'day) "Daily report: " "Weekly report starting on: ")
19514 (plist-get p1 :tstart) "\n")
19515 (org-dblock-write:clocktable p1)
19516 (re-search-forward "#\\+END:")
19517 (end-of-line 0))))
19520 (defun org-clocktable-add-file (file table)
19521 (if table
19522 (let ((lines (org-split-string table "\n"))
19523 (ff (file-name-nondirectory file)))
19524 (mapconcat 'identity
19525 (mapcar (lambda (x)
19526 (if (string-match org-table-dataline-regexp x)
19527 (concat "|" ff x)
19529 lines)
19530 "\n"))))
19532 ;; FIXME: I don't think anybody uses this, ask David
19533 (defun org-collect-clock-time-entries ()
19534 "Return an internal list with clocking information.
19535 This list has one entry for each CLOCK interval.
19536 FIXME: describe the elements."
19537 (interactive)
19538 (let ((re (concat "^[ \t]*" org-clock-string
19539 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
19540 rtn beg end next cont level title total closedp leafp
19541 clockpos titlepos h m donep)
19542 (save-excursion
19543 (org-clock-sum)
19544 (goto-char (point-min))
19545 (while (re-search-forward re nil t)
19546 (setq clockpos (match-beginning 0)
19547 beg (match-string 1) end (match-string 2)
19548 cont (match-end 0))
19549 (setq beg (apply 'encode-time (org-parse-time-string beg))
19550 end (apply 'encode-time (org-parse-time-string end)))
19551 (org-back-to-heading t)
19552 (setq donep (org-entry-is-done-p))
19553 (setq titlepos (point)
19554 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
19555 h (/ total 60) m (- total (* 60 h))
19556 total (cons h m))
19557 (looking-at "\\(\\*+\\) +\\(.*\\)")
19558 (setq level (- (match-end 1) (match-beginning 1))
19559 title (org-match-string-no-properties 2))
19560 (save-excursion (outline-next-heading) (setq next (point)))
19561 (setq closedp (re-search-forward org-closed-time-regexp next t))
19562 (goto-char next)
19563 (setq leafp (and (looking-at "^\\*+ ")
19564 (<= (- (match-end 0) (point)) level)))
19565 (push (list beg end clockpos closedp donep
19566 total title titlepos level leafp)
19567 rtn)
19568 (goto-char cont)))
19569 (nreverse rtn)))
19571 ;;;; Agenda, and Diary Integration
19573 ;;; Define the Org-agenda-mode
19575 (defvar org-agenda-mode-map (make-sparse-keymap)
19576 "Keymap for `org-agenda-mode'.")
19578 (defvar org-agenda-menu) ; defined later in this file.
19579 (defvar org-agenda-follow-mode nil)
19580 (defvar org-agenda-show-log nil)
19581 (defvar org-agenda-redo-command nil)
19582 (defvar org-agenda-query-string nil)
19583 (defvar org-agenda-mode-hook nil)
19584 (defvar org-agenda-type nil)
19585 (defvar org-agenda-force-single-file nil)
19587 (defun org-agenda-mode ()
19588 "Mode for time-sorted view on action items in Org-mode files.
19590 The following commands are available:
19592 \\{org-agenda-mode-map}"
19593 (interactive)
19594 (kill-all-local-variables)
19595 (setq org-agenda-undo-list nil
19596 org-agenda-pending-undo-list nil)
19597 (setq major-mode 'org-agenda-mode)
19598 ;; Keep global-font-lock-mode from turning on font-lock-mode
19599 (org-set-local 'font-lock-global-modes (list 'not major-mode))
19600 (setq mode-name "Org-Agenda")
19601 (use-local-map org-agenda-mode-map)
19602 (easy-menu-add org-agenda-menu)
19603 (if org-startup-truncated (setq truncate-lines t))
19604 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
19605 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
19606 ;; Make sure properties are removed when copying text
19607 (when (boundp 'buffer-substring-filters)
19608 (org-set-local 'buffer-substring-filters
19609 (cons (lambda (x)
19610 (set-text-properties 0 (length x) nil x) x)
19611 buffer-substring-filters)))
19612 (unless org-agenda-keep-modes
19613 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
19614 org-agenda-show-log nil))
19615 (easy-menu-change
19616 '("Agenda") "Agenda Files"
19617 (append
19618 (list
19619 (vector
19620 (if (get 'org-agenda-files 'org-restrict)
19621 "Restricted to single file"
19622 "Edit File List")
19623 '(org-edit-agenda-file-list)
19624 (not (get 'org-agenda-files 'org-restrict)))
19625 "--")
19626 (mapcar 'org-file-menu-entry (org-agenda-files))))
19627 (org-agenda-set-mode-name)
19628 (apply
19629 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
19630 (list 'org-agenda-mode-hook)))
19632 (substitute-key-definition 'undo 'org-agenda-undo
19633 org-agenda-mode-map global-map)
19634 (org-defkey org-agenda-mode-map "\C-i" 'org-agenda-goto)
19635 (org-defkey org-agenda-mode-map [(tab)] 'org-agenda-goto)
19636 (org-defkey org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
19637 (org-defkey org-agenda-mode-map "\C-k" 'org-agenda-kill)
19638 (org-defkey org-agenda-mode-map "\C-c$" 'org-agenda-archive)
19639 (org-defkey org-agenda-mode-map "\C-c\C-x\C-s" 'org-agenda-archive)
19640 (org-defkey org-agenda-mode-map "$" 'org-agenda-archive)
19641 (org-defkey org-agenda-mode-map "\C-c\C-o" 'org-agenda-open-link)
19642 (org-defkey org-agenda-mode-map " " 'org-agenda-show)
19643 (org-defkey org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
19644 (org-defkey org-agenda-mode-map [(control shift right)] 'org-agenda-todo-nextset)
19645 (org-defkey org-agenda-mode-map [(control shift left)] 'org-agenda-todo-previousset)
19646 (org-defkey org-agenda-mode-map "\C-c\C-xb" 'org-agenda-tree-to-indirect-buffer)
19647 (org-defkey org-agenda-mode-map "b" 'org-agenda-tree-to-indirect-buffer)
19648 (org-defkey org-agenda-mode-map "o" 'delete-other-windows)
19649 (org-defkey org-agenda-mode-map "L" 'org-agenda-recenter)
19650 (org-defkey org-agenda-mode-map "t" 'org-agenda-todo)
19651 (org-defkey org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
19652 (org-defkey org-agenda-mode-map ":" 'org-agenda-set-tags)
19653 (org-defkey org-agenda-mode-map "." 'org-agenda-goto-today)
19654 (org-defkey org-agenda-mode-map "j" 'org-agenda-goto-date)
19655 (org-defkey org-agenda-mode-map "d" 'org-agenda-day-view)
19656 (org-defkey org-agenda-mode-map "w" 'org-agenda-week-view)
19657 (org-defkey org-agenda-mode-map "m" 'org-agenda-month-view)
19658 (org-defkey org-agenda-mode-map "y" 'org-agenda-year-view)
19659 (org-defkey org-agenda-mode-map [(shift right)] 'org-agenda-date-later)
19660 (org-defkey org-agenda-mode-map [(shift left)] 'org-agenda-date-earlier)
19661 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
19662 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
19664 (org-defkey org-agenda-mode-map ">" 'org-agenda-date-prompt)
19665 (org-defkey org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
19666 (org-defkey org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
19667 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
19668 (while l (org-defkey org-agenda-mode-map
19669 (int-to-string (pop l)) 'digit-argument)))
19671 (org-defkey org-agenda-mode-map "f" 'org-agenda-follow-mode)
19672 (org-defkey org-agenda-mode-map "l" 'org-agenda-log-mode)
19673 (org-defkey org-agenda-mode-map "D" 'org-agenda-toggle-diary)
19674 (org-defkey org-agenda-mode-map "G" 'org-agenda-toggle-time-grid)
19675 (org-defkey org-agenda-mode-map "r" 'org-agenda-redo)
19676 (org-defkey org-agenda-mode-map "g" 'org-agenda-redo)
19677 (org-defkey org-agenda-mode-map "e" 'org-agenda-execute)
19678 (org-defkey org-agenda-mode-map "q" 'org-agenda-quit)
19679 (org-defkey org-agenda-mode-map "x" 'org-agenda-exit)
19680 (org-defkey org-agenda-mode-map "\C-x\C-w" 'org-write-agenda)
19681 (org-defkey org-agenda-mode-map "s" 'org-save-all-org-buffers)
19682 (org-defkey org-agenda-mode-map "\C-x\C-s" 'org-save-all-org-buffers)
19683 (org-defkey org-agenda-mode-map "P" 'org-agenda-show-priority)
19684 (org-defkey org-agenda-mode-map "T" 'org-agenda-show-tags)
19685 (org-defkey org-agenda-mode-map "n" 'next-line)
19686 (org-defkey org-agenda-mode-map "p" 'previous-line)
19687 (org-defkey org-agenda-mode-map "\C-c\C-n" 'org-agenda-next-date-line)
19688 (org-defkey org-agenda-mode-map "\C-c\C-p" 'org-agenda-previous-date-line)
19689 (org-defkey org-agenda-mode-map "," 'org-agenda-priority)
19690 (org-defkey org-agenda-mode-map "\C-c," 'org-agenda-priority)
19691 (org-defkey org-agenda-mode-map "i" 'org-agenda-diary-entry)
19692 (org-defkey org-agenda-mode-map "c" 'org-agenda-goto-calendar)
19693 (eval-after-load "calendar"
19694 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
19695 'org-calendar-goto-agenda))
19696 (org-defkey org-agenda-mode-map "C" 'org-agenda-convert-date)
19697 (org-defkey org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
19698 (org-defkey org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
19699 (org-defkey org-agenda-mode-map "h" 'org-agenda-holidays)
19700 (org-defkey org-agenda-mode-map "H" 'org-agenda-holidays)
19701 (org-defkey org-agenda-mode-map "\C-c\C-x\C-i" 'org-agenda-clock-in)
19702 (org-defkey org-agenda-mode-map "I" 'org-agenda-clock-in)
19703 (org-defkey org-agenda-mode-map "\C-c\C-x\C-o" 'org-agenda-clock-out)
19704 (org-defkey org-agenda-mode-map "O" 'org-agenda-clock-out)
19705 (org-defkey org-agenda-mode-map "\C-c\C-x\C-x" 'org-agenda-clock-cancel)
19706 (org-defkey org-agenda-mode-map "X" 'org-agenda-clock-cancel)
19707 (org-defkey org-agenda-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19708 (org-defkey org-agenda-mode-map "J" 'org-clock-goto)
19709 (org-defkey org-agenda-mode-map "+" 'org-agenda-priority-up)
19710 (org-defkey org-agenda-mode-map "-" 'org-agenda-priority-down)
19711 (org-defkey org-agenda-mode-map [(shift up)] 'org-agenda-priority-up)
19712 (org-defkey org-agenda-mode-map [(shift down)] 'org-agenda-priority-down)
19713 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
19714 (org-defkey org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
19715 (org-defkey org-agenda-mode-map [(right)] 'org-agenda-later)
19716 (org-defkey org-agenda-mode-map [(left)] 'org-agenda-earlier)
19717 (org-defkey org-agenda-mode-map "\C-c\C-x\C-c" 'org-agenda-columns)
19719 (org-defkey org-agenda-mode-map "[" 'org-agenda-manipulate-query-add)
19720 (org-defkey org-agenda-mode-map "]" 'org-agenda-manipulate-query-subtract)
19721 (org-defkey org-agenda-mode-map "{" 'org-agenda-manipulate-query-add-re)
19722 (org-defkey org-agenda-mode-map "}" 'org-agenda-manipulate-query-subtract-re)
19724 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
19725 "Local keymap for agenda entries from Org-mode.")
19727 (org-defkey org-agenda-keymap
19728 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
19729 (org-defkey org-agenda-keymap
19730 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
19731 (when org-agenda-mouse-1-follows-link
19732 (org-defkey org-agenda-keymap [follow-link] 'mouse-face))
19733 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
19734 '("Agenda"
19735 ("Agenda Files")
19736 "--"
19737 ["Show" org-agenda-show t]
19738 ["Go To (other window)" org-agenda-goto t]
19739 ["Go To (this window)" org-agenda-switch-to t]
19740 ["Follow Mode" org-agenda-follow-mode
19741 :style toggle :selected org-agenda-follow-mode :active t]
19742 ["Tree to indirect frame" org-agenda-tree-to-indirect-buffer t]
19743 "--"
19744 ["Cycle TODO" org-agenda-todo t]
19745 ["Archive subtree" org-agenda-archive t]
19746 ["Delete subtree" org-agenda-kill t]
19747 "--"
19748 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
19749 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
19750 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
19751 ["Jump to date" org-agenda-goto-date (org-agenda-check-type nil 'agenda)]
19752 "--"
19753 ("Tags and Properties"
19754 ["Show all Tags" org-agenda-show-tags t]
19755 ["Set Tags current line" org-agenda-set-tags (not (org-region-active-p))]
19756 ["Change tag in region" org-agenda-set-tags (org-region-active-p)]
19757 "--"
19758 ["Column View" org-columns t])
19759 ("Date/Schedule"
19760 ["Schedule" org-agenda-schedule t]
19761 ["Set Deadline" org-agenda-deadline t]
19762 "--"
19763 ["Change Date +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
19764 ["Change Date -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
19765 ["Change Date to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
19766 ("Clock"
19767 ["Clock in" org-agenda-clock-in t]
19768 ["Clock out" org-agenda-clock-out t]
19769 ["Clock cancel" org-agenda-clock-cancel t]
19770 ["Goto running clock" org-clock-goto t])
19771 ("Priority"
19772 ["Set Priority" org-agenda-priority t]
19773 ["Increase Priority" org-agenda-priority-up t]
19774 ["Decrease Priority" org-agenda-priority-down t]
19775 ["Show Priority" org-agenda-show-priority t])
19776 ("Calendar/Diary"
19777 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
19778 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
19779 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
19780 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
19781 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
19782 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)]
19783 "--"
19784 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t])
19785 "--"
19786 ("View"
19787 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
19788 :style radio :selected (equal org-agenda-ndays 1)]
19789 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
19790 :style radio :selected (equal org-agenda-ndays 7)]
19791 ["Month View" org-agenda-month-view :active (org-agenda-check-type nil 'agenda)
19792 :style radio :selected (member org-agenda-ndays '(28 29 30 31))]
19793 ["Year View" org-agenda-year-view :active (org-agenda-check-type nil 'agenda)
19794 :style radio :selected (member org-agenda-ndays '(365 366))]
19795 "--"
19796 ["Show Logbook entries" org-agenda-log-mode
19797 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
19798 ["Include Diary" org-agenda-toggle-diary
19799 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
19800 ["Use Time Grid" org-agenda-toggle-time-grid
19801 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)])
19802 ["Write view to file" org-write-agenda t]
19803 ["Rebuild buffer" org-agenda-redo t]
19804 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
19805 "--"
19806 ["Undo Remote Editing" org-agenda-undo org-agenda-undo-list]
19807 "--"
19808 ["Quit" org-agenda-quit t]
19809 ["Exit and Release Buffers" org-agenda-exit t]
19812 ;;; Agenda undo
19814 (defvar org-agenda-allow-remote-undo t
19815 "Non-nil means, allow remote undo from the agenda buffer.")
19816 (defvar org-agenda-undo-list nil
19817 "List of undoable operations in the agenda since last refresh.")
19818 (defvar org-agenda-undo-has-started-in nil
19819 "Buffers that have already seen `undo-start' in the current undo sequence.")
19820 (defvar org-agenda-pending-undo-list nil
19821 "In a series of undo commands, this is the list of remaning undo items.")
19823 (defmacro org-if-unprotected (&rest body)
19824 "Execute BODY if there is no `org-protected' text property at point."
19825 (declare (debug t))
19826 `(unless (get-text-property (point) 'org-protected)
19827 ,@body))
19829 (defmacro org-with-remote-undo (_buffer &rest _body)
19830 "Execute BODY while recording undo information in two buffers."
19831 (declare (indent 1) (debug t))
19832 `(let ((_cline (org-current-line))
19833 (_cmd this-command)
19834 (_buf1 (current-buffer))
19835 (_buf2 ,_buffer)
19836 (_undo1 buffer-undo-list)
19837 (_undo2 (with-current-buffer ,_buffer buffer-undo-list))
19838 _c1 _c2)
19839 ,@_body
19840 (when org-agenda-allow-remote-undo
19841 (setq _c1 (org-verify-change-for-undo
19842 _undo1 (with-current-buffer _buf1 buffer-undo-list))
19843 _c2 (org-verify-change-for-undo
19844 _undo2 (with-current-buffer _buf2 buffer-undo-list)))
19845 (when (or _c1 _c2)
19846 ;; make sure there are undo boundaries
19847 (and _c1 (with-current-buffer _buf1 (undo-boundary)))
19848 (and _c2 (with-current-buffer _buf2 (undo-boundary)))
19849 ;; remember which buffer to undo
19850 (push (list _cmd _cline _buf1 _c1 _buf2 _c2)
19851 org-agenda-undo-list)))))
19853 (defun org-agenda-undo ()
19854 "Undo a remote editing step in the agenda.
19855 This undoes changes both in the agenda buffer and in the remote buffer
19856 that have been changed along."
19857 (interactive)
19858 (or org-agenda-allow-remote-undo
19859 (error "Check the variable `org-agenda-allow-remote-undo' to activate remote undo."))
19860 (if (not (eq this-command last-command))
19861 (setq org-agenda-undo-has-started-in nil
19862 org-agenda-pending-undo-list org-agenda-undo-list))
19863 (if (not org-agenda-pending-undo-list)
19864 (error "No further undo information"))
19865 (let* ((entry (pop org-agenda-pending-undo-list))
19866 buf line cmd rembuf)
19867 (setq cmd (pop entry) line (pop entry))
19868 (setq rembuf (nth 2 entry))
19869 (org-with-remote-undo rembuf
19870 (while (bufferp (setq buf (pop entry)))
19871 (if (pop entry)
19872 (with-current-buffer buf
19873 (let ((last-undo-buffer buf)
19874 (inhibit-read-only t))
19875 (unless (memq buf org-agenda-undo-has-started-in)
19876 (push buf org-agenda-undo-has-started-in)
19877 (make-local-variable 'pending-undo-list)
19878 (undo-start))
19879 (while (and pending-undo-list
19880 (listp pending-undo-list)
19881 (not (car pending-undo-list)))
19882 (pop pending-undo-list))
19883 (undo-more 1))))))
19884 (goto-line line)
19885 (message "`%s' undone (buffer %s)" cmd (buffer-name rembuf))))
19887 (defun org-verify-change-for-undo (l1 l2)
19888 "Verify that a real change occurred between the undo lists L1 and L2."
19889 (while (and l1 (listp l1) (null (car l1))) (pop l1))
19890 (while (and l2 (listp l2) (null (car l2))) (pop l2))
19891 (not (eq l1 l2)))
19893 ;;; Agenda dispatch
19895 (defvar org-agenda-restrict nil)
19896 (defvar org-agenda-restrict-begin (make-marker))
19897 (defvar org-agenda-restrict-end (make-marker))
19898 (defvar org-agenda-last-dispatch-buffer nil)
19899 (defvar org-agenda-overriding-restriction nil)
19901 ;;;###autoload
19902 (defun org-agenda (arg &optional keys restriction)
19903 "Dispatch agenda commands to collect entries to the agenda buffer.
19904 Prompts for a command to execute. Any prefix arg will be passed
19905 on to the selected command. The default selections are:
19907 a Call `org-agenda-list' to display the agenda for current day or week.
19908 t Call `org-todo-list' to display the global todo list.
19909 T Call `org-todo-list' to display the global todo list, select only
19910 entries with a specific TODO keyword (the user gets a prompt).
19911 m Call `org-tags-view' to display headlines with tags matching
19912 a condition (the user is prompted for the condition).
19913 M Like `m', but select only TODO entries, no ordinary headlines.
19914 L Create a timeline for the current buffer.
19915 e Export views to associated files.
19917 More commands can be added by configuring the variable
19918 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
19919 searches can be pre-defined in this way.
19921 If the current buffer is in Org-mode and visiting a file, you can also
19922 first press `<' once to indicate that the agenda should be temporarily
19923 \(until the next use of \\[org-agenda]) restricted to the current file.
19924 Pressing `<' twice means to restrict to the current subtree or region
19925 \(if active)."
19926 (interactive "P")
19927 (catch 'exit
19928 (let* ((prefix-descriptions nil)
19929 (org-agenda-custom-commands-orig org-agenda-custom-commands)
19930 (org-agenda-custom-commands
19931 ;; normalize different versions
19932 (delq nil
19933 (mapcar
19934 (lambda (x)
19935 (cond ((stringp (cdr x))
19936 (push x prefix-descriptions)
19937 nil)
19938 ((stringp (nth 1 x)) x)
19939 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
19940 (t (cons (car x) (cons "" (cdr x))))))
19941 org-agenda-custom-commands)))
19942 (buf (current-buffer))
19943 (bfn (buffer-file-name (buffer-base-buffer)))
19944 entry key type match lprops ans)
19945 ;; Turn off restriction unless there is an overriding one
19946 (unless org-agenda-overriding-restriction
19947 (put 'org-agenda-files 'org-restrict nil)
19948 (setq org-agenda-restrict nil)
19949 (move-marker org-agenda-restrict-begin nil)
19950 (move-marker org-agenda-restrict-end nil))
19951 ;; Delete old local properties
19952 (put 'org-agenda-redo-command 'org-lprops nil)
19953 ;; Remember where this call originated
19954 (setq org-agenda-last-dispatch-buffer (current-buffer))
19955 (unless keys
19956 (setq ans (org-agenda-get-restriction-and-command prefix-descriptions)
19957 keys (car ans)
19958 restriction (cdr ans)))
19959 ;; Estabish the restriction, if any
19960 (when (and (not org-agenda-overriding-restriction) restriction)
19961 (put 'org-agenda-files 'org-restrict (list bfn))
19962 (cond
19963 ((eq restriction 'region)
19964 (setq org-agenda-restrict t)
19965 (move-marker org-agenda-restrict-begin (region-beginning))
19966 (move-marker org-agenda-restrict-end (region-end)))
19967 ((eq restriction 'subtree)
19968 (save-excursion
19969 (setq org-agenda-restrict t)
19970 (org-back-to-heading t)
19971 (move-marker org-agenda-restrict-begin (point))
19972 (move-marker org-agenda-restrict-end
19973 (progn (org-end-of-subtree t)))))))
19975 (require 'calendar) ; FIXME: can we avoid this for some commands?
19976 ;; For example the todo list should not need it (but does...)
19977 (cond
19978 ((setq entry (assoc keys org-agenda-custom-commands))
19979 (if (or (symbolp (nth 2 entry)) (functionp (nth 2 entry)))
19980 (progn
19981 (setq type (nth 2 entry) match (nth 3 entry) lprops (nth 4 entry))
19982 (put 'org-agenda-redo-command 'org-lprops lprops)
19983 (cond
19984 ((eq type 'agenda)
19985 (org-let lprops '(org-agenda-list current-prefix-arg)))
19986 ((eq type 'alltodo)
19987 (org-let lprops '(org-todo-list current-prefix-arg)))
19988 ((eq type 'search)
19989 (org-let lprops '(org-search-view current-prefix-arg match)))
19990 ((eq type 'stuck)
19991 (org-let lprops '(org-agenda-list-stuck-projects
19992 current-prefix-arg)))
19993 ((eq type 'tags)
19994 (org-let lprops '(org-tags-view current-prefix-arg match)))
19995 ((eq type 'tags-todo)
19996 (org-let lprops '(org-tags-view '(4) match)))
19997 ((eq type 'todo)
19998 (org-let lprops '(org-todo-list match)))
19999 ((eq type 'tags-tree)
20000 (org-check-for-org-mode)
20001 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
20002 ((eq type 'todo-tree)
20003 (org-check-for-org-mode)
20004 (org-let lprops
20005 '(org-occur (concat "^" outline-regexp "[ \t]*"
20006 (regexp-quote match) "\\>"))))
20007 ((eq type 'occur-tree)
20008 (org-check-for-org-mode)
20009 (org-let lprops '(org-occur match)))
20010 ((functionp type)
20011 (org-let lprops '(funcall type match)))
20012 ((fboundp type)
20013 (org-let lprops '(funcall type match)))
20014 (t (error "Invalid custom agenda command type %s" type))))
20015 (org-run-agenda-series (nth 1 entry) (cddr entry))))
20016 ((equal keys "C")
20017 (setq org-agenda-custom-commands org-agenda-custom-commands-orig)
20018 (customize-variable 'org-agenda-custom-commands))
20019 ((equal keys "a") (call-interactively 'org-agenda-list))
20020 ((equal keys "s") (call-interactively 'org-search-view))
20021 ((equal keys "t") (call-interactively 'org-todo-list))
20022 ((equal keys "T") (org-call-with-arg 'org-todo-list (or arg '(4))))
20023 ((equal keys "m") (call-interactively 'org-tags-view))
20024 ((equal keys "M") (org-call-with-arg 'org-tags-view (or arg '(4))))
20025 ((equal keys "e") (call-interactively 'org-store-agenda-views))
20026 ((equal keys "L")
20027 (unless (org-mode-p)
20028 (error "This is not an Org-mode file"))
20029 (unless restriction
20030 (put 'org-agenda-files 'org-restrict (list bfn))
20031 (org-call-with-arg 'org-timeline arg)))
20032 ((equal keys "#") (call-interactively 'org-agenda-list-stuck-projects))
20033 ((equal keys "/") (call-interactively 'org-occur-in-agenda-files))
20034 ((equal keys "!") (customize-variable 'org-stuck-projects))
20035 (t (error "Invalid agenda key"))))))
20037 (defun org-agenda-normalize-custom-commands (cmds)
20038 (delq nil
20039 (mapcar
20040 (lambda (x)
20041 (cond ((stringp (cdr x)) nil)
20042 ((stringp (nth 1 x)) x)
20043 ((not (nth 1 x)) (cons (car x) (cons "" (cddr x))))
20044 (t (cons (car x) (cons "" (cdr x))))))
20045 cmds)))
20047 (defun org-agenda-get-restriction-and-command (prefix-descriptions)
20048 "The user interface for selecting an agenda command."
20049 (catch 'exit
20050 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
20051 (restrict-ok (and bfn (org-mode-p)))
20052 (region-p (org-region-active-p))
20053 (custom org-agenda-custom-commands)
20054 (selstring "")
20055 restriction second-time
20056 c entry key type match prefixes rmheader header-end custom1 desc)
20057 (save-window-excursion
20058 (delete-other-windows)
20059 (org-switch-to-buffer-other-window " *Agenda Commands*")
20060 (erase-buffer)
20061 (insert (eval-when-compile
20062 (let ((header
20064 Press key for an agenda command: < Buffer,subtree/region restriction
20065 -------------------------------- > Remove restriction
20066 a Agenda for current week or day e Export agenda views
20067 t List of all TODO entries T Entries with special TODO kwd
20068 m Match a TAGS query M Like m, but only TODO entries
20069 L Timeline for current buffer # List stuck projects (!=configure)
20070 s Search for keywords C Configure custom agenda commands
20071 / Multi-occur
20073 (start 0))
20074 (while (string-match
20075 "\\(^\\| \\|(\\)\\(\\S-\\)\\( \\|=\\)"
20076 header start)
20077 (setq start (match-end 0))
20078 (add-text-properties (match-beginning 2) (match-end 2)
20079 '(face bold) header))
20080 header)))
20081 (setq header-end (move-marker (make-marker) (point)))
20082 (while t
20083 (setq custom1 custom)
20084 (when (eq rmheader t)
20085 (goto-line 1)
20086 (re-search-forward ":" nil t)
20087 (delete-region (match-end 0) (point-at-eol))
20088 (forward-char 1)
20089 (looking-at "-+")
20090 (delete-region (match-end 0) (point-at-eol))
20091 (move-marker header-end (match-end 0)))
20092 (goto-char header-end)
20093 (delete-region (point) (point-max))
20094 (while (setq entry (pop custom1))
20095 (setq key (car entry) desc (nth 1 entry)
20096 type (nth 2 entry) match (nth 3 entry))
20097 (if (> (length key) 1)
20098 (add-to-list 'prefixes (string-to-char key))
20099 (insert
20100 (format
20101 "\n%-4s%-14s: %s"
20102 (org-add-props (copy-sequence key)
20103 '(face bold))
20104 (cond
20105 ((string-match "\\S-" desc) desc)
20106 ((eq type 'agenda) "Agenda for current week or day")
20107 ((eq type 'alltodo) "List of all TODO entries")
20108 ((eq type 'search) "Word search")
20109 ((eq type 'stuck) "List of stuck projects")
20110 ((eq type 'todo) "TODO keyword")
20111 ((eq type 'tags) "Tags query")
20112 ((eq type 'tags-todo) "Tags (TODO)")
20113 ((eq type 'tags-tree) "Tags tree")
20114 ((eq type 'todo-tree) "TODO kwd tree")
20115 ((eq type 'occur-tree) "Occur tree")
20116 ((functionp type) (if (symbolp type)
20117 (symbol-name type)
20118 "Lambda expression"))
20119 (t "???"))
20120 (cond
20121 ((stringp match)
20122 (org-add-props match nil 'face 'org-warning))
20123 (match
20124 (format "set of %d commands" (length match)))
20125 (t ""))))))
20126 (when prefixes
20127 (mapc (lambda (x)
20128 (insert
20129 (format "\n%s %s"
20130 (org-add-props (char-to-string x)
20131 nil 'face 'bold)
20132 (or (cdr (assoc (concat selstring (char-to-string x))
20133 prefix-descriptions))
20134 "Prefix key"))))
20135 prefixes))
20136 (goto-char (point-min))
20137 (when (fboundp 'fit-window-to-buffer)
20138 (if second-time
20139 (if (not (pos-visible-in-window-p (point-max)))
20140 (fit-window-to-buffer))
20141 (setq second-time t)
20142 (fit-window-to-buffer)))
20143 (message "Press key for agenda command%s:"
20144 (if (or restrict-ok org-agenda-overriding-restriction)
20145 (if org-agenda-overriding-restriction
20146 " (restriction lock active)"
20147 (if restriction
20148 (format " (restricted to %s)" restriction)
20149 " (unrestricted)"))
20150 ""))
20151 (setq c (read-char-exclusive))
20152 (message "")
20153 (cond
20154 ((assoc (char-to-string c) custom)
20155 (setq selstring (concat selstring (char-to-string c)))
20156 (throw 'exit (cons selstring restriction)))
20157 ((memq c prefixes)
20158 (setq selstring (concat selstring (char-to-string c))
20159 prefixes nil
20160 rmheader (or rmheader t)
20161 custom (delq nil (mapcar
20162 (lambda (x)
20163 (if (or (= (length (car x)) 1)
20164 (/= (string-to-char (car x)) c))
20166 (cons (substring (car x) 1) (cdr x))))
20167 custom))))
20168 ((and (not restrict-ok) (memq c '(?1 ?0 ?<)))
20169 (message "Restriction is only possible in Org-mode buffers")
20170 (ding) (sit-for 1))
20171 ((eq c ?1)
20172 (org-agenda-remove-restriction-lock 'noupdate)
20173 (setq restriction 'buffer))
20174 ((eq c ?0)
20175 (org-agenda-remove-restriction-lock 'noupdate)
20176 (setq restriction (if region-p 'region 'subtree)))
20177 ((eq c ?<)
20178 (org-agenda-remove-restriction-lock 'noupdate)
20179 (setq restriction
20180 (cond
20181 ((eq restriction 'buffer)
20182 (if region-p 'region 'subtree))
20183 ((memq restriction '(subtree region))
20184 nil)
20185 (t 'buffer))))
20186 ((eq c ?>)
20187 (org-agenda-remove-restriction-lock 'noupdate)
20188 (setq restriction nil))
20189 ((and (equal selstring "") (memq c '(?s ?a ?t ?m ?L ?C ?e ?T ?M ?# ?! ?/)))
20190 (throw 'exit (cons (setq selstring (char-to-string c)) restriction)))
20191 ((and (> (length selstring) 0) (eq c ?\d))
20192 (delete-window)
20193 (org-agenda-get-restriction-and-command prefix-descriptions))
20195 ((equal c ?q) (error "Abort"))
20196 (t (error "Invalid key %c" c))))))))
20198 (defun org-run-agenda-series (name series)
20199 (org-prepare-agenda name)
20200 (let* ((org-agenda-multi t)
20201 (redo (list 'org-run-agenda-series name (list 'quote series)))
20202 (cmds (car series))
20203 (gprops (nth 1 series))
20204 match ;; The byte compiler incorrectly complains about this. Keep it!
20205 cmd type lprops)
20206 (while (setq cmd (pop cmds))
20207 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
20208 (cond
20209 ((eq type 'agenda)
20210 (org-let2 gprops lprops
20211 '(call-interactively 'org-agenda-list)))
20212 ((eq type 'alltodo)
20213 (org-let2 gprops lprops
20214 '(call-interactively 'org-todo-list)))
20215 ((eq type 'search)
20216 (org-let2 gprops lprops
20217 '(org-search-view current-prefix-arg match)))
20218 ((eq type 'stuck)
20219 (org-let2 gprops lprops
20220 '(call-interactively 'org-agenda-list-stuck-projects)))
20221 ((eq type 'tags)
20222 (org-let2 gprops lprops
20223 '(org-tags-view current-prefix-arg match)))
20224 ((eq type 'tags-todo)
20225 (org-let2 gprops lprops
20226 '(org-tags-view '(4) match)))
20227 ((eq type 'todo)
20228 (org-let2 gprops lprops
20229 '(org-todo-list match)))
20230 ((fboundp type)
20231 (org-let2 gprops lprops
20232 '(funcall type match)))
20233 (t (error "Invalid type in command series"))))
20234 (widen)
20235 (setq org-agenda-redo-command redo)
20236 (goto-char (point-min)))
20237 (org-finalize-agenda))
20239 ;;;###autoload
20240 (defmacro org-batch-agenda (cmd-key &rest parameters)
20241 "Run an agenda command in batch mode and send the result to STDOUT.
20242 If CMD-KEY is a string of length 1, it is used as a key in
20243 `org-agenda-custom-commands' and triggers this command. If it is a
20244 longer string it is used as a tags/todo match string.
20245 Paramters are alternating variable names and values that will be bound
20246 before running the agenda command."
20247 (let (pars)
20248 (while parameters
20249 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20250 (if (> (length cmd-key) 2)
20251 (eval (list 'let (nreverse pars)
20252 (list 'org-tags-view nil cmd-key)))
20253 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20254 (set-buffer org-agenda-buffer-name)
20255 (princ (org-encode-for-stdout (buffer-string)))))
20257 (defun org-encode-for-stdout (string)
20258 (if (fboundp 'encode-coding-string)
20259 (encode-coding-string string buffer-file-coding-system)
20260 string))
20262 (defvar org-agenda-info nil)
20264 ;;;###autoload
20265 (defmacro org-batch-agenda-csv (cmd-key &rest parameters)
20266 "Run an agenda command in batch mode and send the result to STDOUT.
20267 If CMD-KEY is a string of length 1, it is used as a key in
20268 `org-agenda-custom-commands' and triggers this command. If it is a
20269 longer string it is used as a tags/todo match string.
20270 Paramters are alternating variable names and values that will be bound
20271 before running the agenda command.
20273 The output gives a line for each selected agenda item. Each
20274 item is a list of comma-separated values, like this:
20276 category,head,type,todo,tags,date,time,extra,priority-l,priority-n
20278 category The category of the item
20279 head The headline, without TODO kwd, TAGS and PRIORITY
20280 type The type of the agenda entry, can be
20281 todo selected in TODO match
20282 tagsmatch selected in tags match
20283 diary imported from diary
20284 deadline a deadline on given date
20285 scheduled scheduled on given date
20286 timestamp entry has timestamp on given date
20287 closed entry was closed on given date
20288 upcoming-deadline warning about deadline
20289 past-scheduled forwarded scheduled item
20290 block entry has date block including g. date
20291 todo The todo keyword, if any
20292 tags All tags including inherited ones, separated by colons
20293 date The relevant date, like 2007-2-14
20294 time The time, like 15:00-16:50
20295 extra Sting with extra planning info
20296 priority-l The priority letter if any was given
20297 priority-n The computed numerical priority
20298 agenda-day The day in the agenda where this is listed"
20300 (let (pars)
20301 (while parameters
20302 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20303 (push (list 'org-agenda-remove-tags t) pars)
20304 (if (> (length cmd-key) 2)
20305 (eval (list 'let (nreverse pars)
20306 (list 'org-tags-view nil cmd-key)))
20307 (eval (list 'let (nreverse pars) (list 'org-agenda nil cmd-key))))
20308 (set-buffer org-agenda-buffer-name)
20309 (let* ((lines (org-split-string (buffer-string) "\n"))
20310 line)
20311 (while (setq line (pop lines))
20312 (catch 'next
20313 (if (not (get-text-property 0 'org-category line)) (throw 'next nil))
20314 (setq org-agenda-info
20315 (org-fix-agenda-info (text-properties-at 0 line)))
20316 (princ
20317 (org-encode-for-stdout
20318 (mapconcat 'org-agenda-export-csv-mapper
20319 '(org-category txt type todo tags date time-of-day extra
20320 priority-letter priority agenda-day)
20321 ",")))
20322 (princ "\n"))))))
20324 (defun org-fix-agenda-info (props)
20325 "Make sure all properties on an agenda item have a canonical form,
20326 so the export commands can easily use it."
20327 (let (tmp re)
20328 (when (setq tmp (plist-get props 'tags))
20329 (setq props (plist-put props 'tags (mapconcat 'identity tmp ":"))))
20330 (when (setq tmp (plist-get props 'date))
20331 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20332 (let ((calendar-date-display-form '(year "-" month "-" day)))
20333 '((format "%4d, %9s %2s, %4s" dayname monthname day year))
20335 (setq tmp (calendar-date-string tmp)))
20336 (setq props (plist-put props 'date tmp)))
20337 (when (setq tmp (plist-get props 'day))
20338 (if (integerp tmp) (setq tmp (calendar-gregorian-from-absolute tmp)))
20339 (let ((calendar-date-display-form '(year "-" month "-" day)))
20340 (setq tmp (calendar-date-string tmp)))
20341 (setq props (plist-put props 'day tmp))
20342 (setq props (plist-put props 'agenda-day tmp)))
20343 (when (setq tmp (plist-get props 'txt))
20344 (when (string-match "\\[#\\([A-Z0-9]\\)\\] ?" tmp)
20345 (plist-put props 'priority-letter (match-string 1 tmp))
20346 (setq tmp (replace-match "" t t tmp)))
20347 (when (and (setq re (plist-get props 'org-todo-regexp))
20348 (setq re (concat "\\`\\.*" re " ?"))
20349 (string-match re tmp))
20350 (plist-put props 'todo (match-string 1 tmp))
20351 (setq tmp (replace-match "" t t tmp)))
20352 (plist-put props 'txt tmp)))
20353 props)
20355 (defun org-agenda-export-csv-mapper (prop)
20356 (let ((res (plist-get org-agenda-info prop)))
20357 (setq res
20358 (cond
20359 ((not res) "")
20360 ((stringp res) res)
20361 (t (prin1-to-string res))))
20362 (while (string-match "," res)
20363 (setq res (replace-match ";" t t res)))
20364 (org-trim res)))
20367 ;;;###autoload
20368 (defun org-store-agenda-views (&rest parameters)
20369 (interactive)
20370 (eval (list 'org-batch-store-agenda-views)))
20372 ;; FIXME, why is this a macro?????
20373 ;;;###autoload
20374 (defmacro org-batch-store-agenda-views (&rest parameters)
20375 "Run all custom agenda commands that have a file argument."
20376 (let ((cmds (org-agenda-normalize-custom-commands org-agenda-custom-commands))
20377 (pop-up-frames nil)
20378 (dir default-directory)
20379 pars cmd thiscmdkey files opts)
20380 (while parameters
20381 (push (list (pop parameters) (if parameters (pop parameters))) pars))
20382 (setq pars (reverse pars))
20383 (save-window-excursion
20384 (while cmds
20385 (setq cmd (pop cmds)
20386 thiscmdkey (car cmd)
20387 opts (nth 4 cmd)
20388 files (nth 5 cmd))
20389 (if (stringp files) (setq files (list files)))
20390 (when files
20391 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20392 (list 'org-agenda nil thiscmdkey)))
20393 (set-buffer org-agenda-buffer-name)
20394 (while files
20395 (eval (list 'let (append org-agenda-exporter-settings opts pars)
20396 (list 'org-write-agenda
20397 (expand-file-name (pop files) dir) t))))
20398 (and (get-buffer org-agenda-buffer-name)
20399 (kill-buffer org-agenda-buffer-name)))))))
20401 (defun org-write-agenda (file &optional nosettings)
20402 "Write the current buffer (an agenda view) as a file.
20403 Depending on the extension of the file name, plain text (.txt),
20404 HTML (.html or .htm) or Postscript (.ps) is produced.
20405 If the extension is .ics, run icalendar export over all files used
20406 to construct the agenda and limit the export to entries listed in the
20407 agenda now.
20408 If NOSETTINGS is given, do not scope the settings of
20409 `org-agenda-exporter-settings' into the export commands. This is used when
20410 the settings have already been scoped and we do not wish to overrule other,
20411 higher priority settings."
20412 (interactive "FWrite agenda to file: ")
20413 (if (not (file-writable-p file))
20414 (error "Cannot write agenda to file %s" file))
20415 (cond
20416 ((string-match "\\.html?\\'" file) (require 'htmlize))
20417 ((string-match "\\.ps\\'" file) (require 'ps-print)))
20418 (org-let (if nosettings nil org-agenda-exporter-settings)
20419 '(save-excursion
20420 (save-window-excursion
20421 (cond
20422 ((string-match "\\.html?\\'" file)
20423 (set-buffer (htmlize-buffer (current-buffer)))
20425 (when (and org-agenda-export-html-style
20426 (string-match "<style>" org-agenda-export-html-style))
20427 ;; replace <style> section with org-agenda-export-html-style
20428 (goto-char (point-min))
20429 (kill-region (- (search-forward "<style") 6)
20430 (search-forward "</style>"))
20431 (insert org-agenda-export-html-style))
20432 (write-file file)
20433 (kill-buffer (current-buffer))
20434 (message "HTML written to %s" file))
20435 ((string-match "\\.ps\\'" file)
20436 (ps-print-buffer-with-faces file)
20437 (message "Postscript written to %s" file))
20438 ((string-match "\\.ics\\'" file)
20439 (let ((org-agenda-marker-table
20440 (org-create-marker-find-array
20441 (org-agenda-collect-markers)))
20442 (org-icalendar-verify-function 'org-check-agenda-marker-table)
20443 (org-combined-agenda-icalendar-file file))
20444 (apply 'org-export-icalendar 'combine (org-agenda-files))))
20446 (let ((bs (buffer-string)))
20447 (find-file file)
20448 (insert bs)
20449 (save-buffer 0)
20450 (kill-buffer (current-buffer))
20451 (message "Plain text written to %s" file))))))
20452 (set-buffer org-agenda-buffer-name)))
20454 (defun org-agenda-collect-markers ()
20455 "Collect the markers pointing to entries in the agenda buffer."
20456 (let (m markers)
20457 (save-excursion
20458 (goto-char (point-min))
20459 (while (not (eobp))
20460 (when (setq m (or (get-text-property (point) 'org-hd-marker)
20461 (get-text-property (point) 'org-marker)))
20462 (push m markers))
20463 (beginning-of-line 2)))
20464 (nreverse markers)))
20466 (defun org-create-marker-find-array (marker-list)
20467 "Create a alist of files names with all marker positions in that file."
20468 (let (f tbl m a p)
20469 (while (setq m (pop marker-list))
20470 (setq p (marker-position m)
20471 f (buffer-file-name (or (buffer-base-buffer
20472 (marker-buffer m))
20473 (marker-buffer m))))
20474 (if (setq a (assoc f tbl))
20475 (push (marker-position m) (cdr a))
20476 (push (list f p) tbl)))
20477 (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
20478 tbl)))
20480 (defvar org-agenda-marker-table nil) ; dyamically scoped parameter
20481 (defun org-check-agenda-marker-table ()
20482 "Check of the current entry is on the marker list."
20483 (let ((file (buffer-file-name (or (buffer-base-buffer) (current-buffer))))
20485 (and (setq a (assoc file org-agenda-marker-table))
20486 (save-match-data
20487 (save-excursion
20488 (org-back-to-heading t)
20489 (member (point) (cdr a)))))))
20491 (defmacro org-no-read-only (&rest body)
20492 "Inhibit read-only for BODY."
20493 `(let ((inhibit-read-only t)) ,@body))
20495 (defun org-check-for-org-mode ()
20496 "Make sure current buffer is in org-mode. Error if not."
20497 (or (org-mode-p)
20498 (error "Cannot execute org-mode agenda command on buffer in %s."
20499 major-mode)))
20501 (defun org-fit-agenda-window ()
20502 "Fit the window to the buffer size."
20503 (and (memq org-agenda-window-setup '(reorganize-frame))
20504 (fboundp 'fit-window-to-buffer)
20505 (fit-window-to-buffer
20507 (floor (* (frame-height) (cdr org-agenda-window-frame-fractions)))
20508 (floor (* (frame-height) (car org-agenda-window-frame-fractions))))))
20510 ;;; Agenda file list
20512 (defun org-agenda-files (&optional unrestricted)
20513 "Get the list of agenda files.
20514 Optional UNRESTRICTED means return the full list even if a restriction
20515 is currently in place."
20516 (let ((files
20517 (cond
20518 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
20519 ((stringp org-agenda-files) (org-read-agenda-file-list))
20520 ((listp org-agenda-files) org-agenda-files)
20521 (t (error "Invalid value of `org-agenda-files'")))))
20522 (setq files (apply 'append
20523 (mapcar (lambda (f)
20524 (if (file-directory-p f)
20525 (directory-files f t
20526 org-agenda-file-regexp)
20527 (list f)))
20528 files)))
20529 (if org-agenda-skip-unavailable-files
20530 (delq nil
20531 (mapcar (function
20532 (lambda (file)
20533 (and (file-readable-p file) file)))
20534 files))
20535 files))) ; `org-check-agenda-file' will remove them from the list
20537 (defun org-edit-agenda-file-list ()
20538 "Edit the list of agenda files.
20539 Depending on setup, this either uses customize to edit the variable
20540 `org-agenda-files', or it visits the file that is holding the list. In the
20541 latter case, the buffer is set up in a way that saving it automatically kills
20542 the buffer and restores the previous window configuration."
20543 (interactive)
20544 (if (stringp org-agenda-files)
20545 (let ((cw (current-window-configuration)))
20546 (find-file org-agenda-files)
20547 (org-set-local 'org-window-configuration cw)
20548 (org-add-hook 'after-save-hook
20549 (lambda ()
20550 (set-window-configuration
20551 (prog1 org-window-configuration
20552 (kill-buffer (current-buffer))))
20553 (org-install-agenda-files-menu)
20554 (message "New agenda file list installed"))
20555 nil 'local)
20556 (message "%s" (substitute-command-keys
20557 "Edit list and finish with \\[save-buffer]")))
20558 (customize-variable 'org-agenda-files)))
20560 (defun org-store-new-agenda-file-list (list)
20561 "Set new value for the agenda file list and save it correcly."
20562 (if (stringp org-agenda-files)
20563 (let ((f org-agenda-files) b)
20564 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
20565 (with-temp-file f
20566 (insert (mapconcat 'identity list "\n") "\n")))
20567 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
20568 (setq org-agenda-files list)
20569 (customize-save-variable 'org-agenda-files org-agenda-files))))
20571 (defun org-read-agenda-file-list ()
20572 "Read the list of agenda files from a file."
20573 (when (stringp org-agenda-files)
20574 (with-temp-buffer
20575 (insert-file-contents org-agenda-files)
20576 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
20579 ;;;###autoload
20580 (defun org-cycle-agenda-files ()
20581 "Cycle through the files in `org-agenda-files'.
20582 If the current buffer visits an agenda file, find the next one in the list.
20583 If the current buffer does not, find the first agenda file."
20584 (interactive)
20585 (let* ((fs (org-agenda-files t))
20586 (files (append fs (list (car fs))))
20587 (tcf (if buffer-file-name (file-truename buffer-file-name)))
20588 file)
20589 (unless files (error "No agenda files"))
20590 (catch 'exit
20591 (while (setq file (pop files))
20592 (if (equal (file-truename file) tcf)
20593 (when (car files)
20594 (find-file (car files))
20595 (throw 'exit t))))
20596 (find-file (car fs)))
20597 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
20599 (defun org-agenda-file-to-front (&optional to-end)
20600 "Move/add the current file to the top of the agenda file list.
20601 If the file is not present in the list, it is added to the front. If it is
20602 present, it is moved there. With optional argument TO-END, add/move to the
20603 end of the list."
20604 (interactive "P")
20605 (let ((org-agenda-skip-unavailable-files nil)
20606 (file-alist (mapcar (lambda (x)
20607 (cons (file-truename x) x))
20608 (org-agenda-files t)))
20609 (ctf (file-truename buffer-file-name))
20610 x had)
20611 (setq x (assoc ctf file-alist) had x)
20613 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
20614 (if to-end
20615 (setq file-alist (append (delq x file-alist) (list x)))
20616 (setq file-alist (cons x (delq x file-alist))))
20617 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
20618 (org-install-agenda-files-menu)
20619 (message "File %s to %s of agenda file list"
20620 (if had "moved" "added") (if to-end "end" "front"))))
20622 (defun org-remove-file (&optional file)
20623 "Remove current file from the list of files in variable `org-agenda-files'.
20624 These are the files which are being checked for agenda entries.
20625 Optional argument FILE means, use this file instead of the current."
20626 (interactive)
20627 (let* ((org-agenda-skip-unavailable-files nil)
20628 (file (or file buffer-file-name))
20629 (true-file (file-truename file))
20630 (afile (abbreviate-file-name file))
20631 (files (delq nil (mapcar
20632 (lambda (x)
20633 (if (equal true-file
20634 (file-truename x))
20635 nil x))
20636 (org-agenda-files t)))))
20637 (if (not (= (length files) (length (org-agenda-files t))))
20638 (progn
20639 (org-store-new-agenda-file-list files)
20640 (org-install-agenda-files-menu)
20641 (message "Removed file: %s" afile))
20642 (message "File was not in list: %s (not removed)" afile))))
20644 (defun org-file-menu-entry (file)
20645 (vector file (list 'find-file file) t))
20647 (defun org-check-agenda-file (file)
20648 "Make sure FILE exists. If not, ask user what to do."
20649 (when (not (file-exists-p file))
20650 (message "non-existent file %s. [R]emove from list or [A]bort?"
20651 (abbreviate-file-name file))
20652 (let ((r (downcase (read-char-exclusive))))
20653 (cond
20654 ((equal r ?r)
20655 (org-remove-file file)
20656 (throw 'nextfile t))
20657 (t (error "Abort"))))))
20659 ;;; Agenda prepare and finalize
20661 (defvar org-agenda-multi nil) ; dynammically scoped
20662 (defvar org-agenda-buffer-name "*Org Agenda*")
20663 (defvar org-pre-agenda-window-conf nil)
20664 (defvar org-agenda-name nil)
20665 (defun org-prepare-agenda (&optional name)
20666 (setq org-todo-keywords-for-agenda nil)
20667 (setq org-done-keywords-for-agenda nil)
20668 (if org-agenda-multi
20669 (progn
20670 (setq buffer-read-only nil)
20671 (goto-char (point-max))
20672 (unless (or (bobp) org-agenda-compact-blocks)
20673 (insert "\n" (make-string (window-width) ?=) "\n"))
20674 (narrow-to-region (point) (point-max)))
20675 (org-agenda-reset-markers)
20676 (org-prepare-agenda-buffers (org-agenda-files))
20677 (setq org-todo-keywords-for-agenda
20678 (org-uniquify org-todo-keywords-for-agenda))
20679 (setq org-done-keywords-for-agenda
20680 (org-uniquify org-done-keywords-for-agenda))
20681 (let* ((abuf (get-buffer-create org-agenda-buffer-name))
20682 (awin (get-buffer-window abuf)))
20683 (cond
20684 ((equal (current-buffer) abuf) nil)
20685 (awin (select-window awin))
20686 ((not (setq org-pre-agenda-window-conf (current-window-configuration))))
20687 ((equal org-agenda-window-setup 'current-window)
20688 (switch-to-buffer abuf))
20689 ((equal org-agenda-window-setup 'other-window)
20690 (org-switch-to-buffer-other-window abuf))
20691 ((equal org-agenda-window-setup 'other-frame)
20692 (switch-to-buffer-other-frame abuf))
20693 ((equal org-agenda-window-setup 'reorganize-frame)
20694 (delete-other-windows)
20695 (org-switch-to-buffer-other-window abuf))))
20696 (setq buffer-read-only nil)
20697 (erase-buffer)
20698 (org-agenda-mode)
20699 (and name (not org-agenda-name)
20700 (org-set-local 'org-agenda-name name)))
20701 (setq buffer-read-only nil))
20703 (defun org-finalize-agenda ()
20704 "Finishing touch for the agenda buffer, called just before displaying it."
20705 (unless org-agenda-multi
20706 (save-excursion
20707 (let ((inhibit-read-only t))
20708 (goto-char (point-min))
20709 (while (org-activate-bracket-links (point-max))
20710 (add-text-properties (match-beginning 0) (match-end 0)
20711 '(face org-link)))
20712 (org-agenda-align-tags)
20713 (unless org-agenda-with-colors
20714 (remove-text-properties (point-min) (point-max) '(face nil))))
20715 (if (and (boundp 'org-overriding-columns-format)
20716 org-overriding-columns-format)
20717 (org-set-local 'org-overriding-columns-format
20718 org-overriding-columns-format))
20719 (if (and (boundp 'org-agenda-view-columns-initially)
20720 org-agenda-view-columns-initially)
20721 (org-agenda-columns))
20722 (when org-agenda-fontify-priorities
20723 (org-fontify-priorities))
20724 (run-hooks 'org-finalize-agenda-hook)
20725 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
20728 (defun org-fontify-priorities ()
20729 "Make highest priority lines bold, and lowest italic."
20730 (interactive)
20731 (mapc (lambda (o) (if (eq (org-overlay-get o 'org-type) 'org-priority)
20732 (org-delete-overlay o)))
20733 (org-overlays-in (point-min) (point-max)))
20734 (save-excursion
20735 (let ((inhibit-read-only t)
20736 b e p ov h l)
20737 (goto-char (point-min))
20738 (while (re-search-forward "\\[#\\(.\\)\\]" nil t)
20739 (setq h (or (get-char-property (point) 'org-highest-priority)
20740 org-highest-priority)
20741 l (or (get-char-property (point) 'org-lowest-priority)
20742 org-lowest-priority)
20743 p (string-to-char (match-string 1))
20744 b (match-beginning 0) e (point-at-eol)
20745 ov (org-make-overlay b e))
20746 (org-overlay-put
20747 ov 'face
20748 (cond ((listp org-agenda-fontify-priorities)
20749 (cdr (assoc p org-agenda-fontify-priorities)))
20750 ((equal p l) 'italic)
20751 ((equal p h) 'bold)))
20752 (org-overlay-put ov 'org-type 'org-priority)))))
20754 (defun org-prepare-agenda-buffers (files)
20755 "Create buffers for all agenda files, protect archived trees and comments."
20756 (interactive)
20757 (let ((pa '(:org-archived t))
20758 (pc '(:org-comment t))
20759 (pall '(:org-archived t :org-comment t))
20760 (inhibit-read-only t)
20761 (rea (concat ":" org-archive-tag ":"))
20762 bmp file re)
20763 (save-excursion
20764 (save-restriction
20765 (while (setq file (pop files))
20766 (if (bufferp file)
20767 (set-buffer file)
20768 (org-check-agenda-file file)
20769 (set-buffer (org-get-agenda-file-buffer file)))
20770 (widen)
20771 (setq bmp (buffer-modified-p))
20772 (org-refresh-category-properties)
20773 (setq org-todo-keywords-for-agenda
20774 (append org-todo-keywords-for-agenda org-todo-keywords-1))
20775 (setq org-done-keywords-for-agenda
20776 (append org-done-keywords-for-agenda org-done-keywords))
20777 (save-excursion
20778 (remove-text-properties (point-min) (point-max) pall)
20779 (when org-agenda-skip-archived-trees
20780 (goto-char (point-min))
20781 (while (re-search-forward rea nil t)
20782 (if (org-on-heading-p t)
20783 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
20784 (goto-char (point-min))
20785 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
20786 (while (re-search-forward re nil t)
20787 (add-text-properties
20788 (match-beginning 0) (org-end-of-subtree t) pc)))
20789 (set-buffer-modified-p bmp))))))
20791 (defvar org-agenda-skip-function nil
20792 "Function to be called at each match during agenda construction.
20793 If this function returns nil, the current match should not be skipped.
20794 Otherwise, the function must return a position from where the search
20795 should be continued.
20796 This may also be a Lisp form, it will be evaluated.
20797 Never set this variable using `setq' or so, because then it will apply
20798 to all future agenda commands. Instead, bind it with `let' to scope
20799 it dynamically into the agenda-constructing command. A good way to set
20800 it is through options in org-agenda-custom-commands.")
20802 (defun org-agenda-skip ()
20803 "Throw to `:skip' in places that should be skipped.
20804 Also moves point to the end of the skipped region, so that search can
20805 continue from there."
20806 (let ((p (point-at-bol)) to fp)
20807 (and org-agenda-skip-archived-trees
20808 (get-text-property p :org-archived)
20809 (org-end-of-subtree t)
20810 (throw :skip t))
20811 (and (get-text-property p :org-comment)
20812 (org-end-of-subtree t)
20813 (throw :skip t))
20814 (if (equal (char-after p) ?#) (throw :skip t))
20815 (when (and (or (setq fp (functionp org-agenda-skip-function))
20816 (consp org-agenda-skip-function))
20817 (setq to (save-excursion
20818 (save-match-data
20819 (if fp
20820 (funcall org-agenda-skip-function)
20821 (eval org-agenda-skip-function))))))
20822 (goto-char to)
20823 (throw :skip t))))
20825 (defvar org-agenda-markers nil
20826 "List of all currently active markers created by `org-agenda'.")
20827 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
20828 "Creation time of the last agenda marker.")
20830 (defun org-agenda-new-marker (&optional pos)
20831 "Return a new agenda marker.
20832 Org-mode keeps a list of these markers and resets them when they are
20833 no longer in use."
20834 (let ((m (copy-marker (or pos (point)))))
20835 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
20836 (push m org-agenda-markers)
20839 (defun org-agenda-reset-markers ()
20840 "Reset markers created by `org-agenda'."
20841 (while org-agenda-markers
20842 (move-marker (pop org-agenda-markers) nil)))
20844 (defun org-get-agenda-file-buffer (file)
20845 "Get a buffer visiting FILE. If the buffer needs to be created, add
20846 it to the list of buffers which might be released later."
20847 (let ((buf (org-find-base-buffer-visiting file)))
20848 (if buf
20849 buf ; just return it
20850 ;; Make a new buffer and remember it
20851 (setq buf (find-file-noselect file))
20852 (if buf (push buf org-agenda-new-buffers))
20853 buf)))
20855 (defun org-release-buffers (blist)
20856 "Release all buffers in list, asking the user for confirmation when needed.
20857 When a buffer is unmodified, it is just killed. When modified, it is saved
20858 \(if the user agrees) and then killed."
20859 (let (buf file)
20860 (while (setq buf (pop blist))
20861 (setq file (buffer-file-name buf))
20862 (when (and (buffer-modified-p buf)
20863 file
20864 (y-or-n-p (format "Save file %s? " file)))
20865 (with-current-buffer buf (save-buffer)))
20866 (kill-buffer buf))))
20868 (defun org-get-category (&optional pos)
20869 "Get the category applying to position POS."
20870 (get-text-property (or pos (point)) 'org-category))
20872 ;;; Agenda timeline
20874 (defvar org-agenda-only-exact-dates nil) ; dynamically scoped
20876 (defun org-timeline (&optional include-all)
20877 "Show a time-sorted view of the entries in the current org file.
20878 Only entries with a time stamp of today or later will be listed. With
20879 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
20880 under the current date.
20881 If the buffer contains an active region, only check the region for
20882 dates."
20883 (interactive "P")
20884 (require 'calendar)
20885 (org-compile-prefix-format 'timeline)
20886 (org-set-sorting-strategy 'timeline)
20887 (let* ((dopast t)
20888 (dotodo include-all)
20889 (doclosed org-agenda-show-log)
20890 (entry buffer-file-name)
20891 (date (calendar-current-date))
20892 (beg (if (org-region-active-p) (region-beginning) (point-min)))
20893 (end (if (org-region-active-p) (region-end) (point-max)))
20894 (day-numbers (org-get-all-dates beg end 'no-ranges
20895 t doclosed ; always include today
20896 org-timeline-show-empty-dates))
20897 (org-deadline-warning-days 0)
20898 (org-agenda-only-exact-dates t)
20899 (today (time-to-days (current-time)))
20900 (past t)
20901 args
20902 s e rtn d emptyp)
20903 (setq org-agenda-redo-command
20904 (list 'progn
20905 (list 'org-switch-to-buffer-other-window (current-buffer))
20906 (list 'org-timeline (list 'quote include-all))))
20907 (if (not dopast)
20908 ;; Remove past dates from the list of dates.
20909 (setq day-numbers (delq nil (mapcar (lambda(x)
20910 (if (>= x today) x nil))
20911 day-numbers))))
20912 (org-prepare-agenda (concat "Timeline "
20913 (file-name-nondirectory buffer-file-name)))
20914 (if doclosed (push :closed args))
20915 (push :timestamp args)
20916 (push :deadline args)
20917 (push :scheduled args)
20918 (push :sexp args)
20919 (if dotodo (push :todo args))
20920 (while (setq d (pop day-numbers))
20921 (if (and (listp d) (eq (car d) :omitted))
20922 (progn
20923 (setq s (point))
20924 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
20925 (put-text-property s (1- (point)) 'face 'org-agenda-structure))
20926 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
20927 (if (and (>= d today)
20928 dopast
20929 past)
20930 (progn
20931 (setq past nil)
20932 (insert (make-string 79 ?-) "\n")))
20933 (setq date (calendar-gregorian-from-absolute d))
20934 (setq s (point))
20935 (setq rtn (and (not emptyp)
20936 (apply 'org-agenda-get-day-entries entry
20937 date args)))
20938 (if (or rtn (equal d today) org-timeline-show-empty-dates)
20939 (progn
20940 (insert
20941 (if (stringp org-agenda-format-date)
20942 (format-time-string org-agenda-format-date
20943 (org-time-from-absolute date))
20944 (funcall org-agenda-format-date date))
20945 "\n")
20946 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
20947 (put-text-property s (1- (point)) 'org-date-line t)
20948 (if (equal d today)
20949 (put-text-property s (1- (point)) 'org-today t))
20950 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
20951 (put-text-property s (1- (point)) 'day d)))))
20952 (goto-char (point-min))
20953 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
20954 (point-min)))
20955 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
20956 (org-finalize-agenda)
20957 (setq buffer-read-only t)))
20959 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty pre-re)
20960 "Return a list of all relevant day numbers from BEG to END buffer positions.
20961 If NO-RANGES is non-nil, include only the start and end dates of a range,
20962 not every single day in the range. If FORCE-TODAY is non-nil, make
20963 sure that TODAY is included in the list. If INACTIVE is non-nil, also
20964 inactive time stamps (those in square brackets) are included.
20965 When EMPTY is non-nil, also include days without any entries."
20966 (let ((re (concat
20967 (if pre-re pre-re "")
20968 (if inactive org-ts-regexp-both org-ts-regexp)))
20969 dates dates1 date day day1 day2 ts1 ts2)
20970 (if force-today
20971 (setq dates (list (time-to-days (current-time)))))
20972 (save-excursion
20973 (goto-char beg)
20974 (while (re-search-forward re end t)
20975 (setq day (time-to-days (org-time-string-to-time
20976 (substring (match-string 1) 0 10))))
20977 (or (memq day dates) (push day dates)))
20978 (unless no-ranges
20979 (goto-char beg)
20980 (while (re-search-forward org-tr-regexp end t)
20981 (setq ts1 (substring (match-string 1) 0 10)
20982 ts2 (substring (match-string 2) 0 10)
20983 day1 (time-to-days (org-time-string-to-time ts1))
20984 day2 (time-to-days (org-time-string-to-time ts2)))
20985 (while (< (setq day1 (1+ day1)) day2)
20986 (or (memq day1 dates) (push day1 dates)))))
20987 (setq dates (sort dates '<))
20988 (when empty
20989 (while (setq day (pop dates))
20990 (setq day2 (car dates))
20991 (push day dates1)
20992 (when (and day2 empty)
20993 (if (or (eq empty t)
20994 (and (numberp empty) (<= (- day2 day) empty)))
20995 (while (< (setq day (1+ day)) day2)
20996 (push (list day) dates1))
20997 (push (cons :omitted (- day2 day)) dates1))))
20998 (setq dates (nreverse dates1)))
20999 dates)))
21001 ;;; Agenda Daily/Weekly
21003 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
21004 (defvar org-agenda-start-day nil) ; dynamically scoped parameter
21005 (defvar org-agenda-last-arguments nil
21006 "The arguments of the previous call to org-agenda")
21007 (defvar org-starting-day nil) ; local variable in the agenda buffer
21008 (defvar org-agenda-span nil) ; local variable in the agenda buffer
21009 (defvar org-include-all-loc nil) ; local variable
21010 (defvar org-agenda-remove-date nil) ; dynamically scoped FIXME: not used???
21012 ;;;###autoload
21013 (defun org-agenda-list (&optional include-all start-day ndays)
21014 "Produce a daily/weekly view from all files in variable `org-agenda-files'.
21015 The view will be for the current day or week, but from the overview buffer
21016 you will be able to go to other days/weeks.
21018 With one \\[universal-argument] prefix argument INCLUDE-ALL,
21019 all unfinished TODO items will also be shown, before the agenda.
21020 This feature is considered obsolete, please use the TODO list or a block
21021 agenda instead.
21023 With a numeric prefix argument in an interactive call, the agenda will
21024 span INCLUDE-ALL days. Lisp programs should instead specify NDAYS to change
21025 the number of days. NDAYS defaults to `org-agenda-ndays'.
21027 START-DAY defaults to TODAY, or to the most recent match for the weekday
21028 given in `org-agenda-start-on-weekday'."
21029 (interactive "P")
21030 (if (and (integerp include-all) (> include-all 0))
21031 (setq ndays include-all include-all nil))
21032 (setq ndays (or ndays org-agenda-ndays)
21033 start-day (or start-day org-agenda-start-day))
21034 (if org-agenda-overriding-arguments
21035 (setq include-all (car org-agenda-overriding-arguments)
21036 start-day (nth 1 org-agenda-overriding-arguments)
21037 ndays (nth 2 org-agenda-overriding-arguments)))
21038 (if (stringp start-day)
21039 ;; Convert to an absolute day number
21040 (setq start-day (time-to-days (org-read-date nil t start-day))))
21041 (setq org-agenda-last-arguments (list include-all start-day ndays))
21042 (org-compile-prefix-format 'agenda)
21043 (org-set-sorting-strategy 'agenda)
21044 (require 'calendar)
21045 (let* ((org-agenda-start-on-weekday
21046 (if (or (equal ndays 7) (and (null ndays) (equal 7 org-agenda-ndays)))
21047 org-agenda-start-on-weekday nil))
21048 (thefiles (org-agenda-files))
21049 (files thefiles)
21050 (today (time-to-days
21051 (time-subtract (current-time)
21052 (list 0 (* 3600 org-extend-today-until) 0))))
21053 (sd (or start-day today))
21054 (start (if (or (null org-agenda-start-on-weekday)
21055 (< org-agenda-ndays 7))
21057 (let* ((nt (calendar-day-of-week
21058 (calendar-gregorian-from-absolute sd)))
21059 (n1 org-agenda-start-on-weekday)
21060 (d (- nt n1)))
21061 (- sd (+ (if (< d 0) 7 0) d)))))
21062 (day-numbers (list start))
21063 (day-cnt 0)
21064 (inhibit-redisplay (not debug-on-error))
21065 s e rtn rtnall file date d start-pos end-pos todayp nd)
21066 (setq org-agenda-redo-command
21067 (list 'org-agenda-list (list 'quote include-all) start-day ndays))
21068 ;; Make the list of days
21069 (setq ndays (or ndays org-agenda-ndays)
21070 nd ndays)
21071 (while (> ndays 1)
21072 (push (1+ (car day-numbers)) day-numbers)
21073 (setq ndays (1- ndays)))
21074 (setq day-numbers (nreverse day-numbers))
21075 (org-prepare-agenda "Day/Week")
21076 (org-set-local 'org-starting-day (car day-numbers))
21077 (org-set-local 'org-include-all-loc include-all)
21078 (org-set-local 'org-agenda-span
21079 (org-agenda-ndays-to-span nd))
21080 (when (and (or include-all org-agenda-include-all-todo)
21081 (member today day-numbers))
21082 (setq files thefiles
21083 rtnall nil)
21084 (while (setq file (pop files))
21085 (catch 'nextfile
21086 (org-check-agenda-file file)
21087 (setq date (calendar-gregorian-from-absolute today)
21088 rtn (org-agenda-get-day-entries
21089 file date :todo))
21090 (setq rtnall (append rtnall rtn))))
21091 (when rtnall
21092 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
21093 (add-text-properties (point-min) (1- (point))
21094 (list 'face 'org-agenda-structure))
21095 (insert (org-finalize-agenda-entries rtnall) "\n")))
21096 (unless org-agenda-compact-blocks
21097 (setq s (point))
21098 (insert (capitalize (symbol-name (org-agenda-ndays-to-span nd)))
21099 "-agenda:\n")
21100 (add-text-properties s (1- (point)) (list 'face 'org-agenda-structure
21101 'org-date-line t)))
21102 (while (setq d (pop day-numbers))
21103 (setq date (calendar-gregorian-from-absolute d)
21104 s (point))
21105 (if (or (setq todayp (= d today))
21106 (and (not start-pos) (= d sd)))
21107 (setq start-pos (point))
21108 (if (and start-pos (not end-pos))
21109 (setq end-pos (point))))
21110 (setq files thefiles
21111 rtnall nil)
21112 (while (setq file (pop files))
21113 (catch 'nextfile
21114 (org-check-agenda-file file)
21115 (if org-agenda-show-log
21116 (setq rtn (org-agenda-get-day-entries
21117 file date
21118 :deadline :scheduled :timestamp :sexp :closed))
21119 (setq rtn (org-agenda-get-day-entries
21120 file date
21121 :deadline :scheduled :sexp :timestamp)))
21122 (setq rtnall (append rtnall rtn))))
21123 (if org-agenda-include-diary
21124 (progn
21125 (require 'diary-lib)
21126 (setq rtn (org-get-entries-from-diary date))
21127 (setq rtnall (append rtnall rtn))))
21128 (if (or rtnall org-agenda-show-all-dates)
21129 (progn
21130 (setq day-cnt (1+ day-cnt))
21131 (insert
21132 (if (stringp org-agenda-format-date)
21133 (format-time-string org-agenda-format-date
21134 (org-time-from-absolute date))
21135 (funcall org-agenda-format-date date))
21136 "\n")
21137 (put-text-property s (1- (point)) 'face 'org-agenda-structure)
21138 (put-text-property s (1- (point)) 'org-date-line t)
21139 (put-text-property s (1- (point)) 'org-day-cnt day-cnt)
21140 (if todayp (put-text-property s (1- (point)) 'org-today t))
21141 (if rtnall (insert
21142 (org-finalize-agenda-entries
21143 (org-agenda-add-time-grid-maybe
21144 rtnall nd todayp))
21145 "\n"))
21146 (put-text-property s (1- (point)) 'day d)
21147 (put-text-property s (1- (point)) 'org-day-cnt day-cnt))))
21148 (goto-char (point-min))
21149 (org-fit-agenda-window)
21150 (unless (and (pos-visible-in-window-p (point-min))
21151 (pos-visible-in-window-p (point-max)))
21152 (goto-char (1- (point-max)))
21153 (recenter -1)
21154 (if (not (pos-visible-in-window-p (or start-pos 1)))
21155 (progn
21156 (goto-char (or start-pos 1))
21157 (recenter 1))))
21158 (goto-char (or start-pos 1))
21159 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
21160 (org-finalize-agenda)
21161 (setq buffer-read-only t)
21162 (message "")))
21164 (defun org-agenda-ndays-to-span (n)
21165 (cond ((< n 7) 'day) ((= n 7) 'week) ((< n 32) 'month) (t 'year)))
21167 ;;; Agenda word search
21169 (defvar org-agenda-search-history nil)
21171 ;;;###autoload
21172 (defun org-search-view (&optional arg string)
21173 "Show all entries that contain words or regular expressions.
21174 If the first character of the search string is an asterisks,
21175 search only the headlines.
21177 The search string is broken into \"words\" by splitting at whitespace.
21178 The individual words are then interpreted as a boolean expression with
21179 logical AND. Words prefixed with a minus must not occur in the entry.
21180 Words without a prefix or prefixed with a plus must occur in the entry.
21181 Matching is case-insensitive and the words are enclosed by word delimiters.
21183 Words enclosed by curly braces are interpreted as regular expressions
21184 that must or must not match in the entry.
21186 This command searches the agenda files, and in addition the files listed
21187 in `org-agenda-text-search-extra-files'."
21188 (interactive "P")
21189 (org-compile-prefix-format 'search)
21190 (org-set-sorting-strategy 'search)
21191 (org-prepare-agenda "SEARCH")
21192 (let* ((props (list 'face nil
21193 'done-face 'org-done
21194 'org-not-done-regexp org-not-done-regexp
21195 'org-todo-regexp org-todo-regexp
21196 'mouse-face 'highlight
21197 'keymap org-agenda-keymap
21198 'help-echo (format "mouse-2 or RET jump to location")))
21199 regexp rtn rtnall files file pos
21200 marker priority category tags c neg re
21201 ee txt beg end words regexps+ regexps- hdl-only buffer beg1 str)
21202 (unless (and (not arg)
21203 (stringp string)
21204 (string-match "\\S-" string))
21205 (setq string (read-string "[+-]Word/{Regexp} ...: "
21206 (cond
21207 ((integerp arg) (cons string arg))
21208 (arg string))
21209 'org-agenda-search-history)))
21210 (setq org-agenda-redo-command
21211 (list 'org-search-view 'current-prefix-arg string))
21212 (setq org-agenda-query-string string)
21214 (if (equal (string-to-char string) ?*)
21215 (setq hdl-only t
21216 words (substring string 1))
21217 (setq words string))
21218 (setq words (org-split-string words))
21219 (mapc (lambda (w)
21220 (setq c (string-to-char w))
21221 (if (equal c ?-)
21222 (setq neg t w (substring w 1))
21223 (if (equal c ?+)
21224 (setq neg nil w (substring w 1))
21225 (setq neg nil)))
21226 (if (string-match "\\`{.*}\\'" w)
21227 (setq re (substring w 1 -1))
21228 (setq re (concat "\\<" (regexp-quote (downcase w)) "\\>")))
21229 (if neg (push re regexps-) (push re regexps+)))
21230 words)
21231 (setq regexps+ (sort regexps+ (lambda (a b) (> (length a) (length b)))))
21232 (if (not regexps+)
21233 (setq regexp (concat "^" org-outline-regexp))
21234 (setq regexp (pop regexps+))
21235 (if hdl-only (setq regexp (concat "^" org-outline-regexp ".*?"
21236 regexp))))
21237 (setq files (append (org-agenda-files) org-agenda-text-search-extra-files)
21238 rtnall nil)
21239 (while (setq file (pop files))
21240 (setq ee nil)
21241 (catch 'nextfile
21242 (org-check-agenda-file file)
21243 (setq buffer (if (file-exists-p file)
21244 (org-get-agenda-file-buffer file)
21245 (error "No such file %s" file)))
21246 (if (not buffer)
21247 ;; If file does not exist, make sure an error message is sent
21248 (setq rtn (list (format "ORG-AGENDA-ERROR: No such org-file %s"
21249 file))))
21250 (with-current-buffer buffer
21251 (unless (org-mode-p)
21252 (error "Agenda file %s is not in `org-mode'" file))
21253 (let ((case-fold-search t))
21254 (save-excursion
21255 (save-restriction
21256 (if org-agenda-restrict
21257 (narrow-to-region org-agenda-restrict-begin
21258 org-agenda-restrict-end)
21259 (widen))
21260 (goto-char (point-min))
21261 (unless (or (org-on-heading-p)
21262 (outline-next-heading))
21263 (throw 'nextfile t))
21264 (goto-char (max (point-min) (1- (point))))
21265 (while (re-search-forward regexp nil t)
21266 (org-back-to-heading t)
21267 (skip-chars-forward "* ")
21268 (setq beg (point-at-bol)
21269 beg1 (point)
21270 end (progn (outline-next-heading) (point)))
21271 (catch :skip
21272 (goto-char beg)
21273 (org-agenda-skip)
21274 (setq str (buffer-substring-no-properties
21275 (point-at-bol)
21276 (if hdl-only (point-at-eol) end)))
21277 (mapc (lambda (wr) (when (string-match wr str)
21278 (goto-char (1- end))
21279 (throw :skip t)))
21280 regexps-)
21281 (mapc (lambda (wr) (unless (string-match wr str)
21282 (goto-char (1- end))
21283 (throw :skip t)))
21284 regexps+)
21285 (goto-char beg)
21286 (setq marker (org-agenda-new-marker (point))
21287 category (org-get-category)
21288 tags (org-get-tags-at (point))
21289 txt (org-format-agenda-item
21291 (buffer-substring-no-properties
21292 beg1 (point-at-eol))
21293 category tags))
21294 (org-add-props txt props
21295 'org-marker marker 'org-hd-marker marker
21296 'priority 1000 'org-category category
21297 'type "search")
21298 (push txt ee)
21299 (goto-char (1- end)))))))))
21300 (setq rtn (nreverse ee))
21301 (setq rtnall (append rtnall rtn)))
21302 (if org-agenda-overriding-header
21303 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21304 nil 'face 'org-agenda-structure) "\n")
21305 (insert "Search words: ")
21306 (add-text-properties (point-min) (1- (point))
21307 (list 'face 'org-agenda-structure))
21308 (setq pos (point))
21309 (insert string "\n")
21310 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21311 (setq pos (point))
21312 (unless org-agenda-multi
21313 (insert "Press `[', `]' to add/sub word, `{', `}' to add/sub regexp, `C-u r' to edit\n")
21314 (add-text-properties pos (1- (point))
21315 (list 'face 'org-agenda-structure))))
21316 (when rtnall
21317 (insert (org-finalize-agenda-entries rtnall) "\n"))
21318 (goto-char (point-min))
21319 (org-fit-agenda-window)
21320 (add-text-properties (point-min) (point-max) '(org-agenda-type search))
21321 (org-finalize-agenda)
21322 (setq buffer-read-only t)))
21324 ;;; Agenda TODO list
21326 (defvar org-select-this-todo-keyword nil)
21327 (defvar org-last-arg nil)
21329 ;;;###autoload
21330 (defun org-todo-list (arg)
21331 "Show all TODO entries from all agenda file in a single list.
21332 The prefix arg can be used to select a specific TODO keyword and limit
21333 the list to these. When using \\[universal-argument], you will be prompted
21334 for a keyword. A numeric prefix directly selects the Nth keyword in
21335 `org-todo-keywords-1'."
21336 (interactive "P")
21337 (require 'calendar)
21338 (org-compile-prefix-format 'todo)
21339 (org-set-sorting-strategy 'todo)
21340 (org-prepare-agenda "TODO")
21341 (let* ((today (time-to-days (current-time)))
21342 (date (calendar-gregorian-from-absolute today))
21343 (kwds org-todo-keywords-for-agenda)
21344 (completion-ignore-case t)
21345 (org-select-this-todo-keyword
21346 (if (stringp arg) arg
21347 (and arg (integerp arg) (> arg 0)
21348 (nth (1- arg) kwds))))
21349 rtn rtnall files file pos)
21350 (when (equal arg '(4))
21351 (setq org-select-this-todo-keyword
21352 (completing-read "Keyword (or KWD1|K2D2|...): "
21353 (mapcar 'list kwds) nil nil)))
21354 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
21355 (org-set-local 'org-last-arg arg)
21356 (setq org-agenda-redo-command
21357 '(org-todo-list (or current-prefix-arg org-last-arg)))
21358 (setq files (org-agenda-files)
21359 rtnall nil)
21360 (while (setq file (pop files))
21361 (catch 'nextfile
21362 (org-check-agenda-file file)
21363 (setq rtn (org-agenda-get-day-entries file date :todo))
21364 (setq rtnall (append rtnall rtn))))
21365 (if org-agenda-overriding-header
21366 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21367 nil 'face 'org-agenda-structure) "\n")
21368 (insert "Global list of TODO items of type: ")
21369 (add-text-properties (point-min) (1- (point))
21370 (list 'face 'org-agenda-structure))
21371 (setq pos (point))
21372 (insert (or org-select-this-todo-keyword "ALL") "\n")
21373 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21374 (setq pos (point))
21375 (unless org-agenda-multi
21376 (insert "Available with `N r': (0)ALL")
21377 (let ((n 0) s)
21378 (mapc (lambda (x)
21379 (setq s (format "(%d)%s" (setq n (1+ n)) x))
21380 (if (> (+ (current-column) (string-width s) 1) (frame-width))
21381 (insert "\n "))
21382 (insert " " s))
21383 kwds))
21384 (insert "\n"))
21385 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21386 (when rtnall
21387 (insert (org-finalize-agenda-entries rtnall) "\n"))
21388 (goto-char (point-min))
21389 (org-fit-agenda-window)
21390 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
21391 (org-finalize-agenda)
21392 (setq buffer-read-only t)))
21394 ;;; Agenda tags match
21396 ;;;###autoload
21397 (defun org-tags-view (&optional todo-only match)
21398 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
21399 The prefix arg TODO-ONLY limits the search to TODO entries."
21400 (interactive "P")
21401 (org-compile-prefix-format 'tags)
21402 (org-set-sorting-strategy 'tags)
21403 (let* ((org-tags-match-list-sublevels
21404 (if todo-only t org-tags-match-list-sublevels))
21405 (completion-ignore-case t)
21406 rtn rtnall files file pos matcher
21407 buffer)
21408 (setq matcher (org-make-tags-matcher match)
21409 match (car matcher) matcher (cdr matcher))
21410 (org-prepare-agenda (concat "TAGS " match))
21411 (setq org-agenda-query-string match)
21412 (setq org-agenda-redo-command
21413 (list 'org-tags-view (list 'quote todo-only)
21414 (list 'if 'current-prefix-arg nil 'org-agenda-query-string)))
21415 (setq files (org-agenda-files)
21416 rtnall nil)
21417 (while (setq file (pop files))
21418 (catch 'nextfile
21419 (org-check-agenda-file file)
21420 (setq buffer (if (file-exists-p file)
21421 (org-get-agenda-file-buffer file)
21422 (error "No such file %s" file)))
21423 (if (not buffer)
21424 ;; If file does not exist, merror message to agenda
21425 (setq rtn (list
21426 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21427 rtnall (append rtnall rtn))
21428 (with-current-buffer buffer
21429 (unless (org-mode-p)
21430 (error "Agenda file %s is not in `org-mode'" file))
21431 (save-excursion
21432 (save-restriction
21433 (if org-agenda-restrict
21434 (narrow-to-region org-agenda-restrict-begin
21435 org-agenda-restrict-end)
21436 (widen))
21437 (setq rtn (org-scan-tags 'agenda matcher todo-only))
21438 (setq rtnall (append rtnall rtn))))))))
21439 (if org-agenda-overriding-header
21440 (insert (org-add-props (copy-sequence org-agenda-overriding-header)
21441 nil 'face 'org-agenda-structure) "\n")
21442 (insert "Headlines with TAGS match: ")
21443 (add-text-properties (point-min) (1- (point))
21444 (list 'face 'org-agenda-structure))
21445 (setq pos (point))
21446 (insert match "\n")
21447 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
21448 (setq pos (point))
21449 (unless org-agenda-multi
21450 (insert "Press `C-u r' to search again with new search string\n"))
21451 (add-text-properties pos (1- (point)) (list 'face 'org-agenda-structure)))
21452 (when rtnall
21453 (insert (org-finalize-agenda-entries rtnall) "\n"))
21454 (goto-char (point-min))
21455 (org-fit-agenda-window)
21456 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
21457 (org-finalize-agenda)
21458 (setq buffer-read-only t)))
21460 ;;; Agenda Finding stuck projects
21462 (defvar org-agenda-skip-regexp nil
21463 "Regular expression used in skipping subtrees for the agenda.
21464 This is basically a temporary global variable that can be set and then
21465 used by user-defined selections using `org-agenda-skip-function'.")
21467 (defvar org-agenda-overriding-header nil
21468 "When this is set during todo and tags searches, will replace header.")
21470 (defun org-agenda-skip-subtree-when-regexp-matches ()
21471 "Checks if the current subtree contains match for `org-agenda-skip-regexp'.
21472 If yes, it returns the end position of this tree, causing agenda commands
21473 to skip this subtree. This is a function that can be put into
21474 `org-agenda-skip-function' for the duration of a command."
21475 (let ((end (save-excursion (org-end-of-subtree t)))
21476 skip)
21477 (save-excursion
21478 (setq skip (re-search-forward org-agenda-skip-regexp end t)))
21479 (and skip end)))
21481 (defun org-agenda-skip-entry-if (&rest conditions)
21482 "Skip entry if any of CONDITIONS is true.
21483 See `org-agenda-skip-if' for details."
21484 (org-agenda-skip-if nil conditions))
21486 (defun org-agenda-skip-subtree-if (&rest conditions)
21487 "Skip entry if any of CONDITIONS is true.
21488 See `org-agenda-skip-if' for details."
21489 (org-agenda-skip-if t conditions))
21491 (defun org-agenda-skip-if (subtree conditions)
21492 "Checks current entity for CONDITIONS.
21493 If SUBTREE is non-nil, the entire subtree is checked. Otherwise, only
21494 the entry, i.e. the text before the next heading is checked.
21496 CONDITIONS is a list of symbols, boolean OR is used to combine the results
21497 from different tests. Valid conditions are:
21499 scheduled Check if there is a scheduled cookie
21500 notscheduled Check if there is no scheduled cookie
21501 deadline Check if there is a deadline
21502 notdeadline Check if there is no deadline
21503 regexp Check if regexp matches
21504 notregexp Check if regexp does not match.
21506 The regexp is taken from the conditions list, it must come right after
21507 the `regexp' or `notregexp' element.
21509 If any of these conditions is met, this function returns the end point of
21510 the entity, causing the search to continue from there. This is a function
21511 that can be put into `org-agenda-skip-function' for the duration of a command."
21512 (let (beg end m)
21513 (org-back-to-heading t)
21514 (setq beg (point)
21515 end (if subtree
21516 (progn (org-end-of-subtree t) (point))
21517 (progn (outline-next-heading) (1- (point)))))
21518 (goto-char beg)
21519 (and
21521 (and (memq 'scheduled conditions)
21522 (re-search-forward org-scheduled-time-regexp end t))
21523 (and (memq 'notscheduled conditions)
21524 (not (re-search-forward org-scheduled-time-regexp end t)))
21525 (and (memq 'deadline conditions)
21526 (re-search-forward org-deadline-time-regexp end t))
21527 (and (memq 'notdeadline conditions)
21528 (not (re-search-forward org-deadline-time-regexp end t)))
21529 (and (setq m (memq 'regexp conditions))
21530 (stringp (nth 1 m))
21531 (re-search-forward (nth 1 m) end t))
21532 (and (setq m (memq 'notregexp conditions))
21533 (stringp (nth 1 m))
21534 (not (re-search-forward (nth 1 m) end t))))
21535 end)))
21537 ;;;###autoload
21538 (defun org-agenda-list-stuck-projects (&rest ignore)
21539 "Create agenda view for projects that are stuck.
21540 Stuck projects are project that have no next actions. For the definitions
21541 of what a project is and how to check if it stuck, customize the variable
21542 `org-stuck-projects'.
21543 MATCH is being ignored."
21544 (interactive)
21545 (let* ((org-agenda-skip-function 'org-agenda-skip-subtree-when-regexp-matches)
21546 ;; FIXME: we could have used org-agenda-skip-if here.
21547 (org-agenda-overriding-header "List of stuck projects: ")
21548 (matcher (nth 0 org-stuck-projects))
21549 (todo (nth 1 org-stuck-projects))
21550 (todo-wds (if (member "*" todo)
21551 (progn
21552 (org-prepare-agenda-buffers (org-agenda-files))
21553 (org-delete-all
21554 org-done-keywords-for-agenda
21555 (copy-sequence org-todo-keywords-for-agenda)))
21556 todo))
21557 (todo-re (concat "^\\*+[ \t]+\\("
21558 (mapconcat 'identity todo-wds "\\|")
21559 "\\)\\>"))
21560 (tags (nth 2 org-stuck-projects))
21561 (tags-re (if (member "*" tags)
21562 (org-re "^\\*+ .*:[[:alnum:]_@]+:[ \t]*$")
21563 (concat "^\\*+ .*:\\("
21564 (mapconcat 'identity tags "\\|")
21565 (org-re "\\):[[:alnum:]_@:]*[ \t]*$"))))
21566 (gen-re (nth 3 org-stuck-projects))
21567 (re-list
21568 (delq nil
21569 (list
21570 (if todo todo-re)
21571 (if tags tags-re)
21572 (and gen-re (stringp gen-re) (string-match "\\S-" gen-re)
21573 gen-re)))))
21574 (setq org-agenda-skip-regexp
21575 (if re-list
21576 (mapconcat 'identity re-list "\\|")
21577 (error "No information how to identify unstuck projects")))
21578 (org-tags-view nil matcher)
21579 (with-current-buffer org-agenda-buffer-name
21580 (setq org-agenda-redo-command
21581 '(org-agenda-list-stuck-projects
21582 (or current-prefix-arg org-last-arg))))))
21584 ;;; Diary integration
21586 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
21587 (defvar list-diary-entries-hook)
21589 (defun org-get-entries-from-diary (date)
21590 "Get the (Emacs Calendar) diary entries for DATE."
21591 (require 'diary-lib)
21592 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
21593 (diary-display-hook '(fancy-diary-display))
21594 (pop-up-frames nil)
21595 (list-diary-entries-hook
21596 (cons 'org-diary-default-entry list-diary-entries-hook))
21597 (diary-file-name-prefix-function nil) ; turn this feature off
21598 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
21599 entries
21600 (org-disable-agenda-to-diary t))
21601 (save-excursion
21602 (save-window-excursion
21603 (funcall (if (fboundp 'diary-list-entries)
21604 'diary-list-entries 'list-diary-entries)
21605 date 1)))
21606 (if (not (get-buffer fancy-diary-buffer))
21607 (setq entries nil)
21608 (with-current-buffer fancy-diary-buffer
21609 (setq buffer-read-only nil)
21610 (if (zerop (buffer-size))
21611 ;; No entries
21612 (setq entries nil)
21613 ;; Omit the date and other unnecessary stuff
21614 (org-agenda-cleanup-fancy-diary)
21615 ;; Add prefix to each line and extend the text properties
21616 (if (zerop (buffer-size))
21617 (setq entries nil)
21618 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
21619 (set-buffer-modified-p nil)
21620 (kill-buffer fancy-diary-buffer)))
21621 (when entries
21622 (setq entries (org-split-string entries "\n"))
21623 (setq entries
21624 (mapcar
21625 (lambda (x)
21626 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
21627 ;; Extend the text properties to the beginning of the line
21628 (org-add-props x (text-properties-at (1- (length x)) x)
21629 'type "diary" 'date date))
21630 entries)))))
21632 (defun org-agenda-cleanup-fancy-diary ()
21633 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
21634 This gets rid of the date, the underline under the date, and
21635 the dummy entry installed by `org-mode' to ensure non-empty diary for each
21636 date. It also removes lines that contain only whitespace."
21637 (goto-char (point-min))
21638 (if (looking-at ".*?:[ \t]*")
21639 (progn
21640 (replace-match "")
21641 (re-search-forward "\n=+$" nil t)
21642 (replace-match "")
21643 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
21644 (re-search-forward "\n=+$" nil t)
21645 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
21646 (goto-char (point-min))
21647 (while (re-search-forward "^ +\n" nil t)
21648 (replace-match ""))
21649 (goto-char (point-min))
21650 (if (re-search-forward "^Org-mode dummy\n?" nil t)
21651 (replace-match "")))
21653 ;; Make sure entries from the diary have the right text properties.
21654 (eval-after-load "diary-lib"
21655 '(if (boundp 'diary-modify-entry-list-string-function)
21656 ;; We can rely on the hook, nothing to do
21658 ;; Hook not avaiable, must use advice to make this work
21659 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
21660 "Make the position visible."
21661 (if (and org-disable-agenda-to-diary ;; called from org-agenda
21662 (stringp string)
21663 buffer-file-name)
21664 (setq string (org-modify-diary-entry-string string))))))
21666 (defun org-modify-diary-entry-string (string)
21667 "Add text properties to string, allowing org-mode to act on it."
21668 (org-add-props string nil
21669 'mouse-face 'highlight
21670 'keymap org-agenda-keymap
21671 'help-echo (if buffer-file-name
21672 (format "mouse-2 or RET jump to diary file %s"
21673 (abbreviate-file-name buffer-file-name))
21675 'org-agenda-diary-link t
21676 'org-marker (org-agenda-new-marker (point-at-bol))))
21678 (defun org-diary-default-entry ()
21679 "Add a dummy entry to the diary.
21680 Needed to avoid empty dates which mess up holiday display."
21681 ;; Catch the error if dealing with the new add-to-diary-alist
21682 (when org-disable-agenda-to-diary
21683 (condition-case nil
21684 (add-to-diary-list original-date "Org-mode dummy" "")
21685 (error
21686 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
21688 ;;;###autoload
21689 (defun org-diary (&rest args)
21690 "Return diary information from org-files.
21691 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
21692 It accesses org files and extracts information from those files to be
21693 listed in the diary. The function accepts arguments specifying what
21694 items should be listed. The following arguments are allowed:
21696 :timestamp List the headlines of items containing a date stamp or
21697 date range matching the selected date. Deadlines will
21698 also be listed, on the expiration day.
21700 :sexp List entries resulting from diary-like sexps.
21702 :deadline List any deadlines past due, or due within
21703 `org-deadline-warning-days'. The listing occurs only
21704 in the diary for *today*, not at any other date. If
21705 an entry is marked DONE, it is no longer listed.
21707 :scheduled List all items which are scheduled for the given date.
21708 The diary for *today* also contains items which were
21709 scheduled earlier and are not yet marked DONE.
21711 :todo List all TODO items from the org-file. This may be a
21712 long list - so this is not turned on by default.
21713 Like deadlines, these entries only show up in the
21714 diary for *today*, not at any other date.
21716 The call in the diary file should look like this:
21718 &%%(org-diary) ~/path/to/some/orgfile.org
21720 Use a separate line for each org file to check. Or, if you omit the file name,
21721 all files listed in `org-agenda-files' will be checked automatically:
21723 &%%(org-diary)
21725 If you don't give any arguments (as in the example above), the default
21726 arguments (:deadline :scheduled :timestamp :sexp) are used.
21727 So the example above may also be written as
21729 &%%(org-diary :deadline :timestamp :sexp :scheduled)
21731 The function expects the lisp variables `entry' and `date' to be provided
21732 by the caller, because this is how the calendar works. Don't use this
21733 function from a program - use `org-agenda-get-day-entries' instead."
21734 (when (> (- (time-to-seconds (current-time))
21735 org-agenda-last-marker-time)
21737 (org-agenda-reset-markers))
21738 (org-compile-prefix-format 'agenda)
21739 (org-set-sorting-strategy 'agenda)
21740 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21741 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
21742 (list entry)
21743 (org-agenda-files t)))
21744 file rtn results)
21745 (org-prepare-agenda-buffers files)
21746 ;; If this is called during org-agenda, don't return any entries to
21747 ;; the calendar. Org Agenda will list these entries itself.
21748 (if org-disable-agenda-to-diary (setq files nil))
21749 (while (setq file (pop files))
21750 (setq rtn (apply 'org-agenda-get-day-entries file date args))
21751 (setq results (append results rtn)))
21752 (if results
21753 (concat (org-finalize-agenda-entries results) "\n"))))
21755 ;;; Agenda entry finders
21757 (defun org-agenda-get-day-entries (file date &rest args)
21758 "Does the work for `org-diary' and `org-agenda'.
21759 FILE is the path to a file to be checked for entries. DATE is date like
21760 the one returned by `calendar-current-date'. ARGS are symbols indicating
21761 which kind of entries should be extracted. For details about these, see
21762 the documentation of `org-diary'."
21763 (setq args (or args '(:deadline :scheduled :timestamp :sexp)))
21764 (let* ((org-startup-folded nil)
21765 (org-startup-align-all-tables nil)
21766 (buffer (if (file-exists-p file)
21767 (org-get-agenda-file-buffer file)
21768 (error "No such file %s" file)))
21769 arg results rtn)
21770 (if (not buffer)
21771 ;; If file does not exist, make sure an error message ends up in diary
21772 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
21773 (with-current-buffer buffer
21774 (unless (org-mode-p)
21775 (error "Agenda file %s is not in `org-mode'" file))
21776 (let ((case-fold-search nil))
21777 (save-excursion
21778 (save-restriction
21779 (if org-agenda-restrict
21780 (narrow-to-region org-agenda-restrict-begin
21781 org-agenda-restrict-end)
21782 (widen))
21783 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
21784 (while (setq arg (pop args))
21785 (cond
21786 ((and (eq arg :todo)
21787 (equal date (calendar-current-date)))
21788 (setq rtn (org-agenda-get-todos))
21789 (setq results (append results rtn)))
21790 ((eq arg :timestamp)
21791 (setq rtn (org-agenda-get-blocks))
21792 (setq results (append results rtn))
21793 (setq rtn (org-agenda-get-timestamps))
21794 (setq results (append results rtn)))
21795 ((eq arg :sexp)
21796 (setq rtn (org-agenda-get-sexps))
21797 (setq results (append results rtn)))
21798 ((eq arg :scheduled)
21799 (setq rtn (org-agenda-get-scheduled))
21800 (setq results (append results rtn)))
21801 ((eq arg :closed)
21802 (setq rtn (org-agenda-get-closed))
21803 (setq results (append results rtn)))
21804 ((eq arg :deadline)
21805 (setq rtn (org-agenda-get-deadlines))
21806 (setq results (append results rtn))))))))
21807 results))))
21809 (defun org-entry-is-todo-p ()
21810 (member (org-get-todo-state) org-not-done-keywords))
21812 (defun org-entry-is-done-p ()
21813 (member (org-get-todo-state) org-done-keywords))
21815 (defun org-get-todo-state ()
21816 (save-excursion
21817 (org-back-to-heading t)
21818 (and (looking-at org-todo-line-regexp)
21819 (match-end 2)
21820 (match-string 2))))
21822 (defun org-at-date-range-p (&optional inactive-ok)
21823 "Is the cursor inside a date range?"
21824 (interactive)
21825 (save-excursion
21826 (catch 'exit
21827 (let ((pos (point)))
21828 (skip-chars-backward "^[<\r\n")
21829 (skip-chars-backward "<[")
21830 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21831 (>= (match-end 0) pos)
21832 (throw 'exit t))
21833 (skip-chars-backward "^<[\r\n")
21834 (skip-chars-backward "<[")
21835 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
21836 (>= (match-end 0) pos)
21837 (throw 'exit t)))
21838 nil)))
21840 (defun org-agenda-get-todos ()
21841 "Return the TODO information for agenda display."
21842 (let* ((props (list 'face nil
21843 'done-face 'org-done
21844 'org-not-done-regexp org-not-done-regexp
21845 'org-todo-regexp org-todo-regexp
21846 'mouse-face 'highlight
21847 'keymap org-agenda-keymap
21848 'help-echo
21849 (format "mouse-2 or RET jump to org file %s"
21850 (abbreviate-file-name buffer-file-name))))
21851 ;; FIXME: get rid of the \n at some point but watch out
21852 (regexp (concat "^\\*+[ \t]+\\("
21853 (if org-select-this-todo-keyword
21854 (if (equal org-select-this-todo-keyword "*")
21855 org-todo-regexp
21856 (concat "\\<\\("
21857 (mapconcat 'identity (org-split-string org-select-this-todo-keyword "|") "\\|")
21858 "\\)\\>"))
21859 org-not-done-regexp)
21860 "[^\n\r]*\\)"))
21861 marker priority category tags
21862 ee txt beg end)
21863 (goto-char (point-min))
21864 (while (re-search-forward regexp nil t)
21865 (catch :skip
21866 (save-match-data
21867 (beginning-of-line)
21868 (setq beg (point) end (progn (outline-next-heading) (point)))
21869 (when (or (and org-agenda-todo-ignore-with-date (goto-char beg)
21870 (re-search-forward org-ts-regexp end t))
21871 (and org-agenda-todo-ignore-scheduled (goto-char beg)
21872 (re-search-forward org-scheduled-time-regexp end t))
21873 (and org-agenda-todo-ignore-deadlines (goto-char beg)
21874 (re-search-forward org-deadline-time-regexp end t)
21875 (org-deadline-close (match-string 1))))
21876 (goto-char (1+ beg))
21877 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
21878 (throw :skip nil)))
21879 (goto-char beg)
21880 (org-agenda-skip)
21881 (goto-char (match-beginning 1))
21882 (setq marker (org-agenda-new-marker (match-beginning 0))
21883 category (org-get-category)
21884 tags (org-get-tags-at (point))
21885 txt (org-format-agenda-item "" (match-string 1) category tags)
21886 priority (1+ (org-get-priority txt)))
21887 (org-add-props txt props
21888 'org-marker marker 'org-hd-marker marker
21889 'priority priority 'org-category category
21890 'type "todo")
21891 (push txt ee)
21892 (if org-agenda-todo-list-sublevels
21893 (goto-char (match-end 1))
21894 (org-end-of-subtree 'invisible))))
21895 (nreverse ee)))
21897 (defconst org-agenda-no-heading-message
21898 "No heading for this item in buffer or region.")
21900 (defun org-agenda-get-timestamps ()
21901 "Return the date stamp information for agenda display."
21902 (let* ((props (list 'face nil
21903 'org-not-done-regexp org-not-done-regexp
21904 'org-todo-regexp org-todo-regexp
21905 'mouse-face 'highlight
21906 'keymap org-agenda-keymap
21907 'help-echo
21908 (format "mouse-2 or RET jump to org file %s"
21909 (abbreviate-file-name buffer-file-name))))
21910 (d1 (calendar-absolute-from-gregorian date))
21911 (remove-re
21912 (concat
21913 (regexp-quote
21914 (format-time-string
21915 "<%Y-%m-%d"
21916 (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
21917 ".*?>"))
21918 (regexp
21919 (concat
21920 (regexp-quote
21921 (substring
21922 (format-time-string
21923 (car org-time-stamp-formats)
21924 (apply 'encode-time ; DATE bound by calendar
21925 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
21926 0 11))
21927 "\\|\\(<[0-9]+-[0-9]+-[0-9]+[^>\n]+?\\+[0-9]+[dwmy]>\\)"
21928 "\\|\\(<%%\\(([^>\n]+)\\)>\\)"))
21929 marker hdmarker deadlinep scheduledp donep tmp priority category
21930 ee txt timestr tags b0 b3 e3 head)
21931 (goto-char (point-min))
21932 (while (re-search-forward regexp nil t)
21933 (setq b0 (match-beginning 0)
21934 b3 (match-beginning 3) e3 (match-end 3))
21935 (catch :skip
21936 (and (org-at-date-range-p) (throw :skip nil))
21937 (org-agenda-skip)
21938 (if (and (match-end 1)
21939 (not (= d1 (org-time-string-to-absolute (match-string 1) d1))))
21940 (throw :skip nil))
21941 (if (and e3
21942 (not (org-diary-sexp-entry (buffer-substring b3 e3) "" date)))
21943 (throw :skip nil))
21944 (setq marker (org-agenda-new-marker b0)
21945 category (org-get-category b0)
21946 tmp (buffer-substring (max (point-min)
21947 (- b0 org-ds-keyword-length))
21949 timestr (if b3 "" (buffer-substring b0 (point-at-eol)))
21950 deadlinep (string-match org-deadline-regexp tmp)
21951 scheduledp (string-match org-scheduled-regexp tmp)
21952 donep (org-entry-is-done-p))
21953 (if (or scheduledp deadlinep) (throw :skip t))
21954 (if (string-match ">" timestr)
21955 ;; substring should only run to end of time stamp
21956 (setq timestr (substring timestr 0 (match-end 0))))
21957 (save-excursion
21958 (if (re-search-backward "^\\*+ " nil t)
21959 (progn
21960 (goto-char (match-beginning 0))
21961 (setq hdmarker (org-agenda-new-marker)
21962 tags (org-get-tags-at))
21963 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
21964 (setq head (match-string 1))
21965 (and org-agenda-skip-timestamp-if-done donep (throw :skip t))
21966 (setq txt (org-format-agenda-item
21967 nil head category tags timestr nil
21968 remove-re)))
21969 (setq txt org-agenda-no-heading-message))
21970 (setq priority (org-get-priority txt))
21971 (org-add-props txt props
21972 'org-marker marker 'org-hd-marker hdmarker)
21973 (org-add-props txt nil 'priority priority
21974 'org-category category 'date date
21975 'type "timestamp")
21976 (push txt ee))
21977 (outline-next-heading)))
21978 (nreverse ee)))
21980 (defun org-agenda-get-sexps ()
21981 "Return the sexp information for agenda display."
21982 (require 'diary-lib)
21983 (let* ((props (list 'face nil
21984 'mouse-face 'highlight
21985 'keymap org-agenda-keymap
21986 'help-echo
21987 (format "mouse-2 or RET jump to org file %s"
21988 (abbreviate-file-name buffer-file-name))))
21989 (regexp "^&?%%(")
21990 marker category ee txt tags entry result beg b sexp sexp-entry)
21991 (goto-char (point-min))
21992 (while (re-search-forward regexp nil t)
21993 (catch :skip
21994 (org-agenda-skip)
21995 (setq beg (match-beginning 0))
21996 (goto-char (1- (match-end 0)))
21997 (setq b (point))
21998 (forward-sexp 1)
21999 (setq sexp (buffer-substring b (point)))
22000 (setq sexp-entry (if (looking-at "[ \t]*\\(\\S-.*\\)")
22001 (org-trim (match-string 1))
22002 ""))
22003 (setq result (org-diary-sexp-entry sexp sexp-entry date))
22004 (when result
22005 (setq marker (org-agenda-new-marker beg)
22006 category (org-get-category beg))
22008 (if (string-match "\\S-" result)
22009 (setq txt result)
22010 (setq txt "SEXP entry returned empty string"))
22012 (setq txt (org-format-agenda-item
22013 "" txt category tags 'time))
22014 (org-add-props txt props 'org-marker marker)
22015 (org-add-props txt nil
22016 'org-category category 'date date
22017 'type "sexp")
22018 (push txt ee))))
22019 (nreverse ee)))
22021 (defun org-agenda-get-closed ()
22022 "Return the logged TODO entries for agenda display."
22023 (let* ((props (list 'mouse-face 'highlight
22024 'org-not-done-regexp org-not-done-regexp
22025 'org-todo-regexp org-todo-regexp
22026 'keymap org-agenda-keymap
22027 'help-echo
22028 (format "mouse-2 or RET jump to org file %s"
22029 (abbreviate-file-name buffer-file-name))))
22030 (regexp (concat
22031 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
22032 (regexp-quote
22033 (substring
22034 (format-time-string
22035 (car org-time-stamp-formats)
22036 (apply 'encode-time ; DATE bound by calendar
22037 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
22038 1 11))))
22039 marker hdmarker priority category tags closedp
22040 ee txt timestr)
22041 (goto-char (point-min))
22042 (while (re-search-forward regexp nil t)
22043 (catch :skip
22044 (org-agenda-skip)
22045 (setq marker (org-agenda-new-marker (match-beginning 0))
22046 closedp (equal (match-string 1) org-closed-string)
22047 category (org-get-category (match-beginning 0))
22048 timestr (buffer-substring (match-beginning 0) (point-at-eol))
22049 ;; donep (org-entry-is-done-p)
22051 (if (string-match "\\]" timestr)
22052 ;; substring should only run to end of time stamp
22053 (setq timestr (substring timestr 0 (match-end 0))))
22054 (save-excursion
22055 (if (re-search-backward "^\\*+ " nil t)
22056 (progn
22057 (goto-char (match-beginning 0))
22058 (setq hdmarker (org-agenda-new-marker)
22059 tags (org-get-tags-at))
22060 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22061 (setq txt (org-format-agenda-item
22062 (if closedp "Closed: " "Clocked: ")
22063 (match-string 1) category tags timestr)))
22064 (setq txt org-agenda-no-heading-message))
22065 (setq priority 100000)
22066 (org-add-props txt props
22067 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
22068 'priority priority 'org-category category
22069 'type "closed" 'date date
22070 'undone-face 'org-warning 'done-face 'org-done)
22071 (push txt ee))
22072 (goto-char (point-at-eol))))
22073 (nreverse ee)))
22075 (defun org-agenda-get-deadlines ()
22076 "Return the deadline information for agenda display."
22077 (let* ((props (list 'mouse-face 'highlight
22078 'org-not-done-regexp org-not-done-regexp
22079 'org-todo-regexp org-todo-regexp
22080 'keymap org-agenda-keymap
22081 'help-echo
22082 (format "mouse-2 or RET jump to org file %s"
22083 (abbreviate-file-name buffer-file-name))))
22084 (regexp org-deadline-time-regexp)
22085 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22086 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22087 d2 diff dfrac wdays pos pos1 category tags
22088 ee txt head face s upcomingp donep timestr)
22089 (goto-char (point-min))
22090 (while (re-search-forward regexp nil t)
22091 (catch :skip
22092 (org-agenda-skip)
22093 (setq s (match-string 1)
22094 pos (1- (match-beginning 1))
22095 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22096 diff (- d2 d1)
22097 wdays (org-get-wdays s)
22098 dfrac (/ (* 1.0 (- wdays diff)) (max wdays 1))
22099 upcomingp (and todayp (> diff 0)))
22100 ;; When to show a deadline in the calendar:
22101 ;; If the expiration is within wdays warning time.
22102 ;; Past-due deadlines are only shown on the current date
22103 (if (or (and (<= diff wdays)
22104 (and todayp (not org-agenda-only-exact-dates)))
22105 (= diff 0))
22106 (save-excursion
22107 (setq category (org-get-category))
22108 (if (re-search-backward "^\\*+[ \t]+" nil t)
22109 (progn
22110 (goto-char (match-end 0))
22111 (setq pos1 (match-beginning 0))
22112 (setq tags (org-get-tags-at pos1))
22113 (setq head (buffer-substring-no-properties
22114 (point)
22115 (progn (skip-chars-forward "^\r\n")
22116 (point))))
22117 (setq donep (string-match org-looking-at-done-regexp head))
22118 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22119 (setq timestr
22120 (concat (substring s (match-beginning 1)) " "))
22121 (setq timestr 'time))
22122 (if (and donep
22123 (or org-agenda-skip-deadline-if-done
22124 (not (= diff 0))))
22125 (setq txt nil)
22126 (setq txt (org-format-agenda-item
22127 (if (= diff 0)
22128 (car org-agenda-deadline-leaders)
22129 (format (nth 1 org-agenda-deadline-leaders)
22130 diff))
22131 head category tags timestr))))
22132 (setq txt org-agenda-no-heading-message))
22133 (when txt
22134 (setq face (org-agenda-deadline-face dfrac wdays))
22135 (org-add-props txt props
22136 'org-marker (org-agenda-new-marker pos)
22137 'org-hd-marker (org-agenda-new-marker pos1)
22138 'priority (+ (- diff)
22139 (org-get-priority txt))
22140 'org-category category
22141 'type (if upcomingp "upcoming-deadline" "deadline")
22142 'date (if upcomingp date d2)
22143 'face (if donep 'org-done face)
22144 'undone-face face 'done-face 'org-done)
22145 (push txt ee))))))
22146 (nreverse ee)))
22148 (defun org-agenda-deadline-face (fraction &optional wdays)
22149 "Return the face to displaying a deadline item.
22150 FRACTION is what fraction of the head-warning time has passed."
22151 (if (equal wdays 0) (setq fraction 1.))
22152 (let ((faces org-agenda-deadline-faces) f)
22153 (catch 'exit
22154 (while (setq f (pop faces))
22155 (if (>= fraction (car f)) (throw 'exit (cdr f)))))))
22157 (defun org-agenda-get-scheduled ()
22158 "Return the scheduled information for agenda display."
22159 (let* ((props (list 'org-not-done-regexp org-not-done-regexp
22160 'org-todo-regexp org-todo-regexp
22161 'done-face 'org-done
22162 'mouse-face 'highlight
22163 'keymap org-agenda-keymap
22164 'help-echo
22165 (format "mouse-2 or RET jump to org file %s"
22166 (abbreviate-file-name buffer-file-name))))
22167 (regexp org-scheduled-time-regexp)
22168 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
22169 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
22170 d2 diff pos pos1 category tags
22171 ee txt head pastschedp donep face timestr s)
22172 (goto-char (point-min))
22173 (while (re-search-forward regexp nil t)
22174 (catch :skip
22175 (org-agenda-skip)
22176 (setq s (match-string 1)
22177 pos (1- (match-beginning 1))
22178 d2 (org-time-string-to-absolute (match-string 1) d1 'past)
22179 ;;; is this right?
22180 ;;; do we need to do this for deadleine too????
22181 ;;; d2 (org-time-string-to-absolute (match-string 1) (if todayp nil d1))
22182 diff (- d2 d1))
22183 (setq pastschedp (and todayp (< diff 0)))
22184 ;; When to show a scheduled item in the calendar:
22185 ;; If it is on or past the date.
22186 (if (or (and (< diff 0)
22187 (and todayp (not org-agenda-only-exact-dates)))
22188 (= diff 0))
22189 (save-excursion
22190 (setq category (org-get-category))
22191 (if (re-search-backward "^\\*+[ \t]+" nil t)
22192 (progn
22193 (goto-char (match-end 0))
22194 (setq pos1 (match-beginning 0))
22195 (setq tags (org-get-tags-at))
22196 (setq head (buffer-substring-no-properties
22197 (point)
22198 (progn (skip-chars-forward "^\r\n") (point))))
22199 (setq donep (string-match org-looking-at-done-regexp head))
22200 (if (string-match " \\([012]?[0-9]:[0-9][0-9]\\)" s)
22201 (setq timestr
22202 (concat (substring s (match-beginning 1)) " "))
22203 (setq timestr 'time))
22204 (if (and donep
22205 (or org-agenda-skip-scheduled-if-done
22206 (not (= diff 0))))
22207 (setq txt nil)
22208 (setq txt (org-format-agenda-item
22209 (if (= diff 0)
22210 (car org-agenda-scheduled-leaders)
22211 (format (nth 1 org-agenda-scheduled-leaders)
22212 (- 1 diff)))
22213 head category tags timestr))))
22214 (setq txt org-agenda-no-heading-message))
22215 (when txt
22216 (setq face (if pastschedp
22217 'org-scheduled-previously
22218 'org-scheduled-today))
22219 (org-add-props txt props
22220 'undone-face face
22221 'face (if donep 'org-done face)
22222 'org-marker (org-agenda-new-marker pos)
22223 'org-hd-marker (org-agenda-new-marker pos1)
22224 'type (if pastschedp "past-scheduled" "scheduled")
22225 'date (if pastschedp d2 date)
22226 'priority (+ 94 (- 5 diff) (org-get-priority txt))
22227 'org-category category)
22228 (push txt ee))))))
22229 (nreverse ee)))
22231 (defun org-agenda-get-blocks ()
22232 "Return the date-range information for agenda display."
22233 (let* ((props (list 'face nil
22234 'org-not-done-regexp org-not-done-regexp
22235 'org-todo-regexp org-todo-regexp
22236 'mouse-face 'highlight
22237 'keymap org-agenda-keymap
22238 'help-echo
22239 (format "mouse-2 or RET jump to org file %s"
22240 (abbreviate-file-name buffer-file-name))))
22241 (regexp org-tr-regexp)
22242 (d0 (calendar-absolute-from-gregorian date))
22243 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos
22244 donep head)
22245 (goto-char (point-min))
22246 (while (re-search-forward regexp nil t)
22247 (catch :skip
22248 (org-agenda-skip)
22249 (setq pos (point))
22250 (setq timestr (match-string 0)
22251 s1 (match-string 1)
22252 s2 (match-string 2)
22253 d1 (time-to-days (org-time-string-to-time s1))
22254 d2 (time-to-days (org-time-string-to-time s2)))
22255 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
22256 ;; Only allow days between the limits, because the normal
22257 ;; date stamps will catch the limits.
22258 (save-excursion
22259 (setq marker (org-agenda-new-marker (point)))
22260 (setq category (org-get-category))
22261 (if (re-search-backward "^\\*+ " nil t)
22262 (progn
22263 (goto-char (match-beginning 0))
22264 (setq hdmarker (org-agenda-new-marker (point)))
22265 (setq tags (org-get-tags-at))
22266 (looking-at "\\*+[ \t]+\\([^\r\n]+\\)")
22267 (setq head (match-string 1))
22268 (and org-agenda-skip-timestamp-if-done
22269 (org-entry-is-done-p)
22270 (throw :skip t))
22271 (setq txt (org-format-agenda-item
22272 (format (if (= d1 d2) "" "(%d/%d): ")
22273 (1+ (- d0 d1)) (1+ (- d2 d1)))
22274 head category tags
22275 (if (= d0 d1) timestr))))
22276 (setq txt org-agenda-no-heading-message))
22277 (org-add-props txt props
22278 'org-marker marker 'org-hd-marker hdmarker
22279 'type "block" 'date date
22280 'priority (org-get-priority txt) 'org-category category)
22281 (push txt ee)))
22282 (goto-char pos)))
22283 ;; Sort the entries by expiration date.
22284 (nreverse ee)))
22286 ;;; Agenda presentation and sorting
22288 (defconst org-plain-time-of-day-regexp
22289 (concat
22290 "\\(\\<[012]?[0-9]"
22291 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22292 "\\(--?"
22293 "\\(\\<[012]?[0-9]"
22294 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22295 "\\)?")
22296 "Regular expression to match a plain time or time range.
22297 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22298 groups carry important information:
22299 0 the full match
22300 1 the first time, range or not
22301 8 the second time, if it is a range.")
22303 (defconst org-plain-time-extension-regexp
22304 (concat
22305 "\\(\\<[012]?[0-9]"
22306 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
22307 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
22308 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
22309 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
22310 groups carry important information:
22311 0 the full match
22312 7 hours of duration
22313 9 minutes of duration")
22315 (defconst org-stamp-time-of-day-regexp
22316 (concat
22317 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
22318 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
22319 "\\(--?"
22320 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
22321 "Regular expression to match a timestamp time or time range.
22322 After a match, the following groups carry important information:
22323 0 the full match
22324 1 date plus weekday, for backreferencing to make sure both times on same day
22325 2 the first time, range or not
22326 4 the second time, if it is a range.")
22328 (defvar org-prefix-has-time nil
22329 "A flag, set by `org-compile-prefix-format'.
22330 The flag is set if the currently compiled format contains a `%t'.")
22331 (defvar org-prefix-has-tag nil
22332 "A flag, set by `org-compile-prefix-format'.
22333 The flag is set if the currently compiled format contains a `%T'.")
22335 (defun org-format-agenda-item (extra txt &optional category tags dotime
22336 noprefix remove-re)
22337 "Format TXT to be inserted into the agenda buffer.
22338 In particular, it adds the prefix and corresponding text properties. EXTRA
22339 must be a string and replaces the `%s' specifier in the prefix format.
22340 CATEGORY (string, symbol or nil) may be used to overrule the default
22341 category taken from local variable or file name. It will replace the `%c'
22342 specifier in the format. DOTIME, when non-nil, indicates that a
22343 time-of-day should be extracted from TXT for sorting of this entry, and for
22344 the `%t' specifier in the format. When DOTIME is a string, this string is
22345 searched for a time before TXT is. NOPREFIX is a flag and indicates that
22346 only the correctly processes TXT should be returned - this is used by
22347 `org-agenda-change-all-lines'. TAGS can be the tags of the headline.
22348 Any match of REMOVE-RE will be removed from TXT."
22349 (save-match-data
22350 ;; Diary entries sometimes have extra whitespace at the beginning
22351 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
22352 (let* ((category (or category
22353 org-category
22354 (if buffer-file-name
22355 (file-name-sans-extension
22356 (file-name-nondirectory buffer-file-name))
22357 "")))
22358 (tag (if tags (nth (1- (length tags)) tags) ""))
22359 time ; time and tag are needed for the eval of the prefix format
22360 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
22361 (time-of-day (and dotime (org-get-time-of-day ts)))
22362 stamp plain s0 s1 s2 rtn srp)
22363 (when (and dotime time-of-day org-prefix-has-time)
22364 ;; Extract starting and ending time and move them to prefix
22365 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
22366 (setq plain (string-match org-plain-time-of-day-regexp ts)))
22367 (setq s0 (match-string 0 ts)
22368 srp (and stamp (match-end 3))
22369 s1 (match-string (if plain 1 2) ts)
22370 s2 (match-string (if plain 8 (if srp 4 6)) ts))
22372 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
22373 ;; them, we might want to remove them there to avoid duplication.
22374 ;; The user can turn this off with a variable.
22375 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
22376 (string-match (concat (regexp-quote s0) " *") txt)
22377 (not (equal ?\] (string-to-char (substring txt (match-end 0)))))
22378 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
22379 (= (match-beginning 0) 0)
22381 (setq txt (replace-match "" nil nil txt))))
22382 ;; Normalize the time(s) to 24 hour
22383 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
22384 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
22386 (when (and s1 (not s2) org-agenda-default-appointment-duration
22387 (string-match "\\([0-9]+\\):\\([0-9]+\\)" s1))
22388 (let ((m (+ (string-to-number (match-string 2 s1))
22389 (* 60 (string-to-number (match-string 1 s1)))
22390 org-agenda-default-appointment-duration))
22392 (setq h (/ m 60) m (- m (* h 60)))
22393 (setq s2 (format "%02d:%02d" h m))))
22395 (when (string-match (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
22396 txt)
22397 ;; Tags are in the string
22398 (if (or (eq org-agenda-remove-tags t)
22399 (and org-agenda-remove-tags
22400 org-prefix-has-tag))
22401 (setq txt (replace-match "" t t txt))
22402 (setq txt (replace-match
22403 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
22404 (match-string 2 txt))
22405 t t txt))))
22407 (when remove-re
22408 (while (string-match remove-re txt)
22409 (setq txt (replace-match "" t t txt))))
22411 ;; Create the final string
22412 (if noprefix
22413 (setq rtn txt)
22414 ;; Prepare the variables needed in the eval of the compiled format
22415 (setq time (cond (s2 (concat s1 "-" s2))
22416 (s1 (concat s1 "......"))
22417 (t ""))
22418 extra (or extra "")
22419 category (if (symbolp category) (symbol-name category) category))
22420 ;; Evaluate the compiled format
22421 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
22423 ;; And finally add the text properties
22424 (org-add-props rtn nil
22425 'org-category (downcase category) 'tags tags
22426 'org-highest-priority org-highest-priority
22427 'org-lowest-priority org-lowest-priority
22428 'prefix-length (- (length rtn) (length txt))
22429 'time-of-day time-of-day
22430 'txt txt
22431 'time time
22432 'extra extra
22433 'dotime dotime))))
22435 (defvar org-agenda-sorting-strategy) ;; because the def is in a let form
22436 (defvar org-agenda-sorting-strategy-selected nil)
22438 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
22439 (catch 'exit
22440 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
22441 ((and todayp (member 'today (car org-agenda-time-grid))))
22442 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
22443 ((member 'weekly (car org-agenda-time-grid)))
22444 (t (throw 'exit list)))
22445 (let* ((have (delq nil (mapcar
22446 (lambda (x) (get-text-property 1 'time-of-day x))
22447 list)))
22448 (string (nth 1 org-agenda-time-grid))
22449 (gridtimes (nth 2 org-agenda-time-grid))
22450 (req (car org-agenda-time-grid))
22451 (remove (member 'remove-match req))
22452 new time)
22453 (if (and (member 'require-timed req) (not have))
22454 ;; don't show empty grid
22455 (throw 'exit list))
22456 (while (setq time (pop gridtimes))
22457 (unless (and remove (member time have))
22458 (setq time (int-to-string time))
22459 (push (org-format-agenda-item
22460 nil string "" nil
22461 (concat (substring time 0 -2) ":" (substring time -2)))
22462 new)
22463 (put-text-property
22464 1 (length (car new)) 'face 'org-time-grid (car new))))
22465 (if (member 'time-up org-agenda-sorting-strategy-selected)
22466 (append new list)
22467 (append list new)))))
22469 (defun org-compile-prefix-format (key)
22470 "Compile the prefix format into a Lisp form that can be evaluated.
22471 The resulting form is returned and stored in the variable
22472 `org-prefix-format-compiled'."
22473 (setq org-prefix-has-time nil org-prefix-has-tag nil)
22474 (let ((s (cond
22475 ((stringp org-agenda-prefix-format)
22476 org-agenda-prefix-format)
22477 ((assq key org-agenda-prefix-format)
22478 (cdr (assq key org-agenda-prefix-format)))
22479 (t " %-12:c%?-12t% s")))
22480 (start 0)
22481 varform vars var e c f opt)
22482 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
22483 s start)
22484 (setq var (cdr (assoc (match-string 4 s)
22485 '(("c" . category) ("t" . time) ("s" . extra)
22486 ("T" . tag))))
22487 c (or (match-string 3 s) "")
22488 opt (match-beginning 1)
22489 start (1+ (match-beginning 0)))
22490 (if (equal var 'time) (setq org-prefix-has-time t))
22491 (if (equal var 'tag) (setq org-prefix-has-tag t))
22492 (setq f (concat "%" (match-string 2 s) "s"))
22493 (if opt
22494 (setq varform
22495 `(if (equal "" ,var)
22497 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
22498 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
22499 (setq s (replace-match "%s" t nil s))
22500 (push varform vars))
22501 (setq vars (nreverse vars))
22502 (setq org-prefix-format-compiled `(format ,s ,@vars))))
22504 (defun org-set-sorting-strategy (key)
22505 (if (symbolp (car org-agenda-sorting-strategy))
22506 ;; the old format
22507 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
22508 (setq org-agenda-sorting-strategy-selected
22509 (or (cdr (assq key org-agenda-sorting-strategy))
22510 (cdr (assq 'agenda org-agenda-sorting-strategy))
22511 '(time-up category-keep priority-down)))))
22513 (defun org-get-time-of-day (s &optional string mod24)
22514 "Check string S for a time of day.
22515 If found, return it as a military time number between 0 and 2400.
22516 If not found, return nil.
22517 The optional STRING argument forces conversion into a 5 character wide string
22518 HH:MM."
22519 (save-match-data
22520 (when
22521 (or (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
22522 (string-match "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
22523 (let* ((h (string-to-number (match-string 1 s)))
22524 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
22525 (ampm (if (match-end 4) (downcase (match-string 4 s))))
22526 (am-p (equal ampm "am"))
22527 (h1 (cond ((not ampm) h)
22528 ((= h 12) (if am-p 0 12))
22529 (t (+ h (if am-p 0 12)))))
22530 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
22531 (mod h1 24) h1))
22532 (t0 (+ (* 100 h2) m))
22533 (t1 (concat (if (>= h1 24) "+" " ")
22534 (if (< t0 100) "0" "")
22535 (if (< t0 10) "0" "")
22536 (int-to-string t0))))
22537 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
22539 (defun org-finalize-agenda-entries (list &optional nosort)
22540 "Sort and concatenate the agenda items."
22541 (setq list (mapcar 'org-agenda-highlight-todo list))
22542 (if nosort
22543 list
22544 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
22546 (defun org-agenda-highlight-todo (x)
22547 (let (re pl)
22548 (if (eq x 'line)
22549 (save-excursion
22550 (beginning-of-line 1)
22551 (setq re (get-text-property (point) 'org-todo-regexp))
22552 (goto-char (+ (point) (or (get-text-property (point) 'prefix-length) 0)))
22553 (when (looking-at (concat "[ \t]*\\.*" re " +"))
22554 (add-text-properties (match-beginning 0) (match-end 0)
22555 (list 'face (org-get-todo-face 0)))
22556 (let ((s (buffer-substring (match-beginning 1) (match-end 1))))
22557 (delete-region (match-beginning 1) (1- (match-end 0)))
22558 (goto-char (match-beginning 1))
22559 (insert (format org-agenda-todo-keyword-format s)))))
22560 (setq re (concat (get-text-property 0 'org-todo-regexp x))
22561 pl (get-text-property 0 'prefix-length x))
22562 (when (and re
22563 (equal (string-match (concat "\\(\\.*\\)" re "\\( +\\)")
22564 x (or pl 0)) pl))
22565 (add-text-properties
22566 (or (match-end 1) (match-end 0)) (match-end 0)
22567 (list 'face (org-get-todo-face (match-string 2 x)))
22569 (setq x (concat (substring x 0 (match-end 1))
22570 (format org-agenda-todo-keyword-format
22571 (match-string 2 x))
22573 (substring x (match-end 3)))))
22574 x)))
22576 (defsubst org-cmp-priority (a b)
22577 "Compare the priorities of string A and B."
22578 (let ((pa (or (get-text-property 1 'priority a) 0))
22579 (pb (or (get-text-property 1 'priority b) 0)))
22580 (cond ((> pa pb) +1)
22581 ((< pa pb) -1)
22582 (t nil))))
22584 (defsubst org-cmp-category (a b)
22585 "Compare the string values of categories of strings A and B."
22586 (let ((ca (or (get-text-property 1 'org-category a) ""))
22587 (cb (or (get-text-property 1 'org-category b) "")))
22588 (cond ((string-lessp ca cb) -1)
22589 ((string-lessp cb ca) +1)
22590 (t nil))))
22592 (defsubst org-cmp-tag (a b)
22593 "Compare the string values of categories of strings A and B."
22594 (let ((ta (car (last (get-text-property 1 'tags a))))
22595 (tb (car (last (get-text-property 1 'tags b)))))
22596 (cond ((not ta) +1)
22597 ((not tb) -1)
22598 ((string-lessp ta tb) -1)
22599 ((string-lessp tb ta) +1)
22600 (t nil))))
22602 (defsubst org-cmp-time (a b)
22603 "Compare the time-of-day values of strings A and B."
22604 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
22605 (ta (or (get-text-property 1 'time-of-day a) def))
22606 (tb (or (get-text-property 1 'time-of-day b) def)))
22607 (cond ((< ta tb) -1)
22608 ((< tb ta) +1)
22609 (t nil))))
22611 (defun org-entries-lessp (a b)
22612 "Predicate for sorting agenda entries."
22613 ;; The following variables will be used when the form is evaluated.
22614 ;; So even though the compiler complains, keep them.
22615 (let* ((time-up (org-cmp-time a b))
22616 (time-down (if time-up (- time-up) nil))
22617 (priority-up (org-cmp-priority a b))
22618 (priority-down (if priority-up (- priority-up) nil))
22619 (category-up (org-cmp-category a b))
22620 (category-down (if category-up (- category-up) nil))
22621 (category-keep (if category-up +1 nil))
22622 (tag-up (org-cmp-tag a b))
22623 (tag-down (if tag-up (- tag-up) nil)))
22624 (cdr (assoc
22625 (eval (cons 'or org-agenda-sorting-strategy-selected))
22626 '((-1 . t) (1 . nil) (nil . nil))))))
22628 ;;; Agenda restriction lock
22630 (defvar org-agenda-restriction-lock-overlay (org-make-overlay 1 1)
22631 "Overlay to mark the headline to which arenda commands are restricted.")
22632 (org-overlay-put org-agenda-restriction-lock-overlay
22633 'face 'org-agenda-restriction-lock)
22634 (org-overlay-put org-agenda-restriction-lock-overlay
22635 'help-echo "Agendas are currently limited to this subtree.")
22636 (org-detach-overlay org-agenda-restriction-lock-overlay)
22637 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
22638 "Overlay marking the agenda restriction line in speedbar.")
22639 (org-overlay-put org-speedbar-restriction-lock-overlay
22640 'face 'org-agenda-restriction-lock)
22641 (org-overlay-put org-speedbar-restriction-lock-overlay
22642 'help-echo "Agendas are currently limited to this item.")
22643 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22645 (defun org-agenda-set-restriction-lock (&optional type)
22646 "Set restriction lock for agenda, to current subtree or file.
22647 Restriction will be the file if TYPE is `file', or if type is the
22648 universal prefix '(4), or if the cursor is before the first headline
22649 in the file. Otherwise, restriction will be to the current subtree."
22650 (interactive "P")
22651 (and (equal type '(4)) (setq type 'file))
22652 (setq type (cond
22653 (type type)
22654 ((org-at-heading-p) 'subtree)
22655 ((condition-case nil (org-back-to-heading t) (error nil))
22656 'subtree)
22657 (t 'file)))
22658 (if (eq type 'subtree)
22659 (progn
22660 (setq org-agenda-restrict t)
22661 (setq org-agenda-overriding-restriction 'subtree)
22662 (put 'org-agenda-files 'org-restrict
22663 (list (buffer-file-name (buffer-base-buffer))))
22664 (org-back-to-heading t)
22665 (org-move-overlay org-agenda-restriction-lock-overlay (point) (point-at-eol))
22666 (move-marker org-agenda-restrict-begin (point))
22667 (move-marker org-agenda-restrict-end
22668 (save-excursion (org-end-of-subtree t)))
22669 (message "Locking agenda restriction to subtree"))
22670 (put 'org-agenda-files 'org-restrict
22671 (list (buffer-file-name (buffer-base-buffer))))
22672 (setq org-agenda-restrict nil)
22673 (setq org-agenda-overriding-restriction 'file)
22674 (move-marker org-agenda-restrict-begin nil)
22675 (move-marker org-agenda-restrict-end nil)
22676 (message "Locking agenda restriction to file"))
22677 (setq current-prefix-arg nil)
22678 (org-agenda-maybe-redo))
22680 (defun org-agenda-remove-restriction-lock (&optional noupdate)
22681 "Remove the agenda restriction lock."
22682 (interactive "P")
22683 (org-detach-overlay org-agenda-restriction-lock-overlay)
22684 (org-detach-overlay org-speedbar-restriction-lock-overlay)
22685 (setq org-agenda-overriding-restriction nil)
22686 (setq org-agenda-restrict nil)
22687 (put 'org-agenda-files 'org-restrict nil)
22688 (move-marker org-agenda-restrict-begin nil)
22689 (move-marker org-agenda-restrict-end nil)
22690 (setq current-prefix-arg nil)
22691 (message "Agenda restriction lock removed")
22692 (or noupdate (org-agenda-maybe-redo)))
22694 (defun org-agenda-maybe-redo ()
22695 "If there is any window showing the agenda view, update it."
22696 (let ((w (get-buffer-window org-agenda-buffer-name t))
22697 (w0 (selected-window)))
22698 (when w
22699 (select-window w)
22700 (org-agenda-redo)
22701 (select-window w0)
22702 (if org-agenda-overriding-restriction
22703 (message "Agenda view shifted to new %s restriction"
22704 org-agenda-overriding-restriction)
22705 (message "Agenda restriction lock removed")))))
22707 ;;; Agenda commands
22709 (defun org-agenda-check-type (error &rest types)
22710 "Check if agenda buffer is of allowed type.
22711 If ERROR is non-nil, throw an error, otherwise just return nil."
22712 (if (memq org-agenda-type types)
22714 (if error
22715 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
22716 nil)))
22718 (defun org-agenda-quit ()
22719 "Exit agenda by removing the window or the buffer."
22720 (interactive)
22721 (let ((buf (current-buffer)))
22722 (if (not (one-window-p)) (delete-window))
22723 (kill-buffer buf)
22724 (org-agenda-reset-markers)
22725 (org-columns-remove-overlays))
22726 ;; Maybe restore the pre-agenda window configuration.
22727 (and org-agenda-restore-windows-after-quit
22728 (not (eq org-agenda-window-setup 'other-frame))
22729 org-pre-agenda-window-conf
22730 (set-window-configuration org-pre-agenda-window-conf)))
22732 (defun org-agenda-exit ()
22733 "Exit agenda by removing the window or the buffer.
22734 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
22735 Org-mode buffers visited directly by the user will not be touched."
22736 (interactive)
22737 (org-release-buffers org-agenda-new-buffers)
22738 (setq org-agenda-new-buffers nil)
22739 (org-agenda-quit))
22741 (defun org-agenda-execute (arg)
22742 "Execute another agenda command, keeping same window.\\<global-map>
22743 So this is just a shortcut for `\\[org-agenda]', available in the agenda."
22744 (interactive "P")
22745 (let ((org-agenda-window-setup 'current-window))
22746 (org-agenda arg)))
22748 (defun org-save-all-org-buffers ()
22749 "Save all Org-mode buffers without user confirmation."
22750 (interactive)
22751 (message "Saving all Org-mode buffers...")
22752 (save-some-buffers t 'org-mode-p)
22753 (message "Saving all Org-mode buffers... done"))
22755 (defun org-agenda-redo ()
22756 "Rebuild Agenda.
22757 When this is the global TODO list, a prefix argument will be interpreted."
22758 (interactive)
22759 (let* ((org-agenda-keep-modes t)
22760 (line (org-current-line))
22761 (window-line (- line (org-current-line (window-start))))
22762 (lprops (get 'org-agenda-redo-command 'org-lprops)))
22763 (message "Rebuilding agenda buffer...")
22764 (org-let lprops '(eval org-agenda-redo-command))
22765 (setq org-agenda-undo-list nil
22766 org-agenda-pending-undo-list nil)
22767 (message "Rebuilding agenda buffer...done")
22768 (goto-line line)
22769 (recenter window-line)))
22771 (defun org-agenda-manipulate-query-add ()
22772 "Manipulate the query by adding a search term with positive selection.
22773 Positive selection means, the term must be matched for selection of an entry."
22774 (interactive)
22775 (org-agenda-manipulate-query ?\[))
22776 (defun org-agenda-manipulate-query-subtract ()
22777 "Manipulate the query by adding a search term with negative selection.
22778 Negative selection means, term must not be matched for selection of an entry."
22779 (interactive)
22780 (org-agenda-manipulate-query ?\]))
22781 (defun org-agenda-manipulate-query-add-re ()
22782 "Manipulate the query by adding a search regexp with positive selection.
22783 Positive selection means, the regexp must match for selection of an entry."
22784 (interactive)
22785 (org-agenda-manipulate-query ?\{))
22786 (defun org-agenda-manipulate-query-subtract-re ()
22787 "Manipulate the query by adding a search regexp with negative selection.
22788 Negative selection means, regexp must not match for selection of an entry."
22789 (interactive)
22790 (org-agenda-manipulate-query ?\}))
22791 (defun org-agenda-manipulate-query (char)
22792 (cond
22793 ((eq org-agenda-type 'search)
22794 (org-add-to-string
22795 'org-agenda-query-string
22796 (cdr (assoc char '((?\[ . " +") (?\] . " -")
22797 (?\{ . " +{}") (?\} . " -{}")))))
22798 (setq org-agenda-redo-command
22799 (list 'org-search-view
22800 (+ (length org-agenda-query-string)
22801 (if (member char '(?\{ ?\})) 0 1))
22802 org-agenda-query-string))
22803 (set-register org-agenda-query-register org-agenda-query-string)
22804 (org-agenda-redo))
22805 (t (error "Canot manipulate query for %s-type agenda buffers"
22806 org-agenda-type))))
22808 (defun org-add-to-string (var string)
22809 (set var (concat (symbol-value var) string)))
22811 (defun org-agenda-goto-date (date)
22812 "Jump to DATE in agenda."
22813 (interactive (list (org-read-date)))
22814 (org-agenda-list nil date))
22816 (defun org-agenda-goto-today ()
22817 "Go to today."
22818 (interactive)
22819 (org-agenda-check-type t 'timeline 'agenda)
22820 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
22821 (cond
22822 (tdpos (goto-char tdpos))
22823 ((eq org-agenda-type 'agenda)
22824 (let* ((sd (time-to-days
22825 (time-subtract (current-time)
22826 (list 0 (* 3600 org-extend-today-until) 0))))
22827 (comp (org-agenda-compute-time-span sd org-agenda-span))
22828 (org-agenda-overriding-arguments org-agenda-last-arguments))
22829 (setf (nth 1 org-agenda-overriding-arguments) (car comp))
22830 (setf (nth 2 org-agenda-overriding-arguments) (cdr comp))
22831 (org-agenda-redo)
22832 (org-agenda-find-same-or-today-or-agenda)))
22833 (t (error "Cannot find today")))))
22835 (defun org-agenda-find-same-or-today-or-agenda (&optional cnt)
22836 (goto-char
22837 (or (and cnt (text-property-any (point-min) (point-max) 'org-day-cnt cnt))
22838 (text-property-any (point-min) (point-max) 'org-today t)
22839 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
22840 (point-min))))
22842 (defun org-agenda-later (arg)
22843 "Go forward in time by thee current span.
22844 With prefix ARG, go forward that many times the current span."
22845 (interactive "p")
22846 (org-agenda-check-type t 'agenda)
22847 (let* ((span org-agenda-span)
22848 (sd org-starting-day)
22849 (greg (calendar-gregorian-from-absolute sd))
22850 (cnt (get-text-property (point) 'org-day-cnt))
22851 greg2 nd)
22852 (cond
22853 ((eq span 'day)
22854 (setq sd (+ arg sd) nd 1))
22855 ((eq span 'week)
22856 (setq sd (+ (* 7 arg) sd) nd 7))
22857 ((eq span 'month)
22858 (setq greg2 (list (+ (car greg) arg) (nth 1 greg) (nth 2 greg))
22859 sd (calendar-absolute-from-gregorian greg2))
22860 (setcar greg2 (1+ (car greg2)))
22861 (setq nd (- (calendar-absolute-from-gregorian greg2) sd)))
22862 ((eq span 'year)
22863 (setq greg2 (list (car greg) (nth 1 greg) (+ arg (nth 2 greg)))
22864 sd (calendar-absolute-from-gregorian greg2))
22865 (setcar (nthcdr 2 greg2) (1+ (nth 2 greg2)))
22866 (setq nd (- (calendar-absolute-from-gregorian greg2) sd))))
22867 (let ((org-agenda-overriding-arguments
22868 (list (car org-agenda-last-arguments) sd nd t)))
22869 (org-agenda-redo)
22870 (org-agenda-find-same-or-today-or-agenda cnt))))
22872 (defun org-agenda-earlier (arg)
22873 "Go backward in time by the current span.
22874 With prefix ARG, go backward that many times the current span."
22875 (interactive "p")
22876 (org-agenda-later (- arg)))
22878 (defun org-agenda-day-view ()
22879 "Switch to daily view for agenda."
22880 (interactive)
22881 (setq org-agenda-ndays 1)
22882 (org-agenda-change-time-span 'day))
22883 (defun org-agenda-week-view ()
22884 "Switch to daily view for agenda."
22885 (interactive)
22886 (setq org-agenda-ndays 7)
22887 (org-agenda-change-time-span 'week))
22888 (defun org-agenda-month-view ()
22889 "Switch to daily view for agenda."
22890 (interactive)
22891 (org-agenda-change-time-span 'month))
22892 (defun org-agenda-year-view ()
22893 "Switch to daily view for agenda."
22894 (interactive)
22895 (if (y-or-n-p "Are you sure you want to compute the agenda for an entire year? ")
22896 (org-agenda-change-time-span 'year)
22897 (error "Abort")))
22899 (defun org-agenda-change-time-span (span)
22900 "Change the agenda view to SPAN.
22901 SPAN may be `day', `week', `month', `year'."
22902 (org-agenda-check-type t 'agenda)
22903 (if (equal org-agenda-span span)
22904 (error "Viewing span is already \"%s\"" span))
22905 (let* ((sd (or (get-text-property (point) 'day)
22906 org-starting-day))
22907 (computed (org-agenda-compute-time-span sd span))
22908 (org-agenda-overriding-arguments
22909 (list (car org-agenda-last-arguments)
22910 (car computed) (cdr computed) t)))
22911 (org-agenda-redo)
22912 (org-agenda-find-same-or-today-or-agenda))
22913 (org-agenda-set-mode-name)
22914 (message "Switched to %s view" span))
22916 (defun org-agenda-compute-time-span (sd span)
22917 "Compute starting date and number of days for agenda.
22918 SPAN may be `day', `week', `month', `year'. The return value
22919 is a cons cell with the starting date and the number of days,
22920 so that the date SD will be in that range."
22921 (let* ((greg (calendar-gregorian-from-absolute sd))
22923 (cond
22924 ((eq span 'day)
22925 (setq nd 1))
22926 ((eq span 'week)
22927 (let* ((nt (calendar-day-of-week
22928 (calendar-gregorian-from-absolute sd)))
22929 (d (if org-agenda-start-on-weekday
22930 (- nt org-agenda-start-on-weekday)
22931 0)))
22932 (setq sd (- sd (+ (if (< d 0) 7 0) d)))
22933 (setq nd 7)))
22934 ((eq span 'month)
22935 (setq sd (calendar-absolute-from-gregorian
22936 (list (car greg) 1 (nth 2 greg)))
22937 nd (- (calendar-absolute-from-gregorian
22938 (list (1+ (car greg)) 1 (nth 2 greg)))
22939 sd)))
22940 ((eq span 'year)
22941 (setq sd (calendar-absolute-from-gregorian
22942 (list 1 1 (nth 2 greg)))
22943 nd (- (calendar-absolute-from-gregorian
22944 (list 1 1 (1+ (nth 2 greg))))
22945 sd))))
22946 (cons sd nd)))
22948 ;; FIXME: does not work if user makes date format that starts with a blank
22949 (defun org-agenda-next-date-line (&optional arg)
22950 "Jump to the next line indicating a date in agenda buffer."
22951 (interactive "p")
22952 (org-agenda-check-type t 'agenda 'timeline)
22953 (beginning-of-line 1)
22954 (if (looking-at "^\\S-") (forward-char 1))
22955 (if (not (re-search-forward "^\\S-" nil t arg))
22956 (progn
22957 (backward-char 1)
22958 (error "No next date after this line in this buffer")))
22959 (goto-char (match-beginning 0)))
22961 (defun org-agenda-previous-date-line (&optional arg)
22962 "Jump to the previous line indicating a date in agenda buffer."
22963 (interactive "p")
22964 (org-agenda-check-type t 'agenda 'timeline)
22965 (beginning-of-line 1)
22966 (if (not (re-search-backward "^\\S-" nil t arg))
22967 (error "No previous date before this line in this buffer")))
22969 ;; Initialize the highlight
22970 (defvar org-hl (org-make-overlay 1 1))
22971 (org-overlay-put org-hl 'face 'highlight)
22973 (defun org-highlight (begin end &optional buffer)
22974 "Highlight a region with overlay."
22975 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
22976 org-hl begin end (or buffer (current-buffer))))
22978 (defun org-unhighlight ()
22979 "Detach overlay INDEX."
22980 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
22982 ;; FIXME this is currently not used.
22983 (defun org-highlight-until-next-command (beg end &optional buffer)
22984 (org-highlight beg end buffer)
22985 (add-hook 'pre-command-hook 'org-unhighlight-once))
22986 (defun org-unhighlight-once ()
22987 (remove-hook 'pre-command-hook 'org-unhighlight-once)
22988 (org-unhighlight))
22990 (defun org-agenda-follow-mode ()
22991 "Toggle follow mode in an agenda buffer."
22992 (interactive)
22993 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
22994 (org-agenda-set-mode-name)
22995 (message "Follow mode is %s"
22996 (if org-agenda-follow-mode "on" "off")))
22998 (defun org-agenda-log-mode ()
22999 "Toggle log mode in an agenda buffer."
23000 (interactive)
23001 (org-agenda-check-type t 'agenda 'timeline)
23002 (setq org-agenda-show-log (not org-agenda-show-log))
23003 (org-agenda-set-mode-name)
23004 (org-agenda-redo)
23005 (message "Log mode is %s"
23006 (if org-agenda-show-log "on" "off")))
23008 (defun org-agenda-toggle-diary ()
23009 "Toggle diary inclusion in an agenda buffer."
23010 (interactive)
23011 (org-agenda-check-type t 'agenda)
23012 (setq org-agenda-include-diary (not org-agenda-include-diary))
23013 (org-agenda-redo)
23014 (org-agenda-set-mode-name)
23015 (message "Diary inclusion turned %s"
23016 (if org-agenda-include-diary "on" "off")))
23018 (defun org-agenda-toggle-time-grid ()
23019 "Toggle time grid in an agenda buffer."
23020 (interactive)
23021 (org-agenda-check-type t 'agenda)
23022 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
23023 (org-agenda-redo)
23024 (org-agenda-set-mode-name)
23025 (message "Time-grid turned %s"
23026 (if org-agenda-use-time-grid "on" "off")))
23028 (defun org-agenda-set-mode-name ()
23029 "Set the mode name to indicate all the small mode settings."
23030 (setq mode-name
23031 (concat "Org-Agenda"
23032 (if (equal org-agenda-ndays 1) " Day" "")
23033 (if (equal org-agenda-ndays 7) " Week" "")
23034 (if org-agenda-follow-mode " Follow" "")
23035 (if org-agenda-include-diary " Diary" "")
23036 (if org-agenda-use-time-grid " Grid" "")
23037 (if org-agenda-show-log " Log" "")))
23038 (force-mode-line-update))
23040 (defun org-agenda-post-command-hook ()
23041 (and (eolp) (not (bolp)) (backward-char 1))
23042 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
23043 (if (and org-agenda-follow-mode
23044 (get-text-property (point) 'org-marker))
23045 (org-agenda-show)))
23047 (defun org-agenda-show-priority ()
23048 "Show the priority of the current item.
23049 This priority is composed of the main priority given with the [#A] cookies,
23050 and by additional input from the age of a schedules or deadline entry."
23051 (interactive)
23052 (let* ((pri (get-text-property (point-at-bol) 'priority)))
23053 (message "Priority is %d" (if pri pri -1000))))
23055 (defun org-agenda-show-tags ()
23056 "Show the tags applicable to the current item."
23057 (interactive)
23058 (let* ((tags (get-text-property (point-at-bol) 'tags)))
23059 (if tags
23060 (message "Tags are :%s:"
23061 (org-no-properties (mapconcat 'identity tags ":")))
23062 (message "No tags associated with this line"))))
23064 (defun org-agenda-goto (&optional highlight)
23065 "Go to the Org-mode file which contains the item at point."
23066 (interactive)
23067 (let* ((marker (or (get-text-property (point) 'org-marker)
23068 (org-agenda-error)))
23069 (buffer (marker-buffer marker))
23070 (pos (marker-position marker)))
23071 (switch-to-buffer-other-window buffer)
23072 (widen)
23073 (goto-char pos)
23074 (when (org-mode-p)
23075 (org-show-context 'agenda)
23076 (save-excursion
23077 (and (outline-next-heading)
23078 (org-flag-heading nil)))) ; show the next heading
23079 (recenter (/ (window-height) 2))
23080 (run-hooks 'org-agenda-after-show-hook)
23081 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
23083 (defvar org-agenda-after-show-hook nil
23084 "Normal hook run after an item has been shown from the agenda.
23085 Point is in the buffer where the item originated.")
23087 (defun org-agenda-kill ()
23088 "Kill the entry or subtree belonging to the current agenda entry."
23089 (interactive)
23090 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23091 (let* ((marker (or (get-text-property (point) 'org-marker)
23092 (org-agenda-error)))
23093 (buffer (marker-buffer marker))
23094 (pos (marker-position marker))
23095 (type (get-text-property (point) 'type))
23096 dbeg dend (n 0) conf)
23097 (org-with-remote-undo buffer
23098 (with-current-buffer buffer
23099 (save-excursion
23100 (goto-char pos)
23101 (if (and (org-mode-p) (not (member type '("sexp"))))
23102 (setq dbeg (progn (org-back-to-heading t) (point))
23103 dend (org-end-of-subtree t t))
23104 (setq dbeg (point-at-bol)
23105 dend (min (point-max) (1+ (point-at-eol)))))
23106 (goto-char dbeg)
23107 (while (re-search-forward "^[ \t]*\\S-" dend t) (setq n (1+ n)))))
23108 (setq conf (or (eq t org-agenda-confirm-kill)
23109 (and (numberp org-agenda-confirm-kill)
23110 (> n org-agenda-confirm-kill))))
23111 (and conf
23112 (not (y-or-n-p
23113 (format "Delete entry with %d lines in buffer \"%s\"? "
23114 n (buffer-name buffer))))
23115 (error "Abort"))
23116 (org-remove-subtree-entries-from-agenda buffer dbeg dend)
23117 (with-current-buffer buffer (delete-region dbeg dend))
23118 (message "Agenda item and source killed"))))
23120 (defun org-agenda-archive ()
23121 "Kill the entry or subtree belonging to the current agenda entry."
23122 (interactive)
23123 (or (eq major-mode 'org-agenda-mode) (error "Not in agenda"))
23124 (let* ((marker (or (get-text-property (point) 'org-marker)
23125 (org-agenda-error)))
23126 (buffer (marker-buffer marker))
23127 (pos (marker-position marker)))
23128 (org-with-remote-undo buffer
23129 (with-current-buffer buffer
23130 (if (org-mode-p)
23131 (save-excursion
23132 (goto-char pos)
23133 (org-remove-subtree-entries-from-agenda)
23134 (org-back-to-heading t)
23135 (org-archive-subtree))
23136 (error "Archiving works only in Org-mode files"))))))
23138 (defun org-remove-subtree-entries-from-agenda (&optional buf beg end)
23139 "Remove all lines in the agenda that correspond to a given subtree.
23140 The subtree is the one in buffer BUF, starting at BEG and ending at END.
23141 If this information is not given, the function uses the tree at point."
23142 (let ((buf (or buf (current-buffer))) m p)
23143 (save-excursion
23144 (unless (and beg end)
23145 (org-back-to-heading t)
23146 (setq beg (point))
23147 (org-end-of-subtree t)
23148 (setq end (point)))
23149 (set-buffer (get-buffer org-agenda-buffer-name))
23150 (save-excursion
23151 (goto-char (point-max))
23152 (beginning-of-line 1)
23153 (while (not (bobp))
23154 (when (and (setq m (get-text-property (point) 'org-marker))
23155 (equal buf (marker-buffer m))
23156 (setq p (marker-position m))
23157 (>= p beg)
23158 (<= p end))
23159 (let ((inhibit-read-only t))
23160 (delete-region (point-at-bol) (1+ (point-at-eol)))))
23161 (beginning-of-line 0))))))
23163 (defun org-agenda-open-link ()
23164 "Follow the link in the current line, if any."
23165 (interactive)
23166 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local)
23167 (save-excursion
23168 (save-restriction
23169 (narrow-to-region (point-at-bol) (point-at-eol))
23170 (org-open-at-point))))
23172 (defun org-agenda-copy-local-variable (var)
23173 "Get a variable from a referenced buffer and install it here."
23174 (let ((m (get-text-property (point) 'org-marker)))
23175 (when (and m (buffer-live-p (marker-buffer m)))
23176 (org-set-local var (with-current-buffer (marker-buffer m)
23177 (symbol-value var))))))
23179 (defun org-agenda-switch-to (&optional delete-other-windows)
23180 "Go to the Org-mode file which contains the item at point."
23181 (interactive)
23182 (let* ((marker (or (get-text-property (point) 'org-marker)
23183 (org-agenda-error)))
23184 (buffer (marker-buffer marker))
23185 (pos (marker-position marker)))
23186 (switch-to-buffer buffer)
23187 (and delete-other-windows (delete-other-windows))
23188 (widen)
23189 (goto-char pos)
23190 (when (org-mode-p)
23191 (org-show-context 'agenda)
23192 (save-excursion
23193 (and (outline-next-heading)
23194 (org-flag-heading nil)))))) ; show the next heading
23196 (defun org-agenda-goto-mouse (ev)
23197 "Go to the Org-mode file which contains the item at the mouse click."
23198 (interactive "e")
23199 (mouse-set-point ev)
23200 (org-agenda-goto))
23202 (defun org-agenda-show ()
23203 "Display the Org-mode file which contains the item at point."
23204 (interactive)
23205 (let ((win (selected-window)))
23206 (org-agenda-goto t)
23207 (select-window win)))
23209 (defun org-agenda-recenter (arg)
23210 "Display the Org-mode file which contains the item at point and recenter."
23211 (interactive "P")
23212 (let ((win (selected-window)))
23213 (org-agenda-goto t)
23214 (recenter arg)
23215 (select-window win)))
23217 (defun org-agenda-show-mouse (ev)
23218 "Display the Org-mode file which contains the item at the mouse click."
23219 (interactive "e")
23220 (mouse-set-point ev)
23221 (org-agenda-show))
23223 (defun org-agenda-check-no-diary ()
23224 "Check if the entry is a diary link and abort if yes."
23225 (if (get-text-property (point) 'org-agenda-diary-link)
23226 (org-agenda-error)))
23228 (defun org-agenda-error ()
23229 (error "Command not allowed in this line"))
23231 (defun org-agenda-tree-to-indirect-buffer ()
23232 "Show the subtree corresponding to the current entry in an indirect buffer.
23233 This calls the command `org-tree-to-indirect-buffer' from the original
23234 Org-mode buffer.
23235 With numerical prefix arg ARG, go up to this level and then take that tree.
23236 With a C-u prefix, make a separate frame for this tree (i.e. don't use the
23237 dedicated frame)."
23238 (interactive)
23239 (org-agenda-check-no-diary)
23240 (let* ((marker (or (get-text-property (point) 'org-marker)
23241 (org-agenda-error)))
23242 (buffer (marker-buffer marker))
23243 (pos (marker-position marker)))
23244 (with-current-buffer buffer
23245 (save-excursion
23246 (goto-char pos)
23247 (call-interactively 'org-tree-to-indirect-buffer)))))
23249 (defvar org-last-heading-marker (make-marker)
23250 "Marker pointing to the headline that last changed its TODO state
23251 by a remote command from the agenda.")
23253 (defun org-agenda-todo-nextset ()
23254 "Switch TODO entry to next sequence."
23255 (interactive)
23256 (org-agenda-todo 'nextset))
23258 (defun org-agenda-todo-previousset ()
23259 "Switch TODO entry to previous sequence."
23260 (interactive)
23261 (org-agenda-todo 'previousset))
23263 (defun org-agenda-todo (&optional arg)
23264 "Cycle TODO state of line at point, also in Org-mode file.
23265 This changes the line at point, all other lines in the agenda referring to
23266 the same tree node, and the headline of the tree node in the Org-mode file."
23267 (interactive "P")
23268 (org-agenda-check-no-diary)
23269 (let* ((col (current-column))
23270 (marker (or (get-text-property (point) 'org-marker)
23271 (org-agenda-error)))
23272 (buffer (marker-buffer marker))
23273 (pos (marker-position marker))
23274 (hdmarker (get-text-property (point) 'org-hd-marker))
23275 (inhibit-read-only t)
23276 newhead)
23277 (org-with-remote-undo buffer
23278 (with-current-buffer buffer
23279 (widen)
23280 (goto-char pos)
23281 (org-show-context 'agenda)
23282 (save-excursion
23283 (and (outline-next-heading)
23284 (org-flag-heading nil))) ; show the next heading
23285 (org-todo arg)
23286 (and (bolp) (forward-char 1))
23287 (setq newhead (org-get-heading))
23288 (save-excursion
23289 (org-back-to-heading)
23290 (move-marker org-last-heading-marker (point))))
23291 (beginning-of-line 1)
23292 (save-excursion
23293 (org-agenda-change-all-lines newhead hdmarker 'fixface))
23294 (move-to-column col))))
23296 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
23297 "Change all lines in the agenda buffer which match HDMARKER.
23298 The new content of the line will be NEWHEAD (as modified by
23299 `org-format-agenda-item'). HDMARKER is checked with
23300 `equal' against all `org-hd-marker' text properties in the file.
23301 If FIXFACE is non-nil, the face of each item is modified acording to
23302 the new TODO state."
23303 (let* ((inhibit-read-only t)
23304 props m pl undone-face done-face finish new dotime cat tags)
23305 (save-excursion
23306 (goto-char (point-max))
23307 (beginning-of-line 1)
23308 (while (not finish)
23309 (setq finish (bobp))
23310 (when (and (setq m (get-text-property (point) 'org-hd-marker))
23311 (equal m hdmarker))
23312 (setq props (text-properties-at (point))
23313 dotime (get-text-property (point) 'dotime)
23314 cat (get-text-property (point) 'org-category)
23315 tags (get-text-property (point) 'tags)
23316 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
23317 pl (get-text-property (point) 'prefix-length)
23318 undone-face (get-text-property (point) 'undone-face)
23319 done-face (get-text-property (point) 'done-face))
23320 (move-to-column pl)
23321 (cond
23322 ((equal new "")
23323 (beginning-of-line 1)
23324 (and (looking-at ".*\n?") (replace-match "")))
23325 ((looking-at ".*")
23326 (replace-match new t t)
23327 (beginning-of-line 1)
23328 (add-text-properties (point-at-bol) (point-at-eol) props)
23329 (when fixface
23330 (add-text-properties
23331 (point-at-bol) (point-at-eol)
23332 (list 'face
23333 (if org-last-todo-state-is-todo
23334 undone-face done-face))))
23335 (org-agenda-highlight-todo 'line)
23336 (beginning-of-line 1))
23337 (t (error "Line update did not work"))))
23338 (beginning-of-line 0)))
23339 (org-finalize-agenda)))
23341 (defun org-agenda-align-tags (&optional line)
23342 "Align all tags in agenda items to `org-agenda-tags-column'."
23343 (let ((inhibit-read-only t) l c)
23344 (save-excursion
23345 (goto-char (if line (point-at-bol) (point-min)))
23346 (while (re-search-forward (org-re "\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$")
23347 (if line (point-at-eol) nil) t)
23348 (add-text-properties
23349 (match-beginning 2) (match-end 2)
23350 (list 'face (delq nil (list 'org-tag (get-text-property
23351 (match-beginning 2) 'face)))))
23352 (setq l (- (match-end 2) (match-beginning 2))
23353 c (if (< org-agenda-tags-column 0)
23354 (- (abs org-agenda-tags-column) l)
23355 org-agenda-tags-column))
23356 (delete-region (match-beginning 1) (match-end 1))
23357 (goto-char (match-beginning 1))
23358 (insert (org-add-props
23359 (make-string (max 1 (- c (current-column))) ?\ )
23360 (text-properties-at (point))))))))
23362 (defun org-agenda-priority-up ()
23363 "Increase the priority of line at point, also in Org-mode file."
23364 (interactive)
23365 (org-agenda-priority 'up))
23367 (defun org-agenda-priority-down ()
23368 "Decrease the priority of line at point, also in Org-mode file."
23369 (interactive)
23370 (org-agenda-priority 'down))
23372 (defun org-agenda-priority (&optional force-direction)
23373 "Set the priority of line at point, also in Org-mode file.
23374 This changes the line at point, all other lines in the agenda referring to
23375 the same tree node, and the headline of the tree node in the Org-mode file."
23376 (interactive)
23377 (org-agenda-check-no-diary)
23378 (let* ((marker (or (get-text-property (point) 'org-marker)
23379 (org-agenda-error)))
23380 (hdmarker (get-text-property (point) 'org-hd-marker))
23381 (buffer (marker-buffer hdmarker))
23382 (pos (marker-position hdmarker))
23383 (inhibit-read-only t)
23384 newhead)
23385 (org-with-remote-undo buffer
23386 (with-current-buffer buffer
23387 (widen)
23388 (goto-char pos)
23389 (org-show-context 'agenda)
23390 (save-excursion
23391 (and (outline-next-heading)
23392 (org-flag-heading nil))) ; show the next heading
23393 (funcall 'org-priority force-direction)
23394 (end-of-line 1)
23395 (setq newhead (org-get-heading)))
23396 (org-agenda-change-all-lines newhead hdmarker)
23397 (beginning-of-line 1))))
23399 (defun org-get-tags-at (&optional pos)
23400 "Get a list of all headline tags applicable at POS.
23401 POS defaults to point. If tags are inherited, the list contains
23402 the targets in the same sequence as the headlines appear, i.e.
23403 the tags of the current headline come last."
23404 (interactive)
23405 (let (tags lastpos)
23406 (save-excursion
23407 (save-restriction
23408 (widen)
23409 (goto-char (or pos (point)))
23410 (save-match-data
23411 (condition-case nil
23412 (progn
23413 (org-back-to-heading t)
23414 (while (not (equal lastpos (point)))
23415 (setq lastpos (point))
23416 (if (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
23417 (setq tags (append (org-split-string
23418 (org-match-string-no-properties 1) ":")
23419 tags)))
23420 (or org-use-tag-inheritance (error ""))
23421 (org-up-heading-all 1)))
23422 (error nil))))
23423 tags)))
23425 ;; FIXME: should fix the tags property of the agenda line.
23426 (defun org-agenda-set-tags ()
23427 "Set tags for the current headline."
23428 (interactive)
23429 (org-agenda-check-no-diary)
23430 (if (and (org-region-active-p) (interactive-p))
23431 (call-interactively 'org-change-tag-in-region)
23432 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23433 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23434 (org-agenda-error)))
23435 (buffer (marker-buffer hdmarker))
23436 (pos (marker-position hdmarker))
23437 (inhibit-read-only t)
23438 newhead)
23439 (org-with-remote-undo buffer
23440 (with-current-buffer buffer
23441 (widen)
23442 (goto-char pos)
23443 (save-excursion
23444 (org-show-context 'agenda))
23445 (save-excursion
23446 (and (outline-next-heading)
23447 (org-flag-heading nil))) ; show the next heading
23448 (goto-char pos)
23449 (call-interactively 'org-set-tags)
23450 (end-of-line 1)
23451 (setq newhead (org-get-heading)))
23452 (org-agenda-change-all-lines newhead hdmarker)
23453 (beginning-of-line 1)))))
23455 (defun org-agenda-toggle-archive-tag ()
23456 "Toggle the archive tag for the current entry."
23457 (interactive)
23458 (org-agenda-check-no-diary)
23459 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
23460 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
23461 (org-agenda-error)))
23462 (buffer (marker-buffer hdmarker))
23463 (pos (marker-position hdmarker))
23464 (inhibit-read-only t)
23465 newhead)
23466 (org-with-remote-undo buffer
23467 (with-current-buffer buffer
23468 (widen)
23469 (goto-char pos)
23470 (org-show-context 'agenda)
23471 (save-excursion
23472 (and (outline-next-heading)
23473 (org-flag-heading nil))) ; show the next heading
23474 (call-interactively 'org-toggle-archive-tag)
23475 (end-of-line 1)
23476 (setq newhead (org-get-heading)))
23477 (org-agenda-change-all-lines newhead hdmarker)
23478 (beginning-of-line 1))))
23480 (defun org-agenda-date-later (arg &optional what)
23481 "Change the date of this item to one day later."
23482 (interactive "p")
23483 (org-agenda-check-type t 'agenda 'timeline)
23484 (org-agenda-check-no-diary)
23485 (let* ((marker (or (get-text-property (point) 'org-marker)
23486 (org-agenda-error)))
23487 (buffer (marker-buffer marker))
23488 (pos (marker-position marker)))
23489 (org-with-remote-undo buffer
23490 (with-current-buffer buffer
23491 (widen)
23492 (goto-char pos)
23493 (if (not (org-at-timestamp-p))
23494 (error "Cannot find time stamp"))
23495 (org-timestamp-change arg (or what 'day)))
23496 (org-agenda-show-new-time marker org-last-changed-timestamp))
23497 (message "Time stamp changed to %s" org-last-changed-timestamp)))
23499 (defun org-agenda-date-earlier (arg &optional what)
23500 "Change the date of this item to one day earlier."
23501 (interactive "p")
23502 (org-agenda-date-later (- arg) what))
23504 (defun org-agenda-show-new-time (marker stamp &optional prefix)
23505 "Show new date stamp via text properties."
23506 ;; We use text properties to make this undoable
23507 (let ((inhibit-read-only t))
23508 (setq stamp (concat " " prefix " => " stamp))
23509 (save-excursion
23510 (goto-char (point-max))
23511 (while (not (bobp))
23512 (when (equal marker (get-text-property (point) 'org-marker))
23513 (move-to-column (- (window-width) (length stamp)) t)
23514 (if (featurep 'xemacs)
23515 ;; Use `duplicable' property to trigger undo recording
23516 (let ((ex (make-extent nil nil))
23517 (gl (make-glyph stamp)))
23518 (set-glyph-face gl 'secondary-selection)
23519 (set-extent-properties
23520 ex (list 'invisible t 'end-glyph gl 'duplicable t))
23521 (insert-extent ex (1- (point)) (point-at-eol)))
23522 (add-text-properties
23523 (1- (point)) (point-at-eol)
23524 (list 'display (org-add-props stamp nil
23525 'face 'secondary-selection))))
23526 (beginning-of-line 1))
23527 (beginning-of-line 0)))))
23529 (defun org-agenda-date-prompt (arg)
23530 "Change the date of this item. Date is prompted for, with default today.
23531 The prefix ARG is passed to the `org-time-stamp' command and can therefore
23532 be used to request time specification in the time stamp."
23533 (interactive "P")
23534 (org-agenda-check-type t 'agenda 'timeline)
23535 (org-agenda-check-no-diary)
23536 (let* ((marker (or (get-text-property (point) 'org-marker)
23537 (org-agenda-error)))
23538 (buffer (marker-buffer marker))
23539 (pos (marker-position marker)))
23540 (org-with-remote-undo buffer
23541 (with-current-buffer buffer
23542 (widen)
23543 (goto-char pos)
23544 (if (not (org-at-timestamp-p))
23545 (error "Cannot find time stamp"))
23546 (org-time-stamp arg)
23547 (message "Time stamp changed to %s" org-last-changed-timestamp)))))
23549 (defun org-agenda-schedule (arg)
23550 "Schedule the item at point."
23551 (interactive "P")
23552 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23553 (org-agenda-check-no-diary)
23554 (let* ((marker (or (get-text-property (point) 'org-marker)
23555 (org-agenda-error)))
23556 (type (marker-insertion-type marker))
23557 (buffer (marker-buffer marker))
23558 (pos (marker-position marker))
23559 (org-insert-labeled-timestamps-at-point nil)
23561 (when type (message "%s" type) (sit-for 3))
23562 (set-marker-insertion-type marker t)
23563 (org-with-remote-undo buffer
23564 (with-current-buffer buffer
23565 (widen)
23566 (goto-char pos)
23567 (setq ts (org-schedule arg)))
23568 (org-agenda-show-new-time marker ts "S"))
23569 (message "Item scheduled for %s" ts)))
23571 (defun org-agenda-deadline (arg)
23572 "Schedule the item at point."
23573 (interactive "P")
23574 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
23575 (org-agenda-check-no-diary)
23576 (let* ((marker (or (get-text-property (point) 'org-marker)
23577 (org-agenda-error)))
23578 (buffer (marker-buffer marker))
23579 (pos (marker-position marker))
23580 (org-insert-labeled-timestamps-at-point nil)
23582 (org-with-remote-undo buffer
23583 (with-current-buffer buffer
23584 (widen)
23585 (goto-char pos)
23586 (setq ts (org-deadline arg)))
23587 (org-agenda-show-new-time marker ts "S"))
23588 (message "Deadline for this item set to %s" ts)))
23590 (defun org-get-heading (&optional no-tags)
23591 "Return the heading of the current entry, without the stars."
23592 (save-excursion
23593 (org-back-to-heading t)
23594 (if (looking-at
23595 (if no-tags
23596 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
23597 "\\*+[ \t]+\\([^\r\n]*\\)"))
23598 (match-string 1) "")))
23600 (defun org-agenda-clock-in (&optional arg)
23601 "Start the clock on the currently selected item."
23602 (interactive "P")
23603 (org-agenda-check-no-diary)
23604 (let* ((marker (or (get-text-property (point) 'org-marker)
23605 (org-agenda-error)))
23606 (pos (marker-position marker)))
23607 (org-with-remote-undo (marker-buffer marker)
23608 (with-current-buffer (marker-buffer marker)
23609 (widen)
23610 (goto-char pos)
23611 (org-clock-in)))))
23613 (defun org-agenda-clock-out (&optional arg)
23614 "Stop the currently running clock."
23615 (interactive "P")
23616 (unless (marker-buffer org-clock-marker)
23617 (error "No running clock"))
23618 (org-with-remote-undo (marker-buffer org-clock-marker)
23619 (org-clock-out)))
23621 (defun org-agenda-clock-cancel (&optional arg)
23622 "Cancel the currently running clock."
23623 (interactive "P")
23624 (unless (marker-buffer org-clock-marker)
23625 (error "No running clock"))
23626 (org-with-remote-undo (marker-buffer org-clock-marker)
23627 (org-clock-cancel)))
23629 (defun org-agenda-diary-entry ()
23630 "Make a diary entry, like the `i' command from the calendar.
23631 All the standard commands work: block, weekly etc."
23632 (interactive)
23633 (org-agenda-check-type t 'agenda 'timeline)
23634 (require 'diary-lib)
23635 (let* ((char (progn
23636 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
23637 (read-char-exclusive)))
23638 (cmd (cdr (assoc char
23639 '((?d . insert-diary-entry)
23640 (?w . insert-weekly-diary-entry)
23641 (?m . insert-monthly-diary-entry)
23642 (?y . insert-yearly-diary-entry)
23643 (?a . insert-anniversary-diary-entry)
23644 (?b . insert-block-diary-entry)
23645 (?c . insert-cyclic-diary-entry)))))
23646 (oldf (symbol-function 'calendar-cursor-to-date))
23647 ; (buf (get-file-buffer (substitute-in-file-name diary-file)))
23648 (point (point))
23649 (mark (or (mark t) (point))))
23650 (unless cmd
23651 (error "No command associated with <%c>" char))
23652 (unless (and (get-text-property point 'day)
23653 (or (not (equal ?b char))
23654 (get-text-property mark 'day)))
23655 (error "Don't know which date to use for diary entry"))
23656 ;; We implement this by hacking the `calendar-cursor-to-date' function
23657 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
23658 (let ((calendar-mark-ring
23659 (list (calendar-gregorian-from-absolute
23660 (or (get-text-property mark 'day)
23661 (get-text-property point 'day))))))
23662 (unwind-protect
23663 (progn
23664 (fset 'calendar-cursor-to-date
23665 (lambda (&optional error)
23666 (calendar-gregorian-from-absolute
23667 (get-text-property point 'day))))
23668 (call-interactively cmd))
23669 (fset 'calendar-cursor-to-date oldf)))))
23672 (defun org-agenda-execute-calendar-command (cmd)
23673 "Execute a calendar command from the agenda, with the date associated to
23674 the cursor position."
23675 (org-agenda-check-type t 'agenda 'timeline)
23676 (require 'diary-lib)
23677 (unless (get-text-property (point) 'day)
23678 (error "Don't know which date to use for calendar command"))
23679 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
23680 (point (point))
23681 (date (calendar-gregorian-from-absolute
23682 (get-text-property point 'day)))
23683 ;; the following 3 vars are needed in the calendar
23684 (displayed-day (extract-calendar-day date))
23685 (displayed-month (extract-calendar-month date))
23686 (displayed-year (extract-calendar-year date)))
23687 (unwind-protect
23688 (progn
23689 (fset 'calendar-cursor-to-date
23690 (lambda (&optional error)
23691 (calendar-gregorian-from-absolute
23692 (get-text-property point 'day))))
23693 (call-interactively cmd))
23694 (fset 'calendar-cursor-to-date oldf))))
23696 (defun org-agenda-phases-of-moon ()
23697 "Display the phases of the moon for the 3 months around the cursor date."
23698 (interactive)
23699 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
23701 (defun org-agenda-holidays ()
23702 "Display the holidays for the 3 months around the cursor date."
23703 (interactive)
23704 (org-agenda-execute-calendar-command 'list-calendar-holidays))
23706 (defvar calendar-longitude)
23707 (defvar calendar-latitude)
23708 (defvar calendar-location-name)
23710 (defun org-agenda-sunrise-sunset (arg)
23711 "Display sunrise and sunset for the cursor date.
23712 Latitude and longitude can be specified with the variables
23713 `calendar-latitude' and `calendar-longitude'. When called with prefix
23714 argument, latitude and longitude will be prompted for."
23715 (interactive "P")
23716 (require 'solar)
23717 (let ((calendar-longitude (if arg nil calendar-longitude))
23718 (calendar-latitude (if arg nil calendar-latitude))
23719 (calendar-location-name
23720 (if arg "the given coordinates" calendar-location-name)))
23721 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
23723 (defun org-agenda-goto-calendar ()
23724 "Open the Emacs calendar with the date at the cursor."
23725 (interactive)
23726 (org-agenda-check-type t 'agenda 'timeline)
23727 (let* ((day (or (get-text-property (point) 'day)
23728 (error "Don't know which date to open in calendar")))
23729 (date (calendar-gregorian-from-absolute day))
23730 (calendar-move-hook nil)
23731 (view-calendar-holidays-initially nil)
23732 (view-diary-entries-initially nil))
23733 (calendar)
23734 (calendar-goto-date date)))
23736 (defun org-calendar-goto-agenda ()
23737 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
23738 This is a command that has to be installed in `calendar-mode-map'."
23739 (interactive)
23740 (org-agenda-list nil (calendar-absolute-from-gregorian
23741 (calendar-cursor-to-date))
23742 nil))
23744 (defun org-agenda-convert-date ()
23745 (interactive)
23746 (org-agenda-check-type t 'agenda 'timeline)
23747 (let ((day (get-text-property (point) 'day))
23748 date s)
23749 (unless day
23750 (error "Don't know which date to convert"))
23751 (setq date (calendar-gregorian-from-absolute day))
23752 (setq s (concat
23753 "Gregorian: " (calendar-date-string date) "\n"
23754 "ISO: " (calendar-iso-date-string date) "\n"
23755 "Day of Yr: " (calendar-day-of-year-string date) "\n"
23756 "Julian: " (calendar-julian-date-string date) "\n"
23757 "Astron. JD: " (calendar-astro-date-string date)
23758 " (Julian date number at noon UTC)\n"
23759 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
23760 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
23761 "French: " (calendar-french-date-string date) "\n"
23762 "Baha'i: " (calendar-bahai-date-string date) " (until sunset)\n"
23763 "Mayan: " (calendar-mayan-date-string date) "\n"
23764 "Coptic: " (calendar-coptic-date-string date) "\n"
23765 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
23766 "Persian: " (calendar-persian-date-string date) "\n"
23767 "Chinese: " (calendar-chinese-date-string date) "\n"))
23768 (with-output-to-temp-buffer "*Dates*"
23769 (princ s))
23770 (if (fboundp 'fit-window-to-buffer)
23771 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
23774 ;;;; Embedded LaTeX
23776 (defvar org-cdlatex-mode-map (make-sparse-keymap)
23777 "Keymap for the minor `org-cdlatex-mode'.")
23779 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
23780 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
23781 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
23782 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
23783 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
23785 (defvar org-cdlatex-texmathp-advice-is-done nil
23786 "Flag remembering if we have applied the advice to texmathp already.")
23788 (define-minor-mode org-cdlatex-mode
23789 "Toggle the minor `org-cdlatex-mode'.
23790 This mode supports entering LaTeX environment and math in LaTeX fragments
23791 in Org-mode.
23792 \\{org-cdlatex-mode-map}"
23793 nil " OCDL" nil
23794 (when org-cdlatex-mode (require 'cdlatex))
23795 (unless org-cdlatex-texmathp-advice-is-done
23796 (setq org-cdlatex-texmathp-advice-is-done t)
23797 (defadvice texmathp (around org-math-always-on activate)
23798 "Always return t in org-mode buffers.
23799 This is because we want to insert math symbols without dollars even outside
23800 the LaTeX math segments. If Orgmode thinks that point is actually inside
23801 en embedded LaTeX fragement, let texmathp do its job.
23802 \\[org-cdlatex-mode-map]"
23803 (interactive)
23804 (let (p)
23805 (cond
23806 ((not (org-mode-p)) ad-do-it)
23807 ((eq this-command 'cdlatex-math-symbol)
23808 (setq ad-return-value t
23809 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
23811 (let ((p (org-inside-LaTeX-fragment-p)))
23812 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
23813 (setq ad-return-value t
23814 texmathp-why '("Org-mode embedded math" . 0))
23815 (if p ad-do-it)))))))))
23817 (defun turn-on-org-cdlatex ()
23818 "Unconditionally turn on `org-cdlatex-mode'."
23819 (org-cdlatex-mode 1))
23821 (defun org-inside-LaTeX-fragment-p ()
23822 "Test if point is inside a LaTeX fragment.
23823 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
23824 sequence appearing also before point.
23825 Even though the matchers for math are configurable, this function assumes
23826 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
23827 delimiters are skipped when they have been removed by customization.
23828 The return value is nil, or a cons cell with the delimiter and
23829 and the position of this delimiter.
23831 This function does a reasonably good job, but can locally be fooled by
23832 for example currency specifications. For example it will assume being in
23833 inline math after \"$22.34\". The LaTeX fragment formatter will only format
23834 fragments that are properly closed, but during editing, we have to live
23835 with the uncertainty caused by missing closing delimiters. This function
23836 looks only before point, not after."
23837 (catch 'exit
23838 (let ((pos (point))
23839 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
23840 (lim (progn
23841 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
23842 (point)))
23843 dd-on str (start 0) m re)
23844 (goto-char pos)
23845 (when dodollar
23846 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
23847 re (nth 1 (assoc "$" org-latex-regexps)))
23848 (while (string-match re str start)
23849 (cond
23850 ((= (match-end 0) (length str))
23851 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
23852 ((= (match-end 0) (- (length str) 5))
23853 (throw 'exit nil))
23854 (t (setq start (match-end 0))))))
23855 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
23856 (goto-char pos)
23857 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
23858 (and (match-beginning 2) (throw 'exit nil))
23859 ;; count $$
23860 (while (re-search-backward "\\$\\$" lim t)
23861 (setq dd-on (not dd-on)))
23862 (goto-char pos)
23863 (if dd-on (cons "$$" m))))))
23866 (defun org-try-cdlatex-tab ()
23867 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
23868 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
23869 - inside a LaTeX fragment, or
23870 - after the first word in a line, where an abbreviation expansion could
23871 insert a LaTeX environment."
23872 (when org-cdlatex-mode
23873 (cond
23874 ((save-excursion
23875 (skip-chars-backward "a-zA-Z0-9*")
23876 (skip-chars-backward " \t")
23877 (bolp))
23878 (cdlatex-tab) t)
23879 ((org-inside-LaTeX-fragment-p)
23880 (cdlatex-tab) t)
23881 (t nil))))
23883 (defun org-cdlatex-underscore-caret (&optional arg)
23884 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
23885 Revert to the normal definition outside of these fragments."
23886 (interactive "P")
23887 (if (org-inside-LaTeX-fragment-p)
23888 (call-interactively 'cdlatex-sub-superscript)
23889 (let (org-cdlatex-mode)
23890 (call-interactively (key-binding (vector last-input-event))))))
23892 (defun org-cdlatex-math-modify (&optional arg)
23893 "Execute `cdlatex-math-modify' in LaTeX fragments.
23894 Revert to the normal definition outside of these fragments."
23895 (interactive "P")
23896 (if (org-inside-LaTeX-fragment-p)
23897 (call-interactively 'cdlatex-math-modify)
23898 (let (org-cdlatex-mode)
23899 (call-interactively (key-binding (vector last-input-event))))))
23901 (defvar org-latex-fragment-image-overlays nil
23902 "List of overlays carrying the images of latex fragments.")
23903 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
23905 (defun org-remove-latex-fragment-image-overlays ()
23906 "Remove all overlays with LaTeX fragment images in current buffer."
23907 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
23908 (setq org-latex-fragment-image-overlays nil))
23910 (defun org-preview-latex-fragment (&optional subtree)
23911 "Preview the LaTeX fragment at point, or all locally or globally.
23912 If the cursor is in a LaTeX fragment, create the image and overlay
23913 it over the source code. If there is no fragment at point, display
23914 all fragments in the current text, from one headline to the next. With
23915 prefix SUBTREE, display all fragments in the current subtree. With a
23916 double prefix `C-u C-u', or when the cursor is before the first headline,
23917 display all fragments in the buffer.
23918 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
23919 (interactive "P")
23920 (org-remove-latex-fragment-image-overlays)
23921 (save-excursion
23922 (save-restriction
23923 (let (beg end at msg)
23924 (cond
23925 ((or (equal subtree '(16))
23926 (not (save-excursion
23927 (re-search-backward (concat "^" outline-regexp) nil t))))
23928 (setq beg (point-min) end (point-max)
23929 msg "Creating images for buffer...%s"))
23930 ((equal subtree '(4))
23931 (org-back-to-heading)
23932 (setq beg (point) end (org-end-of-subtree t)
23933 msg "Creating images for subtree...%s"))
23935 (if (setq at (org-inside-LaTeX-fragment-p))
23936 (goto-char (max (point-min) (- (cdr at) 2)))
23937 (org-back-to-heading))
23938 (setq beg (point) end (progn (outline-next-heading) (point))
23939 msg (if at "Creating image...%s"
23940 "Creating images for entry...%s"))))
23941 (message msg "")
23942 (narrow-to-region beg end)
23943 (goto-char beg)
23944 (org-format-latex
23945 (concat "ltxpng/" (file-name-sans-extension
23946 (file-name-nondirectory
23947 buffer-file-name)))
23948 default-directory 'overlays msg at 'forbuffer)
23949 (message msg "done. Use `C-c C-c' to remove images.")))))
23951 (defvar org-latex-regexps
23952 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
23953 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
23954 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
23955 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
23956 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
23957 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
23958 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
23959 "Regular expressions for matching embedded LaTeX.")
23961 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
23962 "Replace LaTeX fragments with links to an image, and produce images."
23963 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
23964 (let* ((prefixnodir (file-name-nondirectory prefix))
23965 (absprefix (expand-file-name prefix dir))
23966 (todir (file-name-directory absprefix))
23967 (opt org-format-latex-options)
23968 (matchers (plist-get opt :matchers))
23969 (re-list org-latex-regexps)
23970 (cnt 0) txt link beg end re e checkdir
23971 m n block linkfile movefile ov)
23972 ;; Check if there are old images files with this prefix, and remove them
23973 (when (file-directory-p todir)
23974 (mapc 'delete-file
23975 (directory-files
23976 todir 'full
23977 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
23978 ;; Check the different regular expressions
23979 (while (setq e (pop re-list))
23980 (setq m (car e) re (nth 1 e) n (nth 2 e)
23981 block (if (nth 3 e) "\n\n" ""))
23982 (when (member m matchers)
23983 (goto-char (point-min))
23984 (while (re-search-forward re nil t)
23985 (when (or (not at) (equal (cdr at) (match-beginning n)))
23986 (setq txt (match-string n)
23987 beg (match-beginning n) end (match-end n)
23988 cnt (1+ cnt)
23989 linkfile (format "%s_%04d.png" prefix cnt)
23990 movefile (format "%s_%04d.png" absprefix cnt)
23991 link (concat block "[[file:" linkfile "]]" block))
23992 (if msg (message msg cnt))
23993 (goto-char beg)
23994 (unless checkdir ; make sure the directory exists
23995 (setq checkdir t)
23996 (or (file-directory-p todir) (make-directory todir)))
23997 (org-create-formula-image
23998 txt movefile opt forbuffer)
23999 (if overlays
24000 (progn
24001 (setq ov (org-make-overlay beg end))
24002 (if (featurep 'xemacs)
24003 (progn
24004 (org-overlay-put ov 'invisible t)
24005 (org-overlay-put
24006 ov 'end-glyph
24007 (make-glyph (vector 'png :file movefile))))
24008 (org-overlay-put
24009 ov 'display
24010 (list 'image :type 'png :file movefile :ascent 'center)))
24011 (push ov org-latex-fragment-image-overlays)
24012 (goto-char end))
24013 (delete-region beg end)
24014 (insert link))))))))
24016 ;; This function borrows from Ganesh Swami's latex2png.el
24017 (defun org-create-formula-image (string tofile options buffer)
24018 (let* ((tmpdir (if (featurep 'xemacs)
24019 (temp-directory)
24020 temporary-file-directory))
24021 (texfilebase (make-temp-name
24022 (expand-file-name "orgtex" tmpdir)))
24023 (texfile (concat texfilebase ".tex"))
24024 (dvifile (concat texfilebase ".dvi"))
24025 (pngfile (concat texfilebase ".png"))
24026 (fnh (face-attribute 'default :height nil))
24027 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
24028 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
24029 (fg (or (plist-get options (if buffer :foreground :html-foreground))
24030 "Black"))
24031 (bg (or (plist-get options (if buffer :background :html-background))
24032 "Transparent")))
24033 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
24034 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
24035 (with-temp-file texfile
24036 (insert org-format-latex-header
24037 "\n\\begin{document}\n" string "\n\\end{document}\n"))
24038 (let ((dir default-directory))
24039 (condition-case nil
24040 (progn
24041 (cd tmpdir)
24042 (call-process "latex" nil nil nil texfile))
24043 (error nil))
24044 (cd dir))
24045 (if (not (file-exists-p dvifile))
24046 (progn (message "Failed to create dvi file from %s" texfile) nil)
24047 (call-process "dvipng" nil nil nil
24048 "-E" "-fg" fg "-bg" bg
24049 "-D" dpi
24050 ;;"-x" scale "-y" scale
24051 "-T" "tight"
24052 "-o" pngfile
24053 dvifile)
24054 (if (not (file-exists-p pngfile))
24055 (progn (message "Failed to create png file from %s" texfile) nil)
24056 ;; Use the requested file name and clean up
24057 (copy-file pngfile tofile 'replace)
24058 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
24059 (delete-file (concat texfilebase e)))
24060 pngfile))))
24062 (defun org-dvipng-color (attr)
24063 "Return an rgb color specification for dvipng."
24064 (apply 'format "rgb %s %s %s"
24065 (mapcar 'org-normalize-color
24066 (color-values (face-attribute 'default attr nil)))))
24068 (defun org-normalize-color (value)
24069 "Return string to be used as color value for an RGB component."
24070 (format "%g" (/ value 65535.0)))
24072 ;;;; Exporting
24074 ;;; Variables, constants, and parameter plists
24076 (defconst org-level-max 20)
24078 (defvar org-export-html-preamble nil
24079 "Preamble, to be inserted just after <body>. Set by publishing functions.")
24080 (defvar org-export-html-postamble nil
24081 "Preamble, to be inserted just before </body>. Set by publishing functions.")
24082 (defvar org-export-html-auto-preamble t
24083 "Should default preamble be inserted? Set by publishing functions.")
24084 (defvar org-export-html-auto-postamble t
24085 "Should default postamble be inserted? Set by publishing functions.")
24086 (defvar org-current-export-file nil) ; dynamically scoped parameter
24087 (defvar org-current-export-dir nil) ; dynamically scoped parameter
24090 (defconst org-export-plist-vars
24091 '((:language . org-export-default-language)
24092 (:customtime . org-display-custom-times)
24093 (:headline-levels . org-export-headline-levels)
24094 (:section-numbers . org-export-with-section-numbers)
24095 (:table-of-contents . org-export-with-toc)
24096 (:preserve-breaks . org-export-preserve-breaks)
24097 (:archived-trees . org-export-with-archived-trees)
24098 (:emphasize . org-export-with-emphasize)
24099 (:sub-superscript . org-export-with-sub-superscripts)
24100 (:special-strings . org-export-with-special-strings)
24101 (:footnotes . org-export-with-footnotes)
24102 (:drawers . org-export-with-drawers)
24103 (:tags . org-export-with-tags)
24104 (:TeX-macros . org-export-with-TeX-macros)
24105 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
24106 (:skip-before-1st-heading . org-export-skip-text-before-1st-heading)
24107 (:fixed-width . org-export-with-fixed-width)
24108 (:timestamps . org-export-with-timestamps)
24109 (:author-info . org-export-author-info)
24110 (:time-stamp-file . org-export-time-stamp-file)
24111 (:tables . org-export-with-tables)
24112 (:table-auto-headline . org-export-highlight-first-table-line)
24113 (:style . org-export-html-style)
24114 (:agenda-style . org-agenda-export-html-style)
24115 (:convert-org-links . org-export-html-link-org-files-as-html)
24116 (:inline-images . org-export-html-inline-images)
24117 (:html-extension . org-export-html-extension)
24118 (:html-table-tag . org-export-html-table-tag)
24119 (:expand-quoted-html . org-export-html-expand)
24120 (:timestamp . org-export-html-with-timestamp)
24121 (:publishing-directory . org-export-publishing-directory)
24122 (:preamble . org-export-html-preamble)
24123 (:postamble . org-export-html-postamble)
24124 (:auto-preamble . org-export-html-auto-preamble)
24125 (:auto-postamble . org-export-html-auto-postamble)
24126 (:author . user-full-name)
24127 (:email . user-mail-address)))
24129 (defun org-default-export-plist ()
24130 "Return the property list with default settings for the export variables."
24131 (let ((l org-export-plist-vars) rtn e)
24132 (while (setq e (pop l))
24133 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
24134 rtn))
24136 (defun org-infile-export-plist ()
24137 "Return the property list with file-local settings for export."
24138 (save-excursion
24139 (save-restriction
24140 (widen)
24141 (goto-char 0)
24142 (let ((re (org-make-options-regexp
24143 '("TITLE" "AUTHOR" "DATE" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
24144 p key val text options)
24145 (while (re-search-forward re nil t)
24146 (setq key (org-match-string-no-properties 1)
24147 val (org-match-string-no-properties 2))
24148 (cond
24149 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
24150 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
24151 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
24152 ((string-equal key "DATE") (setq p (plist-put p :date val)))
24153 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
24154 ((string-equal key "TEXT")
24155 (setq text (if text (concat text "\n" val) val)))
24156 ((string-equal key "OPTIONS") (setq options val))))
24157 (setq p (plist-put p :text text))
24158 (when options
24159 (let ((op '(("H" . :headline-levels)
24160 ("num" . :section-numbers)
24161 ("toc" . :table-of-contents)
24162 ("\\n" . :preserve-breaks)
24163 ("@" . :expand-quoted-html)
24164 (":" . :fixed-width)
24165 ("|" . :tables)
24166 ("^" . :sub-superscript)
24167 ("-" . :special-strings)
24168 ("f" . :footnotes)
24169 ("d" . :drawers)
24170 ("tags" . :tags)
24171 ("*" . :emphasize)
24172 ("TeX" . :TeX-macros)
24173 ("LaTeX" . :LaTeX-fragments)
24174 ("skip" . :skip-before-1st-heading)
24175 ("author" . :author-info)
24176 ("timestamp" . :time-stamp-file)))
24178 (while (setq o (pop op))
24179 (if (string-match (concat (regexp-quote (car o))
24180 ":\\([^ \t\n\r;,.]*\\)")
24181 options)
24182 (setq p (plist-put p (cdr o)
24183 (car (read-from-string
24184 (match-string 1 options)))))))))
24185 p))))
24187 (defun org-export-directory (type plist)
24188 (let* ((val (plist-get plist :publishing-directory))
24189 (dir (if (listp val)
24190 (or (cdr (assoc type val)) ".")
24191 val)))
24192 dir))
24194 (defun org-skip-comments (lines)
24195 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
24196 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
24197 (re2 "^\\(\\*+\\)[ \t\n\r]")
24198 (case-fold-search nil)
24199 rtn line level)
24200 (while (setq line (pop lines))
24201 (cond
24202 ((and (string-match re1 line)
24203 (setq level (- (match-end 1) (match-beginning 1))))
24204 ;; Beginning of a COMMENT subtree. Skip it.
24205 (while (and (setq line (pop lines))
24206 (or (not (string-match re2 line))
24207 (> (- (match-end 1) (match-beginning 1)) level))))
24208 (setq lines (cons line lines)))
24209 ((string-match "^#" line)
24210 ;; an ordinary comment line
24212 ((and org-export-table-remove-special-lines
24213 (string-match "^[ \t]*|" line)
24214 (or (string-match "^[ \t]*| *[!_^] *|" line)
24215 (and (string-match "| *<[0-9]+> *|" line)
24216 (not (string-match "| *[^ <|]" line)))))
24217 ;; a special table line that should be removed
24219 (t (setq rtn (cons line rtn)))))
24220 (nreverse rtn)))
24222 (defun org-export (&optional arg)
24223 (interactive)
24224 (let ((help "[t] insert the export option template
24225 \[v] limit export to visible part of outline tree
24227 \[a] export as ASCII
24229 \[h] export as HTML
24230 \[H] export as HTML to temporary buffer
24231 \[R] export region as HTML
24232 \[b] export as HTML and browse immediately
24233 \[x] export as XOXO
24235 \[l] export as LaTeX
24236 \[L] export as LaTeX to temporary buffer
24238 \[i] export current file as iCalendar file
24239 \[I] export all agenda files as iCalendar files
24240 \[c] export agenda files into combined iCalendar file
24242 \[F] publish current file
24243 \[P] publish current project
24244 \[X] publish... (project will be prompted for)
24245 \[A] publish all projects")
24246 (cmds
24247 '((?t . org-insert-export-options-template)
24248 (?v . org-export-visible)
24249 (?a . org-export-as-ascii)
24250 (?h . org-export-as-html)
24251 (?b . org-export-as-html-and-open)
24252 (?H . org-export-as-html-to-buffer)
24253 (?R . org-export-region-as-html)
24254 (?x . org-export-as-xoxo)
24255 (?l . org-export-as-latex)
24256 (?L . org-export-as-latex-to-buffer)
24257 (?i . org-export-icalendar-this-file)
24258 (?I . org-export-icalendar-all-agenda-files)
24259 (?c . org-export-icalendar-combine-agenda-files)
24260 (?F . org-publish-current-file)
24261 (?P . org-publish-current-project)
24262 (?X . org-publish)
24263 (?A . org-publish-all)))
24264 r1 r2 ass)
24265 (save-window-excursion
24266 (delete-other-windows)
24267 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
24268 (princ help))
24269 (message "Select command: ")
24270 (setq r1 (read-char-exclusive)))
24271 (setq r2 (if (< r1 27) (+ r1 96) r1))
24272 (if (setq ass (assq r2 cmds))
24273 (call-interactively (cdr ass))
24274 (error "No command associated with key %c" r1))))
24276 (defconst org-html-entities
24277 '(("nbsp")
24278 ("iexcl")
24279 ("cent")
24280 ("pound")
24281 ("curren")
24282 ("yen")
24283 ("brvbar")
24284 ("vert" . "&#124;")
24285 ("sect")
24286 ("uml")
24287 ("copy")
24288 ("ordf")
24289 ("laquo")
24290 ("not")
24291 ("shy")
24292 ("reg")
24293 ("macr")
24294 ("deg")
24295 ("plusmn")
24296 ("sup2")
24297 ("sup3")
24298 ("acute")
24299 ("micro")
24300 ("para")
24301 ("middot")
24302 ("odot"."o")
24303 ("star"."*")
24304 ("cedil")
24305 ("sup1")
24306 ("ordm")
24307 ("raquo")
24308 ("frac14")
24309 ("frac12")
24310 ("frac34")
24311 ("iquest")
24312 ("Agrave")
24313 ("Aacute")
24314 ("Acirc")
24315 ("Atilde")
24316 ("Auml")
24317 ("Aring") ("AA"."&Aring;")
24318 ("AElig")
24319 ("Ccedil")
24320 ("Egrave")
24321 ("Eacute")
24322 ("Ecirc")
24323 ("Euml")
24324 ("Igrave")
24325 ("Iacute")
24326 ("Icirc")
24327 ("Iuml")
24328 ("ETH")
24329 ("Ntilde")
24330 ("Ograve")
24331 ("Oacute")
24332 ("Ocirc")
24333 ("Otilde")
24334 ("Ouml")
24335 ("times")
24336 ("Oslash")
24337 ("Ugrave")
24338 ("Uacute")
24339 ("Ucirc")
24340 ("Uuml")
24341 ("Yacute")
24342 ("THORN")
24343 ("szlig")
24344 ("agrave")
24345 ("aacute")
24346 ("acirc")
24347 ("atilde")
24348 ("auml")
24349 ("aring")
24350 ("aelig")
24351 ("ccedil")
24352 ("egrave")
24353 ("eacute")
24354 ("ecirc")
24355 ("euml")
24356 ("igrave")
24357 ("iacute")
24358 ("icirc")
24359 ("iuml")
24360 ("eth")
24361 ("ntilde")
24362 ("ograve")
24363 ("oacute")
24364 ("ocirc")
24365 ("otilde")
24366 ("ouml")
24367 ("divide")
24368 ("oslash")
24369 ("ugrave")
24370 ("uacute")
24371 ("ucirc")
24372 ("uuml")
24373 ("yacute")
24374 ("thorn")
24375 ("yuml")
24376 ("fnof")
24377 ("Alpha")
24378 ("Beta")
24379 ("Gamma")
24380 ("Delta")
24381 ("Epsilon")
24382 ("Zeta")
24383 ("Eta")
24384 ("Theta")
24385 ("Iota")
24386 ("Kappa")
24387 ("Lambda")
24388 ("Mu")
24389 ("Nu")
24390 ("Xi")
24391 ("Omicron")
24392 ("Pi")
24393 ("Rho")
24394 ("Sigma")
24395 ("Tau")
24396 ("Upsilon")
24397 ("Phi")
24398 ("Chi")
24399 ("Psi")
24400 ("Omega")
24401 ("alpha")
24402 ("beta")
24403 ("gamma")
24404 ("delta")
24405 ("epsilon")
24406 ("varepsilon"."&epsilon;")
24407 ("zeta")
24408 ("eta")
24409 ("theta")
24410 ("iota")
24411 ("kappa")
24412 ("lambda")
24413 ("mu")
24414 ("nu")
24415 ("xi")
24416 ("omicron")
24417 ("pi")
24418 ("rho")
24419 ("sigmaf") ("varsigma"."&sigmaf;")
24420 ("sigma")
24421 ("tau")
24422 ("upsilon")
24423 ("phi")
24424 ("chi")
24425 ("psi")
24426 ("omega")
24427 ("thetasym") ("vartheta"."&thetasym;")
24428 ("upsih")
24429 ("piv")
24430 ("bull") ("bullet"."&bull;")
24431 ("hellip") ("dots"."&hellip;")
24432 ("prime")
24433 ("Prime")
24434 ("oline")
24435 ("frasl")
24436 ("weierp")
24437 ("image")
24438 ("real")
24439 ("trade")
24440 ("alefsym")
24441 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
24442 ("uarr") ("uparrow"."&uarr;")
24443 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
24444 ("darr")("downarrow"."&darr;")
24445 ("harr") ("leftrightarrow"."&harr;")
24446 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
24447 ("lArr") ("Leftarrow"."&lArr;")
24448 ("uArr") ("Uparrow"."&uArr;")
24449 ("rArr") ("Rightarrow"."&rArr;")
24450 ("dArr") ("Downarrow"."&dArr;")
24451 ("hArr") ("Leftrightarrow"."&hArr;")
24452 ("forall")
24453 ("part") ("partial"."&part;")
24454 ("exist") ("exists"."&exist;")
24455 ("empty") ("emptyset"."&empty;")
24456 ("nabla")
24457 ("isin") ("in"."&isin;")
24458 ("notin")
24459 ("ni")
24460 ("prod")
24461 ("sum")
24462 ("minus")
24463 ("lowast") ("ast"."&lowast;")
24464 ("radic")
24465 ("prop") ("proptp"."&prop;")
24466 ("infin") ("infty"."&infin;")
24467 ("ang") ("angle"."&ang;")
24468 ("and") ("wedge"."&and;")
24469 ("or") ("vee"."&or;")
24470 ("cap")
24471 ("cup")
24472 ("int")
24473 ("there4")
24474 ("sim")
24475 ("cong") ("simeq"."&cong;")
24476 ("asymp")("approx"."&asymp;")
24477 ("ne") ("neq"."&ne;")
24478 ("equiv")
24479 ("le")
24480 ("ge")
24481 ("sub") ("subset"."&sub;")
24482 ("sup") ("supset"."&sup;")
24483 ("nsub")
24484 ("sube")
24485 ("supe")
24486 ("oplus")
24487 ("otimes")
24488 ("perp")
24489 ("sdot") ("cdot"."&sdot;")
24490 ("lceil")
24491 ("rceil")
24492 ("lfloor")
24493 ("rfloor")
24494 ("lang")
24495 ("rang")
24496 ("loz") ("Diamond"."&loz;")
24497 ("spades") ("spadesuit"."&spades;")
24498 ("clubs") ("clubsuit"."&clubs;")
24499 ("hearts") ("diamondsuit"."&hearts;")
24500 ("diams") ("diamondsuit"."&diams;")
24501 ("smile"."&#9786;") ("blacksmile"."&#9787;") ("sad"."&#9785;")
24502 ("quot")
24503 ("amp")
24504 ("lt")
24505 ("gt")
24506 ("OElig")
24507 ("oelig")
24508 ("Scaron")
24509 ("scaron")
24510 ("Yuml")
24511 ("circ")
24512 ("tilde")
24513 ("ensp")
24514 ("emsp")
24515 ("thinsp")
24516 ("zwnj")
24517 ("zwj")
24518 ("lrm")
24519 ("rlm")
24520 ("ndash")
24521 ("mdash")
24522 ("lsquo")
24523 ("rsquo")
24524 ("sbquo")
24525 ("ldquo")
24526 ("rdquo")
24527 ("bdquo")
24528 ("dagger")
24529 ("Dagger")
24530 ("permil")
24531 ("lsaquo")
24532 ("rsaquo")
24533 ("euro")
24535 ("arccos"."arccos")
24536 ("arcsin"."arcsin")
24537 ("arctan"."arctan")
24538 ("arg"."arg")
24539 ("cos"."cos")
24540 ("cosh"."cosh")
24541 ("cot"."cot")
24542 ("coth"."coth")
24543 ("csc"."csc")
24544 ("deg"."deg")
24545 ("det"."det")
24546 ("dim"."dim")
24547 ("exp"."exp")
24548 ("gcd"."gcd")
24549 ("hom"."hom")
24550 ("inf"."inf")
24551 ("ker"."ker")
24552 ("lg"."lg")
24553 ("lim"."lim")
24554 ("liminf"."liminf")
24555 ("limsup"."limsup")
24556 ("ln"."ln")
24557 ("log"."log")
24558 ("max"."max")
24559 ("min"."min")
24560 ("Pr"."Pr")
24561 ("sec"."sec")
24562 ("sin"."sin")
24563 ("sinh"."sinh")
24564 ("sup"."sup")
24565 ("tan"."tan")
24566 ("tanh"."tanh")
24568 "Entities for TeX->HTML translation.
24569 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
24570 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
24571 In that case, \"\\ent\" will be translated to \"&other;\".
24572 The list contains HTML entities for Latin-1, Greek and other symbols.
24573 It is supplemented by a number of commonly used TeX macros with appropriate
24574 translations. There is currently no way for users to extend this.")
24576 ;;; General functions for all backends
24578 (defun org-cleaned-string-for-export (string &rest parameters)
24579 "Cleanup a buffer STRING so that links can be created safely."
24580 (interactive)
24581 (let* ((re-radio (and org-target-link-regexp
24582 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
24583 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
24584 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
24585 (re-archive (concat ":" org-archive-tag ":"))
24586 (re-quote (concat "^\\*+[ \t]+" org-quote-string "\\>"))
24587 (re-commented (concat "^\\*+[ \t]+" org-comment-string "\\>"))
24588 (htmlp (plist-get parameters :for-html))
24589 (asciip (plist-get parameters :for-ascii))
24590 (latexp (plist-get parameters :for-LaTeX))
24591 (commentsp (plist-get parameters :comments))
24592 (archived-trees (plist-get parameters :archived-trees))
24593 (inhibit-read-only t)
24594 (drawers org-drawers)
24595 (exp-drawers (plist-get parameters :drawers))
24596 (outline-regexp "\\*+ ")
24597 a b xx
24598 rtn p)
24599 (with-current-buffer (get-buffer-create " org-mode-tmp")
24600 (erase-buffer)
24601 (insert string)
24602 ;; Remove license-to-kill stuff
24603 (while (setq p (text-property-any (point-min) (point-max)
24604 :org-license-to-kill t))
24605 (delete-region p (next-single-property-change p :org-license-to-kill)))
24607 (let ((org-inhibit-startup t)) (org-mode))
24608 (untabify (point-min) (point-max))
24610 ;; Get rid of drawers
24611 (unless (eq t exp-drawers)
24612 (goto-char (point-min))
24613 (let ((re (concat "^[ \t]*:\\("
24614 (mapconcat
24615 'identity
24616 (org-delete-all exp-drawers
24617 (copy-sequence drawers))
24618 "\\|")
24619 "\\):[ \t]*\n\\([^@]*?\n\\)?[ \t]*:END:[ \t]*\n")))
24620 (while (re-search-forward re nil t)
24621 (replace-match ""))))
24623 ;; Get the correct stuff before the first headline
24624 (when (plist-get parameters :skip-before-1st-heading)
24625 (goto-char (point-min))
24626 (when (re-search-forward "^\\*+[ \t]" nil t)
24627 (delete-region (point-min) (match-beginning 0))
24628 (goto-char (point-min))
24629 (insert "\n")))
24630 (when (plist-get parameters :add-text)
24631 (goto-char (point-min))
24632 (insert (plist-get parameters :add-text) "\n"))
24634 ;; Get rid of archived trees
24635 (when (not (eq archived-trees t))
24636 (goto-char (point-min))
24637 (while (re-search-forward re-archive nil t)
24638 (if (not (org-on-heading-p t))
24639 (org-end-of-subtree t)
24640 (beginning-of-line 1)
24641 (setq a (if archived-trees
24642 (1+ (point-at-eol)) (point))
24643 b (org-end-of-subtree t))
24644 (if (> b a) (delete-region a b)))))
24646 ;; Find targets in comments and move them out of comments,
24647 ;; but mark them as targets that should be invisible
24648 (goto-char (point-min))
24649 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
24650 (replace-match "\\1(INVISIBLE)"))
24652 ;; Protect backend specific stuff, throw away the others.
24653 (let ((formatters
24654 `((,htmlp "HTML" "BEGIN_HTML" "END_HTML")
24655 (,asciip "ASCII" "BEGIN_ASCII" "END_ASCII")
24656 (,latexp "LaTeX" "BEGIN_LaTeX" "END_LaTeX")))
24657 fmt)
24658 (goto-char (point-min))
24659 (while (re-search-forward "^#\\+BEGIN_EXAMPLE[ \t]*\n" nil t)
24660 (goto-char (match-end 0))
24661 (while (not (looking-at "#\\+END_EXAMPLE"))
24662 (insert ": ")
24663 (beginning-of-line 2)))
24664 (goto-char (point-min))
24665 (while (re-search-forward "^[ \t]*:.*\\(\n[ \t]*:.*\\)*" nil t)
24666 (add-text-properties (match-beginning 0) (match-end 0)
24667 '(org-protected t)))
24668 (while formatters
24669 (setq fmt (pop formatters))
24670 (when (car fmt)
24671 (goto-char (point-min))
24672 (while (re-search-forward (concat "^#\\+" (cadr fmt)
24673 ":[ \t]*\\(.*\\)") nil t)
24674 (replace-match "\\1" t)
24675 (add-text-properties
24676 (point-at-bol) (min (1+ (point-at-eol)) (point-max))
24677 '(org-protected t))))
24678 (goto-char (point-min))
24679 (while (re-search-forward
24680 (concat "^#\\+"
24681 (caddr fmt) "\\>.*\\(\\(\n.*\\)*?\n\\)#\\+"
24682 (cadddr fmt) "\\>.*\n?") nil t)
24683 (if (car fmt)
24684 (add-text-properties (match-beginning 1) (1+ (match-end 1))
24685 '(org-protected t))
24686 (delete-region (match-beginning 0) (match-end 0))))))
24688 ;; Protect quoted subtrees
24689 (goto-char (point-min))
24690 (while (re-search-forward re-quote nil t)
24691 (goto-char (match-beginning 0))
24692 (end-of-line 1)
24693 (add-text-properties (point) (org-end-of-subtree t)
24694 '(org-protected t)))
24696 ;; Protect verbatim elements
24697 (goto-char (point-min))
24698 (while (re-search-forward org-verbatim-re nil t)
24699 (add-text-properties (match-beginning 4) (match-end 4)
24700 '(org-protected t))
24701 (goto-char (1+ (match-end 4))))
24703 ;; Remove subtrees that are commented
24704 (goto-char (point-min))
24705 (while (re-search-forward re-commented nil t)
24706 (goto-char (match-beginning 0))
24707 (delete-region (point) (org-end-of-subtree t)))
24709 ;; Remove special table lines
24710 (when org-export-table-remove-special-lines
24711 (goto-char (point-min))
24712 (while (re-search-forward "^[ \t]*|" nil t)
24713 (beginning-of-line 1)
24714 (if (or (looking-at "[ \t]*| *[!_^] *|")
24715 (and (looking-at ".*?| *<[0-9]+> *|")
24716 (not (looking-at ".*?| *[^ <|]"))))
24717 (delete-region (max (point-min) (1- (point-at-bol)))
24718 (point-at-eol))
24719 (end-of-line 1))))
24721 ;; Specific LaTeX stuff
24722 (when latexp
24723 (require 'org-export-latex nil)
24724 (org-export-latex-cleaned-string))
24726 (when asciip
24727 (org-export-ascii-clean-string))
24729 ;; Specific HTML stuff
24730 (when htmlp
24731 ;; Convert LaTeX fragments to images
24732 (when (plist-get parameters :LaTeX-fragments)
24733 (org-format-latex
24734 (concat "ltxpng/" (file-name-sans-extension
24735 (file-name-nondirectory
24736 org-current-export-file)))
24737 org-current-export-dir nil "Creating LaTeX image %s"))
24738 (message "Exporting..."))
24740 ;; Remove or replace comments
24741 (goto-char (point-min))
24742 (while (re-search-forward "^#\\(.*\n?\\)" nil t)
24743 (if commentsp
24744 (progn (add-text-properties
24745 (match-beginning 0) (match-end 0) '(org-protected t))
24746 (replace-match (format commentsp (match-string 1)) t t))
24747 (replace-match "")))
24749 ;; Find matches for radio targets and turn them into internal links
24750 (goto-char (point-min))
24751 (when re-radio
24752 (while (re-search-forward re-radio nil t)
24753 (org-if-unprotected
24754 (replace-match "\\1[[\\2]]"))))
24756 ;; Find all links that contain a newline and put them into a single line
24757 (goto-char (point-min))
24758 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
24759 (org-if-unprotected
24760 (replace-match "\\1 \\3")
24761 (goto-char (match-beginning 0))))
24764 ;; Normalize links: Convert angle and plain links into bracket links
24765 ;; Expand link abbreviations
24766 (goto-char (point-min))
24767 (while (re-search-forward re-plain-link nil t)
24768 (goto-char (1- (match-end 0)))
24769 (org-if-unprotected
24770 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24771 ":" (match-string 3) "]]")))
24772 ;; added 'org-link face to links
24773 (put-text-property 0 (length s) 'face 'org-link s)
24774 (replace-match s t t))))
24775 (goto-char (point-min))
24776 (while (re-search-forward re-angle-link nil t)
24777 (goto-char (1- (match-end 0)))
24778 (org-if-unprotected
24779 (let* ((s (concat (match-string 1) "[[" (match-string 2)
24780 ":" (match-string 3) "]]")))
24781 (put-text-property 0 (length s) 'face 'org-link s)
24782 (replace-match s t t))))
24783 (goto-char (point-min))
24784 (while (re-search-forward org-bracket-link-regexp nil t)
24785 (org-if-unprotected
24786 (let* ((s (concat "[[" (setq xx (save-match-data
24787 (org-link-expand-abbrev (match-string 1))))
24789 (if (match-end 3)
24790 (match-string 2)
24791 (concat "[" xx "]"))
24792 "]")))
24793 (put-text-property 0 (length s) 'face 'org-link s)
24794 (replace-match s t t))))
24796 ;; Find multiline emphasis and put them into single line
24797 (when (plist-get parameters :emph-multiline)
24798 (goto-char (point-min))
24799 (while (re-search-forward org-emph-re nil t)
24800 (if (not (= (char-after (match-beginning 3))
24801 (char-after (match-beginning 4))))
24802 (org-if-unprotected
24803 (subst-char-in-region (match-beginning 0) (match-end 0)
24804 ?\n ?\ t)
24805 (goto-char (1- (match-end 0))))
24806 (goto-char (1+ (match-beginning 0))))))
24808 (setq rtn (buffer-string)))
24809 (kill-buffer " org-mode-tmp")
24810 rtn))
24812 (defun org-export-grab-title-from-buffer ()
24813 "Get a title for the current document, from looking at the buffer."
24814 (let ((inhibit-read-only t))
24815 (save-excursion
24816 (goto-char (point-min))
24817 (let ((end (save-excursion (outline-next-heading) (point))))
24818 (when (re-search-forward "^[ \t]*[^|# \t\r\n].*\n" end t)
24819 ;; Mark the line so that it will not be exported as normal text.
24820 (org-unmodified
24821 (add-text-properties (match-beginning 0) (match-end 0)
24822 (list :org-license-to-kill t)))
24823 ;; Return the title string
24824 (org-trim (match-string 0)))))))
24826 (defun org-export-get-title-from-subtree ()
24827 "Return subtree title and exclude it from export."
24828 (let (title (m (mark)))
24829 (save-excursion
24830 (goto-char (region-beginning))
24831 (when (and (org-at-heading-p)
24832 (>= (org-end-of-subtree t t) (region-end)))
24833 ;; This is a subtree, we take the title from the first heading
24834 (goto-char (region-beginning))
24835 (looking-at org-todo-line-regexp)
24836 (setq title (match-string 3))
24837 (org-unmodified
24838 (add-text-properties (point) (1+ (point-at-eol))
24839 (list :org-license-to-kill t)))))
24840 title))
24842 (defun org-solidify-link-text (s &optional alist)
24843 "Take link text and make a safe target out of it."
24844 (save-match-data
24845 (let* ((rtn
24846 (mapconcat
24847 'identity
24848 (org-split-string s "[ \t\r\n]+") "--"))
24849 (a (assoc rtn alist)))
24850 (or (cdr a) rtn))))
24852 (defun org-get-min-level (lines)
24853 "Get the minimum level in LINES."
24854 (let ((re "^\\(\\*+\\) ") l min)
24855 (catch 'exit
24856 (while (setq l (pop lines))
24857 (if (string-match re l)
24858 (throw 'exit (org-tr-level (length (match-string 1 l))))))
24859 1)))
24861 ;; Variable holding the vector with section numbers
24862 (defvar org-section-numbers (make-vector org-level-max 0))
24864 (defun org-init-section-numbers ()
24865 "Initialize the vector for the section numbers."
24866 (let* ((level -1)
24867 (numbers (nreverse (org-split-string "" "\\.")))
24868 (depth (1- (length org-section-numbers)))
24869 (i depth) number-string)
24870 (while (>= i 0)
24871 (if (> i level)
24872 (aset org-section-numbers i 0)
24873 (setq number-string (or (car numbers) "0"))
24874 (if (string-match "\\`[A-Z]\\'" number-string)
24875 (aset org-section-numbers i
24876 (- (string-to-char number-string) ?A -1))
24877 (aset org-section-numbers i (string-to-number number-string)))
24878 (pop numbers))
24879 (setq i (1- i)))))
24881 (defun org-section-number (&optional level)
24882 "Return a string with the current section number.
24883 When LEVEL is non-nil, increase section numbers on that level."
24884 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
24885 (when level
24886 (when (> level -1)
24887 (aset org-section-numbers
24888 level (1+ (aref org-section-numbers level))))
24889 (setq idx (1+ level))
24890 (while (<= idx depth)
24891 (if (not (= idx 1))
24892 (aset org-section-numbers idx 0))
24893 (setq idx (1+ idx))))
24894 (setq idx 0)
24895 (while (<= idx depth)
24896 (setq n (aref org-section-numbers idx))
24897 (setq string (concat string (if (not (string= string "")) "." "")
24898 (int-to-string n)))
24899 (setq idx (1+ idx)))
24900 (save-match-data
24901 (if (string-match "\\`\\([@0]\\.\\)+" string)
24902 (setq string (replace-match "" t nil string)))
24903 (if (string-match "\\(\\.0\\)+\\'" string)
24904 (setq string (replace-match "" t nil string))))
24905 string))
24907 ;;; ASCII export
24909 (defvar org-last-level nil) ; dynamically scoped variable
24910 (defvar org-min-level nil) ; dynamically scoped variable
24911 (defvar org-levels-open nil) ; dynamically scoped parameter
24912 (defvar org-ascii-current-indentation nil) ; For communication
24914 (defun org-export-as-ascii (arg)
24915 "Export the outline as a pretty ASCII file.
24916 If there is an active region, export only the region.
24917 The prefix ARG specifies how many levels of the outline should become
24918 underlined headlines. The default is 3."
24919 (interactive "P")
24920 (setq-default org-todo-line-regexp org-todo-line-regexp)
24921 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
24922 (org-infile-export-plist)))
24923 (region-p (org-region-active-p))
24924 (subtree-p
24925 (when region-p
24926 (save-excursion
24927 (goto-char (region-beginning))
24928 (and (org-at-heading-p)
24929 (>= (org-end-of-subtree t t) (region-end))))))
24930 (custom-times org-display-custom-times)
24931 (org-ascii-current-indentation '(0 . 0))
24932 (level 0) line txt
24933 (umax nil)
24934 (umax-toc nil)
24935 (case-fold-search nil)
24936 (filename (concat (file-name-as-directory
24937 (org-export-directory :ascii opt-plist))
24938 (file-name-sans-extension
24939 (or (and subtree-p
24940 (org-entry-get (region-beginning)
24941 "EXPORT_FILE_NAME" t))
24942 (file-name-nondirectory buffer-file-name)))
24943 ".txt"))
24944 (filename (if (equal (file-truename filename)
24945 (file-truename buffer-file-name))
24946 (concat filename ".txt")
24947 filename))
24948 (buffer (find-file-noselect filename))
24949 (org-levels-open (make-vector org-level-max nil))
24950 (odd org-odd-levels-only)
24951 (date (plist-get opt-plist :date))
24952 (author (plist-get opt-plist :author))
24953 (title (or (and subtree-p (org-export-get-title-from-subtree))
24954 (plist-get opt-plist :title)
24955 (and (not
24956 (plist-get opt-plist :skip-before-1st-heading))
24957 (org-export-grab-title-from-buffer))
24958 (file-name-sans-extension
24959 (file-name-nondirectory buffer-file-name))))
24960 (email (plist-get opt-plist :email))
24961 (language (plist-get opt-plist :language))
24962 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
24963 ; (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
24964 (todo nil)
24965 (lang-words nil)
24966 (region
24967 (buffer-substring
24968 (if (org-region-active-p) (region-beginning) (point-min))
24969 (if (org-region-active-p) (region-end) (point-max))))
24970 (lines (org-split-string
24971 (org-cleaned-string-for-export
24972 region
24973 :for-ascii t
24974 :skip-before-1st-heading
24975 (plist-get opt-plist :skip-before-1st-heading)
24976 :drawers (plist-get opt-plist :drawers)
24977 :verbatim-multiline t
24978 :archived-trees
24979 (plist-get opt-plist :archived-trees)
24980 :add-text (plist-get opt-plist :text))
24981 "\n"))
24982 thetoc have-headings first-heading-pos
24983 table-open table-buffer)
24985 (let ((inhibit-read-only t))
24986 (org-unmodified
24987 (remove-text-properties (point-min) (point-max)
24988 '(:org-license-to-kill t))))
24990 (setq org-min-level (org-get-min-level lines))
24991 (setq org-last-level org-min-level)
24992 (org-init-section-numbers)
24994 (find-file-noselect filename)
24996 (setq lang-words (or (assoc language org-export-language-setup)
24997 (assoc "en" org-export-language-setup)))
24998 (switch-to-buffer-other-window buffer)
24999 (erase-buffer)
25000 (fundamental-mode)
25001 ;; create local variables for all options, to make sure all called
25002 ;; functions get the correct information
25003 (mapc (lambda (x)
25004 (set (make-local-variable (cdr x))
25005 (plist-get opt-plist (car x))))
25006 org-export-plist-vars)
25007 (org-set-local 'org-odd-levels-only odd)
25008 (setq umax (if arg (prefix-numeric-value arg)
25009 org-export-headline-levels))
25010 (setq umax-toc (if (integerp org-export-with-toc)
25011 (min org-export-with-toc umax)
25012 umax))
25014 ;; File header
25015 (if title (org-insert-centered title ?=))
25016 (insert "\n")
25017 (if (and (or author email)
25018 org-export-author-info)
25019 (insert (concat (nth 1 lang-words) ": " (or author "")
25020 (if email (concat " <" email ">") "")
25021 "\n")))
25023 (cond
25024 ((and date (string-match "%" date))
25025 (setq date (format-time-string date (current-time))))
25026 (date)
25027 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25029 (if (and date org-export-time-stamp-file)
25030 (insert (concat (nth 2 lang-words) ": " date"\n")))
25032 (insert "\n\n")
25034 (if org-export-with-toc
25035 (progn
25036 (push (concat (nth 3 lang-words) "\n") thetoc)
25037 (push (concat (make-string (length (nth 3 lang-words)) ?=) "\n") thetoc)
25038 (mapc '(lambda (line)
25039 (if (string-match org-todo-line-regexp
25040 line)
25041 ;; This is a headline
25042 (progn
25043 (setq have-headings t)
25044 (setq level (- (match-end 1) (match-beginning 1))
25045 level (org-tr-level level)
25046 txt (match-string 3 line)
25047 todo
25048 (or (and org-export-mark-todo-in-toc
25049 (match-beginning 2)
25050 (not (member (match-string 2 line)
25051 org-done-keywords)))
25052 ; TODO, not DONE
25053 (and org-export-mark-todo-in-toc
25054 (= level umax-toc)
25055 (org-search-todo-below
25056 line lines level))))
25057 (setq txt (org-html-expand-for-ascii txt))
25059 (while (string-match org-bracket-link-regexp txt)
25060 (setq txt
25061 (replace-match
25062 (match-string (if (match-end 2) 3 1) txt)
25063 t t txt)))
25065 (if (and (memq org-export-with-tags '(not-in-toc nil))
25066 (string-match
25067 (org-re "[ \t]+:[[:alnum:]_@:]+:[ \t]*$")
25068 txt))
25069 (setq txt (replace-match "" t t txt)))
25070 (if (string-match quote-re0 txt)
25071 (setq txt (replace-match "" t t txt)))
25073 (if org-export-with-section-numbers
25074 (setq txt (concat (org-section-number level)
25075 " " txt)))
25076 (if (<= level umax-toc)
25077 (progn
25078 (push
25079 (concat
25080 (make-string
25081 (* (max 0 (- level org-min-level)) 4) ?\ )
25082 (format (if todo "%s (*)\n" "%s\n") txt))
25083 thetoc)
25084 (setq org-last-level level))
25085 ))))
25086 lines)
25087 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25089 (org-init-section-numbers)
25090 (while (setq line (pop lines))
25091 ;; Remove the quoted HTML tags.
25092 (setq line (org-html-expand-for-ascii line))
25093 ;; Remove targets
25094 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
25095 (setq line (replace-match "" t t line)))
25096 ;; Replace internal links
25097 (while (string-match org-bracket-link-regexp line)
25098 (setq line (replace-match
25099 (if (match-end 3) "[\\3]" "[\\1]")
25100 t nil line)))
25101 (when custom-times
25102 (setq line (org-translate-time line)))
25103 (cond
25104 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25105 ;; a Headline
25106 (setq first-heading-pos (or first-heading-pos (point)))
25107 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25108 txt (match-string 2 line))
25109 (org-ascii-level-start level txt umax lines))
25111 ((and org-export-with-tables
25112 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
25113 (if (not table-open)
25114 ;; New table starts
25115 (setq table-open t table-buffer nil))
25116 ;; Accumulate lines
25117 (setq table-buffer (cons line table-buffer))
25118 (when (or (not lines)
25119 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
25120 (car lines))))
25121 (setq table-open nil
25122 table-buffer (nreverse table-buffer))
25123 (insert (mapconcat
25124 (lambda (x)
25125 (org-fix-indentation x org-ascii-current-indentation))
25126 (org-format-table-ascii table-buffer)
25127 "\n") "\n")))
25129 (setq line (org-fix-indentation line org-ascii-current-indentation))
25130 (if (and org-export-with-fixed-width
25131 (string-match "^\\([ \t]*\\)\\(:\\)" line))
25132 (setq line (replace-match "\\1" nil nil line)))
25133 (insert line "\n"))))
25135 (normal-mode)
25137 ;; insert the table of contents
25138 (when thetoc
25139 (goto-char (point-min))
25140 (if (re-search-forward "^[ \t]*\\[TABLE-OF-CONTENTS\\][ \t]*$" nil t)
25141 (progn
25142 (goto-char (match-beginning 0))
25143 (replace-match ""))
25144 (goto-char first-heading-pos))
25145 (mapc 'insert thetoc)
25146 (or (looking-at "[ \t]*\n[ \t]*\n")
25147 (insert "\n\n")))
25149 ;; Convert whitespace place holders
25150 (goto-char (point-min))
25151 (let (beg end)
25152 (while (setq beg (next-single-property-change (point) 'org-whitespace))
25153 (setq end (next-single-property-change beg 'org-whitespace))
25154 (goto-char beg)
25155 (delete-region beg end)
25156 (insert (make-string (- end beg) ?\ ))))
25158 (save-buffer)
25159 ;; remove display and invisible chars
25160 (let (beg end)
25161 (goto-char (point-min))
25162 (while (setq beg (next-single-property-change (point) 'display))
25163 (setq end (next-single-property-change beg 'display))
25164 (delete-region beg end)
25165 (goto-char beg)
25166 (insert "=>"))
25167 (goto-char (point-min))
25168 (while (setq beg (next-single-property-change (point) 'org-cwidth))
25169 (setq end (next-single-property-change beg 'org-cwidth))
25170 (delete-region beg end)
25171 (goto-char beg)))
25172 (goto-char (point-min))))
25174 (defun org-export-ascii-clean-string ()
25175 "Do extra work for ASCII export"
25176 (goto-char (point-min))
25177 (while (re-search-forward org-verbatim-re nil t)
25178 (goto-char (match-end 2))
25179 (backward-delete-char 1) (insert "'")
25180 (goto-char (match-beginning 2))
25181 (delete-char 1) (insert "`")
25182 (goto-char (match-end 2))))
25184 (defun org-search-todo-below (line lines level)
25185 "Search the subtree below LINE for any TODO entries."
25186 (let ((rest (cdr (memq line lines)))
25187 (re org-todo-line-regexp)
25188 line lv todo)
25189 (catch 'exit
25190 (while (setq line (pop rest))
25191 (if (string-match re line)
25192 (progn
25193 (setq lv (- (match-end 1) (match-beginning 1))
25194 todo (and (match-beginning 2)
25195 (not (member (match-string 2 line)
25196 org-done-keywords))))
25197 ; TODO, not DONE
25198 (if (<= lv level) (throw 'exit nil))
25199 (if todo (throw 'exit t))))))))
25201 (defun org-html-expand-for-ascii (line)
25202 "Handle quoted HTML for ASCII export."
25203 (if org-export-html-expand
25204 (while (string-match "@<[^<>\n]*>" line)
25205 ;; We just remove the tags for now.
25206 (setq line (replace-match "" nil nil line))))
25207 line)
25209 (defun org-insert-centered (s &optional underline)
25210 "Insert the string S centered and underline it with character UNDERLINE."
25211 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
25212 (insert (make-string ind ?\ ) s "\n")
25213 (if underline
25214 (insert (make-string ind ?\ )
25215 (make-string (string-width s) underline)
25216 "\n"))))
25218 (defun org-ascii-level-start (level title umax &optional lines)
25219 "Insert a new level in ASCII export."
25220 (let (char (n (- level umax 1)) (ind 0))
25221 (if (> level umax)
25222 (progn
25223 (insert (make-string (* 2 n) ?\ )
25224 (char-to-string (nth (% n (length org-export-ascii-bullets))
25225 org-export-ascii-bullets))
25226 " " title "\n")
25227 ;; find the indentation of the next non-empty line
25228 (catch 'stop
25229 (while lines
25230 (if (string-match "^\\* " (car lines)) (throw 'stop nil))
25231 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
25232 (throw 'stop (setq ind (org-get-indentation (car lines)))))
25233 (pop lines)))
25234 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
25235 (if (or (not (equal (char-before) ?\n))
25236 (not (equal (char-before (1- (point))) ?\n)))
25237 (insert "\n"))
25238 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
25239 (unless org-export-with-tags
25240 (if (string-match (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
25241 (setq title (replace-match "" t t title))))
25242 (if org-export-with-section-numbers
25243 (setq title (concat (org-section-number level) " " title)))
25244 (insert title "\n" (make-string (string-width title) char) "\n")
25245 (setq org-ascii-current-indentation '(0 . 0)))))
25247 (defun org-export-visible (type arg)
25248 "Create a copy of the visible part of the current buffer, and export it.
25249 The copy is created in a temporary buffer and removed after use.
25250 TYPE is the final key (as a string) that also select the export command in
25251 the `C-c C-e' export dispatcher.
25252 As a special case, if the you type SPC at the prompt, the temporary
25253 org-mode file will not be removed but presented to you so that you can
25254 continue to use it. The prefix arg ARG is passed through to the exporting
25255 command."
25256 (interactive
25257 (list (progn
25258 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [H/R]uffer with HTML [x]OXO [ ]keep buffer")
25259 (read-char-exclusive))
25260 current-prefix-arg))
25261 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
25262 (error "Invalid export key"))
25263 (let* ((binding (cdr (assoc type
25264 '((?a . org-export-as-ascii)
25265 (?\C-a . org-export-as-ascii)
25266 (?b . org-export-as-html-and-open)
25267 (?\C-b . org-export-as-html-and-open)
25268 (?h . org-export-as-html)
25269 (?H . org-export-as-html-to-buffer)
25270 (?R . org-export-region-as-html)
25271 (?x . org-export-as-xoxo)))))
25272 (keepp (equal type ?\ ))
25273 (file buffer-file-name)
25274 (buffer (get-buffer-create "*Org Export Visible*"))
25275 s e)
25276 ;; Need to hack the drawers here.
25277 (save-excursion
25278 (goto-char (point-min))
25279 (while (re-search-forward org-drawer-regexp nil t)
25280 (goto-char (match-beginning 1))
25281 (or (org-invisible-p) (org-flag-drawer nil))))
25282 (with-current-buffer buffer (erase-buffer))
25283 (save-excursion
25284 (setq s (goto-char (point-min)))
25285 (while (not (= (point) (point-max)))
25286 (goto-char (org-find-invisible))
25287 (append-to-buffer buffer s (point))
25288 (setq s (goto-char (org-find-visible))))
25289 (org-cycle-hide-drawers 'all)
25290 (goto-char (point-min))
25291 (unless keepp
25292 ;; Copy all comment lines to the end, to make sure #+ settings are
25293 ;; still available for the second export step. Kind of a hack, but
25294 ;; does do the trick.
25295 (if (looking-at "#[^\r\n]*")
25296 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
25297 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
25298 (append-to-buffer buffer (1+ (match-beginning 0))
25299 (min (point-max) (1+ (match-end 0))))))
25300 (set-buffer buffer)
25301 (let ((buffer-file-name file)
25302 (org-inhibit-startup t))
25303 (org-mode)
25304 (show-all)
25305 (unless keepp (funcall binding arg))))
25306 (if (not keepp)
25307 (kill-buffer buffer)
25308 (switch-to-buffer-other-window buffer)
25309 (goto-char (point-min)))))
25311 (defun org-find-visible ()
25312 (let ((s (point)))
25313 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25314 (get-char-property s 'invisible)))
25316 (defun org-find-invisible ()
25317 (let ((s (point)))
25318 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
25319 (not (get-char-property s 'invisible))))
25322 ;;; HTML export
25324 (defun org-get-current-options ()
25325 "Return a string with current options as keyword options.
25326 Does include HTML export options as well as TODO and CATEGORY stuff."
25327 (format
25328 "#+TITLE: %s
25329 #+AUTHOR: %s
25330 #+EMAIL: %s
25331 #+LANGUAGE: %s
25332 #+TEXT: Some descriptive text to be emitted. Several lines OK.
25333 #+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
25334 #+CATEGORY: %s
25335 #+SEQ_TODO: %s
25336 #+TYP_TODO: %s
25337 #+PRIORITIES: %c %c %c
25338 #+DRAWERS: %s
25339 #+STARTUP: %s %s %s %s %s
25340 #+TAGS: %s
25341 #+ARCHIVE: %s
25342 #+LINK: %s
25344 (buffer-name) (user-full-name) user-mail-address org-export-default-language
25345 org-export-headline-levels
25346 org-export-with-section-numbers
25347 org-export-with-toc
25348 org-export-preserve-breaks
25349 org-export-html-expand
25350 org-export-with-fixed-width
25351 org-export-with-tables
25352 org-export-with-sub-superscripts
25353 org-export-with-special-strings
25354 org-export-with-footnotes
25355 org-export-with-emphasize
25356 org-export-with-TeX-macros
25357 org-export-with-LaTeX-fragments
25358 org-export-skip-text-before-1st-heading
25359 org-export-with-drawers
25360 org-export-with-tags
25361 (file-name-nondirectory buffer-file-name)
25362 "TODO FEEDBACK VERIFY DONE"
25363 "Me Jason Marie DONE"
25364 org-highest-priority org-lowest-priority org-default-priority
25365 (mapconcat 'identity org-drawers " ")
25366 (cdr (assoc org-startup-folded
25367 '((nil . "showall") (t . "overview") (content . "content"))))
25368 (if org-odd-levels-only "odd" "oddeven")
25369 (if org-hide-leading-stars "hidestars" "showstars")
25370 (if org-startup-align-all-tables "align" "noalign")
25371 (cond ((eq org-log-done t) "logdone")
25372 ((equal org-log-done 'note) "lognotedone")
25373 ((not org-log-done) "nologdone"))
25374 (or (mapconcat (lambda (x)
25375 (cond
25376 ((equal '(:startgroup) x) "{")
25377 ((equal '(:endgroup) x) "}")
25378 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
25379 (t (car x))))
25380 (or org-tag-alist (org-get-buffer-tags)) " ") "")
25381 org-archive-location
25382 "org file:~/org/%s.org"
25385 (defun org-insert-export-options-template ()
25386 "Insert into the buffer a template with information for exporting."
25387 (interactive)
25388 (if (not (bolp)) (newline))
25389 (let ((s (org-get-current-options)))
25390 (and (string-match "#\\+CATEGORY" s)
25391 (setq s (substring s 0 (match-beginning 0))))
25392 (insert s)))
25394 (defun org-toggle-fixed-width-section (arg)
25395 "Toggle the fixed-width export.
25396 If there is no active region, the QUOTE keyword at the current headline is
25397 inserted or removed. When present, it causes the text between this headline
25398 and the next to be exported as fixed-width text, and unmodified.
25399 If there is an active region, this command adds or removes a colon as the
25400 first character of this line. If the first character of a line is a colon,
25401 this line is also exported in fixed-width font."
25402 (interactive "P")
25403 (let* ((cc 0)
25404 (regionp (org-region-active-p))
25405 (beg (if regionp (region-beginning) (point)))
25406 (end (if regionp (region-end)))
25407 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
25408 (case-fold-search nil)
25409 (re "[ \t]*\\(:\\)")
25410 off)
25411 (if regionp
25412 (save-excursion
25413 (goto-char beg)
25414 (setq cc (current-column))
25415 (beginning-of-line 1)
25416 (setq off (looking-at re))
25417 (while (> nlines 0)
25418 (setq nlines (1- nlines))
25419 (beginning-of-line 1)
25420 (cond
25421 (arg
25422 (move-to-column cc t)
25423 (insert ":\n")
25424 (forward-line -1))
25425 ((and off (looking-at re))
25426 (replace-match "" t t nil 1))
25427 ((not off) (move-to-column cc t) (insert ":")))
25428 (forward-line 1)))
25429 (save-excursion
25430 (org-back-to-heading)
25431 (if (looking-at (concat outline-regexp
25432 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
25433 (replace-match "" t t nil 1)
25434 (if (looking-at outline-regexp)
25435 (progn
25436 (goto-char (match-end 0))
25437 (insert org-quote-string " "))))))))
25439 (defun org-export-as-html-and-open (arg)
25440 "Export the outline as HTML and immediately open it with a browser.
25441 If there is an active region, export only the region.
25442 The prefix ARG specifies how many levels of the outline should become
25443 headlines. The default is 3. Lower levels will become bulleted lists."
25444 (interactive "P")
25445 (org-export-as-html arg 'hidden)
25446 (org-open-file buffer-file-name))
25448 (defun org-export-as-html-batch ()
25449 "Call `org-export-as-html', may be used in batch processing as
25450 emacs --batch
25451 --load=$HOME/lib/emacs/org.el
25452 --eval \"(setq org-export-headline-levels 2)\"
25453 --visit=MyFile --funcall org-export-as-html-batch"
25454 (org-export-as-html org-export-headline-levels 'hidden))
25456 (defun org-export-as-html-to-buffer (arg)
25457 "Call `org-exort-as-html` with output to a temporary buffer.
25458 No file is created. The prefix ARG is passed through to `org-export-as-html'."
25459 (interactive "P")
25460 (org-export-as-html arg nil nil "*Org HTML Export*")
25461 (switch-to-buffer-other-window "*Org HTML Export*"))
25463 (defun org-replace-region-by-html (beg end)
25464 "Assume the current region has org-mode syntax, and convert it to HTML.
25465 This can be used in any buffer. For example, you could write an
25466 itemized list in org-mode syntax in an HTML buffer and then use this
25467 command to convert it."
25468 (interactive "r")
25469 (let (reg html buf pop-up-frames)
25470 (save-window-excursion
25471 (if (org-mode-p)
25472 (setq html (org-export-region-as-html
25473 beg end t 'string))
25474 (setq reg (buffer-substring beg end)
25475 buf (get-buffer-create "*Org tmp*"))
25476 (with-current-buffer buf
25477 (erase-buffer)
25478 (insert reg)
25479 (org-mode)
25480 (setq html (org-export-region-as-html
25481 (point-min) (point-max) t 'string)))
25482 (kill-buffer buf)))
25483 (delete-region beg end)
25484 (insert html)))
25486 (defun org-export-region-as-html (beg end &optional body-only buffer)
25487 "Convert region from BEG to END in org-mode buffer to HTML.
25488 If prefix arg BODY-ONLY is set, omit file header, footer, and table of
25489 contents, and only produce the region of converted text, useful for
25490 cut-and-paste operations.
25491 If BUFFER is a buffer or a string, use/create that buffer as a target
25492 of the converted HTML. If BUFFER is the symbol `string', return the
25493 produced HTML as a string and leave not buffer behind. For example,
25494 a Lisp program could call this function in the following way:
25496 (setq html (org-export-region-as-html beg end t 'string))
25498 When called interactively, the output buffer is selected, and shown
25499 in a window. A non-interactive call will only retunr the buffer."
25500 (interactive "r\nP")
25501 (when (interactive-p)
25502 (setq buffer "*Org HTML Export*"))
25503 (let ((transient-mark-mode t) (zmacs-regions t)
25504 rtn)
25505 (goto-char end)
25506 (set-mark (point)) ;; to activate the region
25507 (goto-char beg)
25508 (setq rtn (org-export-as-html
25509 nil nil nil
25510 buffer body-only))
25511 (if (fboundp 'deactivate-mark) (deactivate-mark))
25512 (if (and (interactive-p) (bufferp rtn))
25513 (switch-to-buffer-other-window rtn)
25514 rtn)))
25516 (defvar html-table-tag nil) ; dynamically scoped into this.
25517 (defun org-export-as-html (arg &optional hidden ext-plist
25518 to-buffer body-only pub-dir)
25519 "Export the outline as a pretty HTML file.
25520 If there is an active region, export only the region. The prefix
25521 ARG specifies how many levels of the outline should become
25522 headlines. The default is 3. Lower levels will become bulleted
25523 lists. When HIDDEN is non-nil, don't display the HTML buffer.
25524 EXT-PLIST is a property list with external parameters overriding
25525 org-mode's default settings, but still inferior to file-local
25526 settings. When TO-BUFFER is non-nil, create a buffer with that
25527 name and export to that buffer. If TO-BUFFER is the symbol
25528 `string', don't leave any buffer behind but just return the
25529 resulting HTML as a string. When BODY-ONLY is set, don't produce
25530 the file header and footer, simply return the content of
25531 <body>...</body>, without even the body tags themselves. When
25532 PUB-DIR is set, use this as the publishing directory."
25533 (interactive "P")
25535 ;; Make sure we have a file name when we need it.
25536 (when (and (not (or to-buffer body-only))
25537 (not buffer-file-name))
25538 (if (buffer-base-buffer)
25539 (org-set-local 'buffer-file-name
25540 (with-current-buffer (buffer-base-buffer)
25541 buffer-file-name))
25542 (error "Need a file name to be able to export.")))
25544 (message "Exporting...")
25545 (setq-default org-todo-line-regexp org-todo-line-regexp)
25546 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
25547 (setq-default org-done-keywords org-done-keywords)
25548 (setq-default org-maybe-keyword-time-regexp org-maybe-keyword-time-regexp)
25549 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
25550 ext-plist
25551 (org-infile-export-plist)))
25553 (style (plist-get opt-plist :style))
25554 (html-extension (plist-get opt-plist :html-extension))
25555 (link-validate (plist-get opt-plist :link-validation-function))
25556 valid thetoc have-headings first-heading-pos
25557 (odd org-odd-levels-only)
25558 (region-p (org-region-active-p))
25559 (subtree-p
25560 (when region-p
25561 (save-excursion
25562 (goto-char (region-beginning))
25563 (and (org-at-heading-p)
25564 (>= (org-end-of-subtree t t) (region-end))))))
25565 ;; The following two are dynamically scoped into other
25566 ;; routines below.
25567 (org-current-export-dir
25568 (or pub-dir (org-export-directory :html opt-plist)))
25569 (org-current-export-file buffer-file-name)
25570 (level 0) (line "") (origline "") txt todo
25571 (umax nil)
25572 (umax-toc nil)
25573 (filename (if to-buffer nil
25574 (expand-file-name
25575 (concat
25576 (file-name-sans-extension
25577 (or (and subtree-p
25578 (org-entry-get (region-beginning)
25579 "EXPORT_FILE_NAME" t))
25580 (file-name-nondirectory buffer-file-name)))
25581 "." html-extension)
25582 (file-name-as-directory
25583 (or pub-dir (org-export-directory :html opt-plist))))))
25584 (current-dir (if buffer-file-name
25585 (file-name-directory buffer-file-name)
25586 default-directory))
25587 (buffer (if to-buffer
25588 (cond
25589 ((eq to-buffer 'string) (get-buffer-create "*Org HTML Export*"))
25590 (t (get-buffer-create to-buffer)))
25591 (find-file-noselect filename)))
25592 (org-levels-open (make-vector org-level-max nil))
25593 (date (plist-get opt-plist :date))
25594 (author (plist-get opt-plist :author))
25595 (title (or (and subtree-p (org-export-get-title-from-subtree))
25596 (plist-get opt-plist :title)
25597 (and (not
25598 (plist-get opt-plist :skip-before-1st-heading))
25599 (org-export-grab-title-from-buffer))
25600 (and buffer-file-name
25601 (file-name-sans-extension
25602 (file-name-nondirectory buffer-file-name)))
25603 "UNTITLED"))
25604 (html-table-tag (plist-get opt-plist :html-table-tag))
25605 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
25606 (quote-re (concat "^\\(\\*+\\)\\([ \t]+" org-quote-string "\\>\\)"))
25607 (inquote nil)
25608 (infixed nil)
25609 (in-local-list nil)
25610 (local-list-num nil)
25611 (local-list-indent nil)
25612 (llt org-plain-list-ordered-item-terminator)
25613 (email (plist-get opt-plist :email))
25614 (language (plist-get opt-plist :language))
25615 (lang-words nil)
25616 (target-alist nil) tg
25617 (head-count 0) cnt
25618 (start 0)
25619 (coding-system (and (boundp 'buffer-file-coding-system)
25620 buffer-file-coding-system))
25621 (coding-system-for-write (or org-export-html-coding-system
25622 coding-system))
25623 (save-buffer-coding-system (or org-export-html-coding-system
25624 coding-system))
25625 (charset (and coding-system-for-write
25626 (fboundp 'coding-system-get)
25627 (coding-system-get coding-system-for-write
25628 'mime-charset)))
25629 (region
25630 (buffer-substring
25631 (if region-p (region-beginning) (point-min))
25632 (if region-p (region-end) (point-max))))
25633 (lines
25634 (org-split-string
25635 (org-cleaned-string-for-export
25636 region
25637 :emph-multiline t
25638 :for-html t
25639 :skip-before-1st-heading
25640 (plist-get opt-plist :skip-before-1st-heading)
25641 :drawers (plist-get opt-plist :drawers)
25642 :archived-trees
25643 (plist-get opt-plist :archived-trees)
25644 :add-text
25645 (plist-get opt-plist :text)
25646 :LaTeX-fragments
25647 (plist-get opt-plist :LaTeX-fragments))
25648 "[\r\n]"))
25649 table-open type
25650 table-buffer table-orig-buffer
25651 ind start-is-num starter didclose
25652 rpl path desc descp desc1 desc2 link
25655 (let ((inhibit-read-only t))
25656 (org-unmodified
25657 (remove-text-properties (point-min) (point-max)
25658 '(:org-license-to-kill t))))
25660 (message "Exporting...")
25662 (setq org-min-level (org-get-min-level lines))
25663 (setq org-last-level org-min-level)
25664 (org-init-section-numbers)
25666 (cond
25667 ((and date (string-match "%" date))
25668 (setq date (format-time-string date (current-time))))
25669 (date)
25670 (t (setq date (format-time-string "%Y/%m/%d %X" (current-time)))))
25672 ;; Get the language-dependent settings
25673 (setq lang-words (or (assoc language org-export-language-setup)
25674 (assoc "en" org-export-language-setup)))
25676 ;; Switch to the output buffer
25677 (set-buffer buffer)
25678 (let ((inhibit-read-only t)) (erase-buffer))
25679 (fundamental-mode)
25681 (and (fboundp 'set-buffer-file-coding-system)
25682 (set-buffer-file-coding-system coding-system-for-write))
25684 (let ((case-fold-search nil)
25685 (org-odd-levels-only odd))
25686 ;; create local variables for all options, to make sure all called
25687 ;; functions get the correct information
25688 (mapc (lambda (x)
25689 (set (make-local-variable (cdr x))
25690 (plist-get opt-plist (car x))))
25691 org-export-plist-vars)
25692 (setq umax (if arg (prefix-numeric-value arg)
25693 org-export-headline-levels))
25694 (setq umax-toc (if (integerp org-export-with-toc)
25695 (min org-export-with-toc umax)
25696 umax))
25697 (unless body-only
25698 ;; File header
25699 (insert (format
25700 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
25701 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
25702 <html xmlns=\"http://www.w3.org/1999/xhtml\"
25703 lang=\"%s\" xml:lang=\"%s\">
25704 <head>
25705 <title>%s</title>
25706 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
25707 <meta name=\"generator\" content=\"Org-mode\"/>
25708 <meta name=\"generated\" content=\"%s\"/>
25709 <meta name=\"author\" content=\"%s\"/>
25711 </head><body>
25713 language language (org-html-expand title)
25714 (or charset "iso-8859-1") date author style))
25716 (insert (or (plist-get opt-plist :preamble) ""))
25718 (when (plist-get opt-plist :auto-preamble)
25719 (if title (insert (format org-export-html-title-format
25720 (org-html-expand title))))))
25722 (if (and org-export-with-toc (not body-only))
25723 (progn
25724 (push (format "<h%d>%s</h%d>\n"
25725 org-export-html-toplevel-hlevel
25726 (nth 3 lang-words)
25727 org-export-html-toplevel-hlevel)
25728 thetoc)
25729 (push "<ul>\n<li>" thetoc)
25730 (setq lines
25731 (mapcar '(lambda (line)
25732 (if (string-match org-todo-line-regexp line)
25733 ;; This is a headline
25734 (progn
25735 (setq have-headings t)
25736 (setq level (- (match-end 1) (match-beginning 1))
25737 level (org-tr-level level)
25738 txt (save-match-data
25739 (org-html-expand
25740 (org-export-cleanup-toc-line
25741 (match-string 3 line))))
25742 todo
25743 (or (and org-export-mark-todo-in-toc
25744 (match-beginning 2)
25745 (not (member (match-string 2 line)
25746 org-done-keywords)))
25747 ; TODO, not DONE
25748 (and org-export-mark-todo-in-toc
25749 (= level umax-toc)
25750 (org-search-todo-below
25751 line lines level))))
25752 (if (string-match
25753 (org-re "[ \t]+:\\([[:alnum:]_@:]+\\):[ \t]*$") txt)
25754 (setq txt (replace-match "&nbsp;&nbsp;&nbsp;<span class=\"tag\"> \\1</span>" t nil txt)))
25755 (if (string-match quote-re0 txt)
25756 (setq txt (replace-match "" t t txt)))
25757 (if org-export-with-section-numbers
25758 (setq txt (concat (org-section-number level)
25759 " " txt)))
25760 (if (<= level (max umax umax-toc))
25761 (setq head-count (+ head-count 1)))
25762 (if (<= level umax-toc)
25763 (progn
25764 (if (> level org-last-level)
25765 (progn
25766 (setq cnt (- level org-last-level))
25767 (while (>= (setq cnt (1- cnt)) 0)
25768 (push "\n<ul>\n<li>" thetoc))
25769 (push "\n" thetoc)))
25770 (if (< level org-last-level)
25771 (progn
25772 (setq cnt (- org-last-level level))
25773 (while (>= (setq cnt (1- cnt)) 0)
25774 (push "</li>\n</ul>" thetoc))
25775 (push "\n" thetoc)))
25776 ;; Check for targets
25777 (while (string-match org-target-regexp line)
25778 (setq tg (match-string 1 line)
25779 line (replace-match
25780 (concat "@<span class=\"target\">" tg "@</span> ")
25781 t t line))
25782 (push (cons (org-solidify-link-text tg)
25783 (format "sec-%d" head-count))
25784 target-alist))
25785 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
25786 (setq txt (replace-match "" t t txt)))
25787 (push
25788 (format
25789 (if todo
25790 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
25791 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
25792 head-count txt) thetoc)
25794 (setq org-last-level level))
25796 line)
25797 lines))
25798 (while (> org-last-level (1- org-min-level))
25799 (setq org-last-level (1- org-last-level))
25800 (push "</li>\n</ul>\n" thetoc))
25801 (setq thetoc (if have-headings (nreverse thetoc) nil))))
25803 (setq head-count 0)
25804 (org-init-section-numbers)
25806 (while (setq line (pop lines) origline line)
25807 (catch 'nextline
25809 ;; end of quote section?
25810 (when (and inquote (string-match "^\\*+ " line))
25811 (insert "</pre>\n")
25812 (setq inquote nil))
25813 ;; inside a quote section?
25814 (when inquote
25815 (insert (org-html-protect line) "\n")
25816 (throw 'nextline nil))
25818 ;; verbatim lines
25819 (when (and org-export-with-fixed-width
25820 (string-match "^[ \t]*:\\(.*\\)" line))
25821 (when (not infixed)
25822 (setq infixed t)
25823 (insert "<pre>\n"))
25824 (insert (org-html-protect (match-string 1 line)) "\n")
25825 (when (and lines
25826 (not (string-match "^[ \t]*\\(:.*\\)"
25827 (car lines))))
25828 (setq infixed nil)
25829 (insert "</pre>\n"))
25830 (throw 'nextline nil))
25832 ;; Protected HTML
25833 (when (get-text-property 0 'org-protected line)
25834 (let (par)
25835 (when (re-search-backward
25836 "\\(<p>\\)\\([ \t\r\n]*\\)\\=" (- (point) 100) t)
25837 (setq par (match-string 1))
25838 (replace-match "\\2\n"))
25839 (insert line "\n")
25840 (while (and lines
25841 (or (= (length (car lines)) 0)
25842 (get-text-property 0 'org-protected (car lines))))
25843 (insert (pop lines) "\n"))
25844 (and par (insert "<p>\n")))
25845 (throw 'nextline nil))
25847 ;; Horizontal line
25848 (when (string-match "^[ \t]*-\\{5,\\}[ \t]*$" line)
25849 (insert "\n<hr/>\n")
25850 (throw 'nextline nil))
25852 ;; make targets to anchors
25853 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
25854 (cond
25855 ((match-end 2)
25856 (setq line (replace-match
25857 (concat "@<a name=\""
25858 (org-solidify-link-text (match-string 1 line))
25859 "\">\\nbsp@</a>")
25860 t t line)))
25861 ((and org-export-with-toc (equal (string-to-char line) ?*))
25862 (setq line (replace-match
25863 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
25864 ; (concat "@<i>" (match-string 1 line) "@</i> ")
25865 t t line)))
25867 (setq line (replace-match
25868 (concat "@<a name=\""
25869 (org-solidify-link-text (match-string 1 line))
25870 "\" class=\"target\">" (match-string 1 line) "@</a> ")
25871 t t line)))))
25873 (setq line (org-html-handle-time-stamps line))
25875 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
25876 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
25877 ;; Also handle sub_superscripts and checkboxes
25878 (or (string-match org-table-hline-regexp line)
25879 (setq line (org-html-expand line)))
25881 ;; Format the links
25882 (setq start 0)
25883 (while (string-match org-bracket-link-analytic-regexp line start)
25884 (setq start (match-beginning 0))
25885 (setq type (if (match-end 2) (match-string 2 line) "internal"))
25886 (setq path (match-string 3 line))
25887 (setq desc1 (if (match-end 5) (match-string 5 line))
25888 desc2 (if (match-end 2) (concat type ":" path) path)
25889 descp (and desc1 (not (equal desc1 desc2)))
25890 desc (or desc1 desc2))
25891 ;; Make an image out of the description if that is so wanted
25892 (when (and descp (org-file-image-p desc))
25893 (save-match-data
25894 (if (string-match "^file:" desc)
25895 (setq desc (substring desc (match-end 0)))))
25896 (setq desc (concat "<img src=\"" desc "\"/>")))
25897 ;; FIXME: do we need to unescape here somewhere?
25898 (cond
25899 ((equal type "internal")
25900 (setq rpl
25901 (concat
25902 "<a href=\"#"
25903 (org-solidify-link-text
25904 (save-match-data (org-link-unescape path)) target-alist)
25905 "\">" desc "</a>")))
25906 ((member type '("http" "https"))
25907 ;; standard URL, just check if we need to inline an image
25908 (if (and (or (eq t org-export-html-inline-images)
25909 (and org-export-html-inline-images (not descp)))
25910 (org-file-image-p path))
25911 (setq rpl (concat "<img src=\"" type ":" path "\"/>"))
25912 (setq link (concat type ":" path))
25913 (setq rpl (concat "<a href=\"" link "\">" desc "</a>"))))
25914 ((member type '("ftp" "mailto" "news"))
25915 ;; standard URL
25916 (setq link (concat type ":" path))
25917 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
25918 ((string= type "file")
25919 ;; FILE link
25920 (let* ((filename path)
25921 (abs-p (file-name-absolute-p filename))
25922 thefile file-is-image-p search)
25923 (save-match-data
25924 (if (string-match "::\\(.*\\)" filename)
25925 (setq search (match-string 1 filename)
25926 filename (replace-match "" t nil filename)))
25927 (setq valid
25928 (if (functionp link-validate)
25929 (funcall link-validate filename current-dir)
25931 (setq file-is-image-p (org-file-image-p filename))
25932 (setq thefile (if abs-p (expand-file-name filename) filename))
25933 (when (and org-export-html-link-org-files-as-html
25934 (string-match "\\.org$" thefile))
25935 (setq thefile (concat (substring thefile 0
25936 (match-beginning 0))
25937 "." html-extension))
25938 (if (and search
25939 ;; make sure this is can be used as target search
25940 (not (string-match "^[0-9]*$" search))
25941 (not (string-match "^\\*" search))
25942 (not (string-match "^/.*/$" search)))
25943 (setq thefile (concat thefile "#"
25944 (org-solidify-link-text
25945 (org-link-unescape search)))))
25946 (when (string-match "^file:" desc)
25947 (setq desc (replace-match "" t t desc))
25948 (if (string-match "\\.org$" desc)
25949 (setq desc (replace-match "" t t desc))))))
25950 (setq rpl (if (and file-is-image-p
25951 (or (eq t org-export-html-inline-images)
25952 (and org-export-html-inline-images
25953 (not descp))))
25954 (concat "<img src=\"" thefile "\"/>")
25955 (concat "<a href=\"" thefile "\">" desc "</a>")))
25956 (if (not valid) (setq rpl desc))))
25957 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
25958 (setq rpl (concat "<i>&lt;" type ":"
25959 (save-match-data (org-link-unescape path))
25960 "&gt;</i>"))))
25961 (setq line (replace-match rpl t t line)
25962 start (+ start (length rpl))))
25964 ;; TODO items
25965 (if (and (string-match org-todo-line-regexp line)
25966 (match-beginning 2))
25968 (setq line
25969 (concat (substring line 0 (match-beginning 2))
25970 "<span class=\""
25971 (if (member (match-string 2 line)
25972 org-done-keywords)
25973 "done" "todo")
25974 "\">" (match-string 2 line)
25975 "</span>" (substring line (match-end 2)))))
25977 ;; Does this contain a reference to a footnote?
25978 (when org-export-with-footnotes
25979 (setq start 0)
25980 (while (string-match "\\([^* \t].*?\\)\\[\\([0-9]+\\)\\]" line start)
25981 (if (get-text-property (match-beginning 2) 'org-protected line)
25982 (setq start (match-end 2))
25983 (let ((n (match-string 2 line)))
25984 (setq line
25985 (replace-match
25986 (format
25987 "%s<sup><a class=\"footref\" name=\"fnr.%s\" href=\"#fn.%s\">%s</a></sup>"
25988 (match-string 1 line) n n n)
25989 t t line))))))
25991 (cond
25992 ((string-match "^\\(\\*+\\)[ \t]+\\(.*\\)" line)
25993 ;; This is a headline
25994 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
25995 txt (match-string 2 line))
25996 (if (string-match quote-re0 txt)
25997 (setq txt (replace-match "" t t txt)))
25998 (if (<= level (max umax umax-toc))
25999 (setq head-count (+ head-count 1)))
26000 (when in-local-list
26001 ;; Close any local lists before inserting a new header line
26002 (while local-list-num
26003 (org-close-li)
26004 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
26005 (pop local-list-num))
26006 (setq local-list-indent nil
26007 in-local-list nil))
26008 (setq first-heading-pos (or first-heading-pos (point)))
26009 (org-html-level-start level txt umax
26010 (and org-export-with-toc (<= level umax))
26011 head-count)
26012 ;; QUOTES
26013 (when (string-match quote-re line)
26014 (insert "<pre>")
26015 (setq inquote t)))
26017 ((and org-export-with-tables
26018 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
26019 (if (not table-open)
26020 ;; New table starts
26021 (setq table-open t table-buffer nil table-orig-buffer nil))
26022 ;; Accumulate lines
26023 (setq table-buffer (cons line table-buffer)
26024 table-orig-buffer (cons origline table-orig-buffer))
26025 (when (or (not lines)
26026 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
26027 (car lines))))
26028 (setq table-open nil
26029 table-buffer (nreverse table-buffer)
26030 table-orig-buffer (nreverse table-orig-buffer))
26031 (org-close-par-maybe)
26032 (insert (org-format-table-html table-buffer table-orig-buffer))))
26034 ;; Normal lines
26035 (when (string-match
26036 (cond
26037 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26038 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26039 ((= llt ?\)) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
26040 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
26041 line)
26042 (setq ind (org-get-string-indentation line)
26043 start-is-num (match-beginning 4)
26044 starter (if (match-beginning 2)
26045 (substring (match-string 2 line) 0 -1))
26046 line (substring line (match-beginning 5)))
26047 (unless (string-match "[^ \t]" line)
26048 ;; empty line. Pretend indentation is large.
26049 (setq ind (if org-empty-line-terminates-plain-lists
26051 (1+ (or (car local-list-indent) 1)))))
26052 (setq didclose nil)
26053 (while (and in-local-list
26054 (or (and (= ind (car local-list-indent))
26055 (not starter))
26056 (< ind (car local-list-indent))))
26057 (setq didclose t)
26058 (org-close-li)
26059 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
26060 (pop local-list-num) (pop local-list-indent)
26061 (setq in-local-list local-list-indent))
26062 (cond
26063 ((and starter
26064 (or (not in-local-list)
26065 (> ind (car local-list-indent))))
26066 ;; Start new (level of) list
26067 (org-close-par-maybe)
26068 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
26069 (push start-is-num local-list-num)
26070 (push ind local-list-indent)
26071 (setq in-local-list t))
26072 (starter
26073 ;; continue current list
26074 (org-close-li)
26075 (insert "<li>\n"))
26076 (didclose
26077 ;; we did close a list, normal text follows: need <p>
26078 (org-open-par)))
26079 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
26080 (setq line
26081 (replace-match
26082 (if (equal (match-string 1 line) "X")
26083 "<b>[X]</b>"
26084 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
26085 t t line))))
26087 ;; Empty lines start a new paragraph. If hand-formatted lists
26088 ;; are not fully interpreted, lines starting with "-", "+", "*"
26089 ;; also start a new paragraph.
26090 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
26092 ;; Is this the start of a footnote?
26093 (when org-export-with-footnotes
26094 (when (string-match "^[ \t]*\\[\\([0-9]+\\)\\]" line)
26095 (org-close-par-maybe)
26096 (let ((n (match-string 1 line)))
26097 (setq line (replace-match
26098 (format "<p class=\"footnote\"><sup><a class=\"footnum\" name=\"fn.%s\" href=\"#fnr.%s\">%s</a></sup>" n n n) t t line)))))
26100 ;; Check if the line break needs to be conserved
26101 (cond
26102 ((string-match "\\\\\\\\[ \t]*$" line)
26103 (setq line (replace-match "<br/>" t t line)))
26104 (org-export-preserve-breaks
26105 (setq line (concat line "<br/>"))))
26107 (insert line "\n")))))
26109 ;; Properly close all local lists and other lists
26110 (when inquote (insert "</pre>\n"))
26111 (when in-local-list
26112 ;; Close any local lists before inserting a new header line
26113 (while local-list-num
26114 (org-close-li)
26115 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
26116 (pop local-list-num))
26117 (setq local-list-indent nil
26118 in-local-list nil))
26119 (org-html-level-start 1 nil umax
26120 (and org-export-with-toc (<= level umax))
26121 head-count)
26123 (unless body-only
26124 (when (plist-get opt-plist :auto-postamble)
26125 (insert "<div id=\"postamble\">")
26126 (when (and org-export-author-info author)
26127 (insert "<p class=\"author\"> "
26128 (nth 1 lang-words) ": " author "\n")
26129 (when email
26130 (if (listp (split-string email ",+ *"))
26131 (mapc (lambda(e)
26132 (insert "<a href=\"mailto:" e "\">&lt;"
26133 e "&gt;</a>\n"))
26134 (split-string email ",+ *"))
26135 (insert "<a href=\"mailto:" email "\">&lt;"
26136 email "&gt;</a>\n")))
26137 (insert "</p>\n"))
26138 (when (and date org-export-time-stamp-file)
26139 (insert "<p class=\"date\"> "
26140 (nth 2 lang-words) ": "
26141 date "</p>\n"))
26142 (insert "</div>"))
26144 (if org-export-html-with-timestamp
26145 (insert org-export-html-html-helper-timestamp))
26146 (insert (or (plist-get opt-plist :postamble) ""))
26147 (insert "</body>\n</html>\n"))
26149 (normal-mode)
26150 (if (eq major-mode default-major-mode) (html-mode))
26152 ;; insert the table of contents
26153 (goto-char (point-min))
26154 (when thetoc
26155 (if (or (re-search-forward
26156 "<p>\\s-*\\[TABLE-OF-CONTENTS\\]\\s-*</p>" nil t)
26157 (re-search-forward
26158 "\\[TABLE-OF-CONTENTS\\]" nil t))
26159 (progn
26160 (goto-char (match-beginning 0))
26161 (replace-match ""))
26162 (goto-char first-heading-pos)
26163 (when (looking-at "\\s-*</p>")
26164 (goto-char (match-end 0))
26165 (insert "\n")))
26166 (insert "<div id=\"table-of-contents\">\n")
26167 (mapc 'insert thetoc)
26168 (insert "</div>\n"))
26169 ;; remove empty paragraphs and lists
26170 (goto-char (point-min))
26171 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
26172 (replace-match ""))
26173 (goto-char (point-min))
26174 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
26175 (replace-match ""))
26176 (goto-char (point-min))
26177 (while (re-search-forward "</ul>\\s-*<ul>\n?" nil t)
26178 (replace-match ""))
26179 ;; Convert whitespace place holders
26180 (goto-char (point-min))
26181 (let (beg end n)
26182 (while (setq beg (next-single-property-change (point) 'org-whitespace))
26183 (setq n (get-text-property beg 'org-whitespace)
26184 end (next-single-property-change beg 'org-whitespace))
26185 (goto-char beg)
26186 (delete-region beg end)
26187 (insert (format "<span style=\"visibility:hidden;\">%s</span>"
26188 (make-string n ?x)))))
26189 (or to-buffer (save-buffer))
26190 (goto-char (point-min))
26191 (message "Exporting... done")
26192 (if (eq to-buffer 'string)
26193 (prog1 (buffer-substring (point-min) (point-max))
26194 (kill-buffer (current-buffer)))
26195 (current-buffer)))))
26197 (defvar org-table-colgroup-info nil)
26198 (defun org-format-table-ascii (lines)
26199 "Format a table for ascii export."
26200 (if (stringp lines)
26201 (setq lines (org-split-string lines "\n")))
26202 (if (not (string-match "^[ \t]*|" (car lines)))
26203 ;; Table made by table.el - test for spanning
26204 lines
26206 ;; A normal org table
26207 ;; Get rid of hlines at beginning and end
26208 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26209 (setq lines (nreverse lines))
26210 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26211 (setq lines (nreverse lines))
26212 (when org-export-table-remove-special-lines
26213 ;; Check if the table has a marking column. If yes remove the
26214 ;; column and the special lines
26215 (setq lines (org-table-clean-before-export lines)))
26216 ;; Get rid of the vertical lines except for grouping
26217 (let ((vl (org-colgroup-info-to-vline-list org-table-colgroup-info))
26218 rtn line vl1 start)
26219 (while (setq line (pop lines))
26220 (if (string-match org-table-hline-regexp line)
26221 (and (string-match "|\\(.*\\)|" line)
26222 (setq line (replace-match " \\1" t nil line)))
26223 (setq start 0 vl1 vl)
26224 (while (string-match "|" line start)
26225 (setq start (match-end 0))
26226 (or (pop vl1) (setq line (replace-match " " t t line)))))
26227 (push line rtn))
26228 (nreverse rtn))))
26230 (defun org-colgroup-info-to-vline-list (info)
26231 (let (vl new last)
26232 (while info
26233 (setq last new new (pop info))
26234 (if (or (memq last '(:end :startend))
26235 (memq new '(:start :startend)))
26236 (push t vl)
26237 (push nil vl)))
26238 (setq vl (nreverse vl))
26239 (and vl (setcar vl nil))
26240 vl))
26242 (defun org-format-table-html (lines olines)
26243 "Find out which HTML converter to use and return the HTML code."
26244 (if (stringp lines)
26245 (setq lines (org-split-string lines "\n")))
26246 (if (string-match "^[ \t]*|" (car lines))
26247 ;; A normal org table
26248 (org-format-org-table-html lines)
26249 ;; Table made by table.el - test for spanning
26250 (let* ((hlines (delq nil (mapcar
26251 (lambda (x)
26252 (if (string-match "^[ \t]*\\+-" x) x
26253 nil))
26254 lines)))
26255 (first (car hlines))
26256 (ll (and (string-match "\\S-+" first)
26257 (match-string 0 first)))
26258 (re (concat "^[ \t]*" (regexp-quote ll)))
26259 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
26260 hlines))))
26261 (if (and (not spanning)
26262 (not org-export-prefer-native-exporter-for-tables))
26263 ;; We can use my own converter with HTML conversions
26264 (org-format-table-table-html lines)
26265 ;; Need to use the code generator in table.el, with the original text.
26266 (org-format-table-table-html-using-table-generate-source olines)))))
26268 (defun org-format-org-table-html (lines &optional splice)
26269 "Format a table into HTML."
26270 ;; Get rid of hlines at beginning and end
26271 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26272 (setq lines (nreverse lines))
26273 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
26274 (setq lines (nreverse lines))
26275 (when org-export-table-remove-special-lines
26276 ;; Check if the table has a marking column. If yes remove the
26277 ;; column and the special lines
26278 (setq lines (org-table-clean-before-export lines)))
26280 (let ((head (and org-export-highlight-first-table-line
26281 (delq nil (mapcar
26282 (lambda (x) (string-match "^[ \t]*|-" x))
26283 (cdr lines)))))
26284 (nlines 0) fnum i
26285 tbopen line fields html gr colgropen)
26286 (if splice (setq head nil))
26287 (unless splice (push (if head "<thead>" "<tbody>") html))
26288 (setq tbopen t)
26289 (while (setq line (pop lines))
26290 (catch 'next-line
26291 (if (string-match "^[ \t]*|-" line)
26292 (progn
26293 (unless splice
26294 (push (if head "</thead>" "</tbody>") html)
26295 (if lines (push "<tbody>" html) (setq tbopen nil)))
26296 (setq head nil) ;; head ends here, first time around
26297 ;; ignore this line
26298 (throw 'next-line t)))
26299 ;; Break the line into fields
26300 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26301 (unless fnum (setq fnum (make-vector (length fields) 0)))
26302 (setq nlines (1+ nlines) i -1)
26303 (push (concat "<tr>"
26304 (mapconcat
26305 (lambda (x)
26306 (setq i (1+ i))
26307 (if (and (< i nlines)
26308 (string-match org-table-number-regexp x))
26309 (incf (aref fnum i)))
26310 (if head
26311 (concat (car org-export-table-header-tags) x
26312 (cdr org-export-table-header-tags))
26313 (concat (car org-export-table-data-tags) x
26314 (cdr org-export-table-data-tags))))
26315 fields "")
26316 "</tr>")
26317 html)))
26318 (unless splice (if tbopen (push "</tbody>" html)))
26319 (unless splice (push "</table>\n" html))
26320 (setq html (nreverse html))
26321 (unless splice
26322 ;; Put in col tags with the alignment (unfortuntely often ignored...)
26323 (push (mapconcat
26324 (lambda (x)
26325 (setq gr (pop org-table-colgroup-info))
26326 (format "%s<col align=\"%s\"></col>%s"
26327 (if (memq gr '(:start :startend))
26328 (prog1
26329 (if colgropen "</colgroup>\n<colgroup>" "<colgroup>")
26330 (setq colgropen t))
26332 (if (> (/ (float x) nlines) org-table-number-fraction)
26333 "right" "left")
26334 (if (memq gr '(:end :startend))
26335 (progn (setq colgropen nil) "</colgroup>")
26336 "")))
26337 fnum "")
26338 html)
26339 (if colgropen (setq html (cons (car html) (cons "</colgroup>" (cdr html)))))
26340 (push html-table-tag html))
26341 (concat (mapconcat 'identity html "\n") "\n")))
26343 (defun org-table-clean-before-export (lines)
26344 "Check if the table has a marking column.
26345 If yes remove the column and the special lines."
26346 (setq org-table-colgroup-info nil)
26347 (if (memq nil
26348 (mapcar
26349 (lambda (x) (or (string-match "^[ \t]*|-" x)
26350 (string-match "^[ \t]*| *\\([#!$*_^ /]\\) *|" x)))
26351 lines))
26352 (progn
26353 (setq org-table-clean-did-remove-column nil)
26354 (delq nil
26355 (mapcar
26356 (lambda (x)
26357 (cond
26358 ((string-match "^[ \t]*| */ *|" x)
26359 (setq org-table-colgroup-info
26360 (mapcar (lambda (x)
26361 (cond ((member x '("<" "&lt;")) :start)
26362 ((member x '(">" "&gt;")) :end)
26363 ((member x '("<>" "&lt;&gt;")) :startend)
26364 (t nil)))
26365 (org-split-string x "[ \t]*|[ \t]*")))
26366 nil)
26367 (t x)))
26368 lines)))
26369 (setq org-table-clean-did-remove-column t)
26370 (delq nil
26371 (mapcar
26372 (lambda (x)
26373 (cond
26374 ((string-match "^[ \t]*| */ *|" x)
26375 (setq org-table-colgroup-info
26376 (mapcar (lambda (x)
26377 (cond ((member x '("<" "&lt;")) :start)
26378 ((member x '(">" "&gt;")) :end)
26379 ((member x '("<>" "&lt;&gt;")) :startend)
26380 (t nil)))
26381 (cdr (org-split-string x "[ \t]*|[ \t]*"))))
26382 nil)
26383 ((string-match "^[ \t]*| *[!_^/] *|" x)
26384 nil) ; ignore this line
26385 ((or (string-match "^\\([ \t]*\\)|-+\\+" x)
26386 (string-match "^\\([ \t]*\\)|[^|]*|" x))
26387 ;; remove the first column
26388 (replace-match "\\1|" t nil x))))
26389 lines))))
26391 (defun org-format-table-table-html (lines)
26392 "Format a table generated by table.el into HTML.
26393 This conversion does *not* use `table-generate-source' from table.el.
26394 This has the advantage that Org-mode's HTML conversions can be used.
26395 But it has the disadvantage, that no cell- or row-spanning is allowed."
26396 (let (line field-buffer
26397 (head org-export-highlight-first-table-line)
26398 fields html empty)
26399 (setq html (concat html-table-tag "\n"))
26400 (while (setq line (pop lines))
26401 (setq empty "&nbsp;")
26402 (catch 'next-line
26403 (if (string-match "^[ \t]*\\+-" line)
26404 (progn
26405 (if field-buffer
26406 (progn
26407 (setq
26408 html
26409 (concat
26410 html
26411 "<tr>"
26412 (mapconcat
26413 (lambda (x)
26414 (if (equal x "") (setq x empty))
26415 (if head
26416 (concat (car org-export-table-header-tags) x
26417 (cdr org-export-table-header-tags))
26418 (concat (car org-export-table-data-tags) x
26419 (cdr org-export-table-data-tags))))
26420 field-buffer "\n")
26421 "</tr>\n"))
26422 (setq head nil)
26423 (setq field-buffer nil)))
26424 ;; Ignore this line
26425 (throw 'next-line t)))
26426 ;; Break the line into fields and store the fields
26427 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
26428 (if field-buffer
26429 (setq field-buffer (mapcar
26430 (lambda (x)
26431 (concat x "<br/>" (pop fields)))
26432 field-buffer))
26433 (setq field-buffer fields))))
26434 (setq html (concat html "</table>\n"))
26435 html))
26437 (defun org-format-table-table-html-using-table-generate-source (lines)
26438 "Format a table into html, using `table-generate-source' from table.el.
26439 This has the advantage that cell- or row-spanning is allowed.
26440 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
26441 (require 'table)
26442 (with-current-buffer (get-buffer-create " org-tmp1 ")
26443 (erase-buffer)
26444 (insert (mapconcat 'identity lines "\n"))
26445 (goto-char (point-min))
26446 (if (not (re-search-forward "|[^+]" nil t))
26447 (error "Error processing table"))
26448 (table-recognize-table)
26449 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
26450 (table-generate-source 'html " org-tmp2 ")
26451 (set-buffer " org-tmp2 ")
26452 (buffer-substring (point-min) (point-max))))
26454 (defun org-html-handle-time-stamps (s)
26455 "Format time stamps in string S, or remove them."
26456 (catch 'exit
26457 (let (r b)
26458 (while (string-match org-maybe-keyword-time-regexp s)
26459 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
26460 ;; never export CLOCK
26461 (throw 'exit ""))
26462 (or b (setq b (substring s 0 (match-beginning 0))))
26463 (if (not org-export-with-timestamps)
26464 (setq r (concat r (substring s 0 (match-beginning 0)))
26465 s (substring s (match-end 0)))
26466 (setq r (concat
26467 r (substring s 0 (match-beginning 0))
26468 (if (match-end 1)
26469 (format "@<span class=\"timestamp-kwd\">%s @</span>"
26470 (match-string 1 s)))
26471 (format " @<span class=\"timestamp\">%s@</span>"
26472 (substring
26473 (org-translate-time (match-string 3 s)) 1 -1)))
26474 s (substring s (match-end 0)))))
26475 ;; Line break if line started and ended with time stamp stuff
26476 (if (not r)
26478 (setq r (concat r s))
26479 (unless (string-match "\\S-" (concat b s))
26480 (setq r (concat r "@<br/>")))
26481 r))))
26483 (defun org-html-protect (s)
26484 ;; convert & to &amp;, < to &lt; and > to &gt;
26485 (let ((start 0))
26486 (while (string-match "&" s start)
26487 (setq s (replace-match "&amp;" t t s)
26488 start (1+ (match-beginning 0))))
26489 (while (string-match "<" s)
26490 (setq s (replace-match "&lt;" t t s)))
26491 (while (string-match ">" s)
26492 (setq s (replace-match "&gt;" t t s))))
26495 (defun org-export-cleanup-toc-line (s)
26496 "Remove tags and time staps from lines going into the toc."
26497 (when (memq org-export-with-tags '(not-in-toc nil))
26498 (if (string-match (org-re " +:[[:alnum:]_@:]+: *$") s)
26499 (setq s (replace-match "" t t s))))
26500 (when org-export-remove-timestamps-from-toc
26501 (while (string-match org-maybe-keyword-time-regexp s)
26502 (setq s (replace-match "" t t s))))
26503 (while (string-match org-bracket-link-regexp s)
26504 (setq s (replace-match (match-string (if (match-end 3) 3 1) s)
26505 t t s)))
26508 (defun org-html-expand (string)
26509 "Prepare STRING for HTML export. Applies all active conversions.
26510 If there are links in the string, don't modify these."
26511 (let* ((re (concat org-bracket-link-regexp "\\|"
26512 (org-re "[ \t]+\\(:[[:alnum:]_@:]+:\\)[ \t]*$")))
26513 m s l res)
26514 (while (setq m (string-match re string))
26515 (setq s (substring string 0 m)
26516 l (match-string 0 string)
26517 string (substring string (match-end 0)))
26518 (push (org-html-do-expand s) res)
26519 (push l res))
26520 (push (org-html-do-expand string) res)
26521 (apply 'concat (nreverse res))))
26523 (defun org-html-do-expand (s)
26524 "Apply all active conversions to translate special ASCII to HTML."
26525 (setq s (org-html-protect s))
26526 (if org-export-html-expand
26527 (let ((start 0))
26528 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
26529 (setq s (replace-match "<\\1>" t nil s)))))
26530 (if org-export-with-emphasize
26531 (setq s (org-export-html-convert-emphasize s)))
26532 (if org-export-with-special-strings
26533 (setq s (org-export-html-convert-special-strings s)))
26534 (if org-export-with-sub-superscripts
26535 (setq s (org-export-html-convert-sub-super s)))
26536 (if org-export-with-TeX-macros
26537 (let ((start 0) wd ass)
26538 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
26539 (if (get-text-property (match-beginning 0) 'org-protected s)
26540 (setq start (match-end 0))
26541 (setq wd (match-string 1 s))
26542 (if (setq ass (assoc wd org-html-entities))
26543 (setq s (replace-match (or (cdr ass)
26544 (concat "&" (car ass) ";"))
26545 t t s))
26546 (setq start (+ start (length wd))))))))
26549 (defun org-create-multibrace-regexp (left right n)
26550 "Create a regular expression which will match a balanced sexp.
26551 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
26552 as single character strings.
26553 The regexp returned will match the entire expression including the
26554 delimiters. It will also define a single group which contains the
26555 match except for the outermost delimiters. The maximum depth of
26556 stacked delimiters is N. Escaping delimiters is not possible."
26557 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
26558 (or "\\|")
26559 (re nothing)
26560 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
26561 (while (> n 1)
26562 (setq n (1- n)
26563 re (concat re or next)
26564 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
26565 (concat left "\\(" re "\\)" right)))
26567 (defvar org-match-substring-regexp
26568 (concat
26569 "\\([^\\]\\)\\([_^]\\)\\("
26570 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26571 "\\|"
26572 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
26573 "\\|"
26574 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
26575 "The regular expression matching a sub- or superscript.")
26577 (defvar org-match-substring-with-braces-regexp
26578 (concat
26579 "\\([^\\]\\)\\([_^]\\)\\("
26580 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
26581 "\\)")
26582 "The regular expression matching a sub- or superscript, forcing braces.")
26584 (defconst org-export-html-special-string-regexps
26585 '(("\\\\-" . "&shy;")
26586 ("---\\([^-]\\)" . "&mdash;\\1")
26587 ("--\\([^-]\\)" . "&ndash;\\1")
26588 ("\\.\\.\\." . "&hellip;"))
26589 "Regular expressions for special string conversion.")
26591 (defun org-export-html-convert-special-strings (string)
26592 "Convert special characters in STRING to HTML."
26593 (let ((all org-export-html-special-string-regexps)
26594 e a re rpl start)
26595 (while (setq a (pop all))
26596 (setq re (car a) rpl (cdr a) start 0)
26597 (while (string-match re string start)
26598 (if (get-text-property (match-beginning 0) 'org-protected string)
26599 (setq start (match-end 0))
26600 (setq string (replace-match rpl t nil string)))))
26601 string))
26603 (defun org-export-html-convert-sub-super (string)
26604 "Convert sub- and superscripts in STRING to HTML."
26605 (let (key c (s 0) (requireb (eq org-export-with-sub-superscripts '{})))
26606 (while (string-match org-match-substring-regexp string s)
26607 (cond
26608 ((and requireb (match-end 8)) (setq s (match-end 2)))
26609 ((get-text-property (match-beginning 2) 'org-protected string)
26610 (setq s (match-end 2)))
26612 (setq s (match-end 1)
26613 key (if (string= (match-string 2 string) "_") "sub" "sup")
26614 c (or (match-string 8 string)
26615 (match-string 6 string)
26616 (match-string 5 string))
26617 string (replace-match
26618 (concat (match-string 1 string)
26619 "<" key ">" c "</" key ">")
26620 t t string)))))
26621 (while (string-match "\\\\\\([_^]\\)" string)
26622 (setq string (replace-match (match-string 1 string) t t string)))
26623 string))
26625 (defun org-export-html-convert-emphasize (string)
26626 "Apply emphasis."
26627 (let ((s 0) rpl)
26628 (while (string-match org-emph-re string s)
26629 (if (not (equal
26630 (substring string (match-beginning 3) (1+ (match-beginning 3)))
26631 (substring string (match-beginning 4) (1+ (match-beginning 4)))))
26632 (setq s (match-beginning 0)
26634 (concat
26635 (match-string 1 string)
26636 (nth 2 (assoc (match-string 3 string) org-emphasis-alist))
26637 (match-string 4 string)
26638 (nth 3 (assoc (match-string 3 string)
26639 org-emphasis-alist))
26640 (match-string 5 string))
26641 string (replace-match rpl t t string)
26642 s (+ s (- (length rpl) 2)))
26643 (setq s (1+ s))))
26644 string))
26646 (defvar org-par-open nil)
26647 (defun org-open-par ()
26648 "Insert <p>, but first close previous paragraph if any."
26649 (org-close-par-maybe)
26650 (insert "\n<p>")
26651 (setq org-par-open t))
26652 (defun org-close-par-maybe ()
26653 "Close paragraph if there is one open."
26654 (when org-par-open
26655 (insert "</p>")
26656 (setq org-par-open nil)))
26657 (defun org-close-li ()
26658 "Close <li> if necessary."
26659 (org-close-par-maybe)
26660 (insert "</li>\n"))
26662 (defvar body-only) ; dynamically scoped into this.
26663 (defun org-html-level-start (level title umax with-toc head-count)
26664 "Insert a new level in HTML export.
26665 When TITLE is nil, just close all open levels."
26666 (org-close-par-maybe)
26667 (let ((l org-level-max))
26668 (while (>= l level)
26669 (if (aref org-levels-open (1- l))
26670 (progn
26671 (org-html-level-close l umax)
26672 (aset org-levels-open (1- l) nil)))
26673 (setq l (1- l)))
26674 (when title
26675 ;; If title is nil, this means this function is called to close
26676 ;; all levels, so the rest is done only if title is given
26677 (when (string-match (org-re "\\(:[[:alnum:]_@:]+:\\)[ \t]*$") title)
26678 (setq title (replace-match
26679 (if org-export-with-tags
26680 (save-match-data
26681 (concat
26682 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
26683 (mapconcat 'identity (org-split-string
26684 (match-string 1 title) ":")
26685 "&nbsp;")
26686 "</span>"))
26688 t t title)))
26689 (if (> level umax)
26690 (progn
26691 (if (aref org-levels-open (1- level))
26692 (progn
26693 (org-close-li)
26694 (insert "<li>" title "<br/>\n"))
26695 (aset org-levels-open (1- level) t)
26696 (org-close-par-maybe)
26697 (insert "<ul>\n<li>" title "<br/>\n")))
26698 (aset org-levels-open (1- level) t)
26699 (if (and org-export-with-section-numbers (not body-only))
26700 (setq title (concat (org-section-number level) " " title)))
26701 (setq level (+ level org-export-html-toplevel-hlevel -1))
26702 (if with-toc
26703 (insert (format "\n<div class=\"outline-%d\">\n<h%d id=\"sec-%d\">%s</h%d>\n"
26704 level level head-count title level))
26705 (insert (format "\n<div class=\"outline-%d\">\n<h%d>%s</h%d>\n" level level title level)))
26706 (org-open-par)))))
26708 (defun org-html-level-close (level max-outline-level)
26709 "Terminate one level in HTML export."
26710 (if (<= level max-outline-level)
26711 (insert "</div>\n")
26712 (org-close-li)
26713 (insert "</ul>\n")))
26715 ;;; iCalendar export
26717 ;;;###autoload
26718 (defun org-export-icalendar-this-file ()
26719 "Export current file as an iCalendar file.
26720 The iCalendar file will be located in the same directory as the Org-mode
26721 file, but with extension `.ics'."
26722 (interactive)
26723 (org-export-icalendar nil buffer-file-name))
26725 ;;;###autoload
26726 (defun org-export-icalendar-all-agenda-files ()
26727 "Export all files in `org-agenda-files' to iCalendar .ics files.
26728 Each iCalendar file will be located in the same directory as the Org-mode
26729 file, but with extension `.ics'."
26730 (interactive)
26731 (apply 'org-export-icalendar nil (org-agenda-files t)))
26733 ;;;###autoload
26734 (defun org-export-icalendar-combine-agenda-files ()
26735 "Export all files in `org-agenda-files' to a single combined iCalendar file.
26736 The file is stored under the name `org-combined-agenda-icalendar-file'."
26737 (interactive)
26738 (apply 'org-export-icalendar t (org-agenda-files t)))
26740 (defun org-export-icalendar (combine &rest files)
26741 "Create iCalendar files for all elements of FILES.
26742 If COMBINE is non-nil, combine all calendar entries into a single large
26743 file and store it under the name `org-combined-agenda-icalendar-file'."
26744 (save-excursion
26745 (org-prepare-agenda-buffers files)
26746 (let* ((dir (org-export-directory
26747 :ical (list :publishing-directory
26748 org-export-publishing-directory)))
26749 file ical-file ical-buffer category started org-agenda-new-buffers)
26750 (and (get-buffer "*ical-tmp*") (kill-buffer "*ical-tmp*"))
26751 (when combine
26752 (setq ical-file
26753 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
26754 org-combined-agenda-icalendar-file
26755 (expand-file-name org-combined-agenda-icalendar-file dir))
26756 ical-buffer (org-get-agenda-file-buffer ical-file))
26757 (set-buffer ical-buffer) (erase-buffer))
26758 (while (setq file (pop files))
26759 (catch 'nextfile
26760 (org-check-agenda-file file)
26761 (set-buffer (org-get-agenda-file-buffer file))
26762 (unless combine
26763 (setq ical-file (concat (file-name-as-directory dir)
26764 (file-name-sans-extension
26765 (file-name-nondirectory buffer-file-name))
26766 ".ics"))
26767 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
26768 (with-current-buffer ical-buffer (erase-buffer)))
26769 (setq category (or org-category
26770 (file-name-sans-extension
26771 (file-name-nondirectory buffer-file-name))))
26772 (if (symbolp category) (setq category (symbol-name category)))
26773 (let ((standard-output ical-buffer))
26774 (if combine
26775 (and (not started) (setq started t)
26776 (org-start-icalendar-file org-icalendar-combined-name))
26777 (org-start-icalendar-file category))
26778 (org-print-icalendar-entries combine)
26779 (when (or (and combine (not files)) (not combine))
26780 (org-finish-icalendar-file)
26781 (set-buffer ical-buffer)
26782 (save-buffer)
26783 (run-hooks 'org-after-save-iCalendar-file-hook)))))
26784 (org-release-buffers org-agenda-new-buffers))))
26786 (defvar org-after-save-iCalendar-file-hook nil
26787 "Hook run after an iCalendar file has been saved.
26788 The iCalendar buffer is still current when this hook is run.
26789 A good way to use this is to tell a desktop calenndar application to re-read
26790 the iCalendar file.")
26792 (defun org-print-icalendar-entries (&optional combine)
26793 "Print iCalendar entries for the current Org-mode file to `standard-output'.
26794 When COMBINE is non nil, add the category to each line."
26795 (let ((re1 (concat org-ts-regexp "\\|<%%([^>\n]+>"))
26796 (re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
26797 (dts (org-ical-ts-to-string
26798 (format-time-string (cdr org-time-stamp-formats) (current-time))
26799 "DTSTART"))
26800 hd ts ts2 state status (inc t) pos b sexp rrule
26801 scheduledp deadlinep tmp pri category entry location summary desc
26802 (sexp-buffer (get-buffer-create "*ical-tmp*")))
26803 (org-refresh-category-properties)
26804 (save-excursion
26805 (goto-char (point-min))
26806 (while (re-search-forward re1 nil t)
26807 (catch :skip
26808 (org-agenda-skip)
26809 (when (boundp 'org-icalendar-verify-function)
26810 (unless (funcall org-icalendar-verify-function)
26811 (outline-next-heading)
26812 (backward-char 1)
26813 (throw :skip nil)))
26814 (setq pos (match-beginning 0)
26815 ts (match-string 0)
26816 inc t
26817 hd (org-get-heading)
26818 summary (org-icalendar-cleanup-string
26819 (org-entry-get nil "SUMMARY"))
26820 desc (org-icalendar-cleanup-string
26821 (or (org-entry-get nil "DESCRIPTION")
26822 (and org-icalendar-include-body (org-get-entry)))
26823 t org-icalendar-include-body)
26824 location (org-icalendar-cleanup-string
26825 (org-entry-get nil "LOCATION"))
26826 category (org-get-category))
26827 (if (looking-at re2)
26828 (progn
26829 (goto-char (match-end 0))
26830 (setq ts2 (match-string 1) inc nil))
26831 (setq tmp (buffer-substring (max (point-min)
26832 (- pos org-ds-keyword-length))
26833 pos)
26834 ts2 (if (string-match "[0-9]\\{1,2\\}:[0-9][0-9]-\\([0-9]\\{1,2\\}:[0-9][0-9]\\)" ts)
26835 (progn
26836 (setq inc nil)
26837 (replace-match "\\1" t nil ts))
26839 deadlinep (string-match org-deadline-regexp tmp)
26840 scheduledp (string-match org-scheduled-regexp tmp)
26841 ;; donep (org-entry-is-done-p)
26843 (if (or (string-match org-tr-regexp hd)
26844 (string-match org-ts-regexp hd))
26845 (setq hd (replace-match "" t t hd)))
26846 (if (string-match "\\+\\([0-9]+\\)\\([dwmy]\\)>" ts)
26847 (setq rrule
26848 (concat "\nRRULE:FREQ="
26849 (cdr (assoc
26850 (match-string 2 ts)
26851 '(("d" . "DAILY")("w" . "WEEKLY")
26852 ("m" . "MONTHLY")("y" . "YEARLY"))))
26853 ";INTERVAL=" (match-string 1 ts)))
26854 (setq rrule ""))
26855 (setq summary (or summary hd))
26856 (if (string-match org-bracket-link-regexp summary)
26857 (setq summary
26858 (replace-match (if (match-end 3)
26859 (match-string 3 summary)
26860 (match-string 1 summary))
26861 t t summary)))
26862 (if deadlinep (setq summary (concat "DL: " summary)))
26863 (if scheduledp (setq summary (concat "S: " summary)))
26864 (if (string-match "\\`<%%" ts)
26865 (with-current-buffer sexp-buffer
26866 (insert (substring ts 1 -1) " " summary "\n"))
26867 (princ (format "BEGIN:VEVENT
26869 %s%s
26870 SUMMARY:%s%s%s
26871 CATEGORIES:%s
26872 END:VEVENT\n"
26873 (org-ical-ts-to-string ts "DTSTART")
26874 (org-ical-ts-to-string ts2 "DTEND" inc)
26875 rrule summary
26876 (if (and desc (string-match "\\S-" desc))
26877 (concat "\nDESCRIPTION: " desc) "")
26878 (if (and location (string-match "\\S-" location))
26879 (concat "\nLOCATION: " location) "")
26880 category)))))
26882 (when (and org-icalendar-include-sexps
26883 (condition-case nil (require 'icalendar) (error nil))
26884 (fboundp 'icalendar-export-region))
26885 ;; Get all the literal sexps
26886 (goto-char (point-min))
26887 (while (re-search-forward "^&?%%(" nil t)
26888 (catch :skip
26889 (org-agenda-skip)
26890 (setq b (match-beginning 0))
26891 (goto-char (1- (match-end 0)))
26892 (forward-sexp 1)
26893 (end-of-line 1)
26894 (setq sexp (buffer-substring b (point)))
26895 (with-current-buffer sexp-buffer
26896 (insert sexp "\n"))
26897 (princ (org-diary-to-ical-string sexp-buffer)))))
26899 (when org-icalendar-include-todo
26900 (goto-char (point-min))
26901 (while (re-search-forward org-todo-line-regexp nil t)
26902 (catch :skip
26903 (org-agenda-skip)
26904 (when (boundp 'org-icalendar-verify-function)
26905 (unless (funcall org-icalendar-verify-function)
26906 (outline-next-heading)
26907 (backward-char 1)
26908 (throw :skip nil)))
26909 (setq state (match-string 2))
26910 (setq status (if (member state org-done-keywords)
26911 "COMPLETED" "NEEDS-ACTION"))
26912 (when (and state
26913 (or (not (member state org-done-keywords))
26914 (eq org-icalendar-include-todo 'all))
26915 (not (member org-archive-tag (org-get-tags-at)))
26917 (setq hd (match-string 3)
26918 summary (org-icalendar-cleanup-string
26919 (org-entry-get nil "SUMMARY"))
26920 desc (org-icalendar-cleanup-string
26921 (or (org-entry-get nil "DESCRIPTION")
26922 (and org-icalendar-include-body (org-get-entry)))
26923 t org-icalendar-include-body)
26924 location (org-icalendar-cleanup-string
26925 (org-entry-get nil "LOCATION")))
26926 (if (string-match org-bracket-link-regexp hd)
26927 (setq hd (replace-match (if (match-end 3) (match-string 3 hd)
26928 (match-string 1 hd))
26929 t t hd)))
26930 (if (string-match org-priority-regexp hd)
26931 (setq pri (string-to-char (match-string 2 hd))
26932 hd (concat (substring hd 0 (match-beginning 1))
26933 (substring hd (match-end 1))))
26934 (setq pri org-default-priority))
26935 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
26936 (- org-lowest-priority org-highest-priority))))))
26938 (princ (format "BEGIN:VTODO
26940 SUMMARY:%s%s%s
26941 CATEGORIES:%s
26942 SEQUENCE:1
26943 PRIORITY:%d
26944 STATUS:%s
26945 END:VTODO\n"
26947 (or summary hd)
26948 (if (and location (string-match "\\S-" location))
26949 (concat "\nLOCATION: " location) "")
26950 (if (and desc (string-match "\\S-" desc))
26951 (concat "\nDESCRIPTION: " desc) "")
26952 category pri status)))))))))
26954 (defun org-icalendar-cleanup-string (s &optional is-body maxlength)
26955 "Take out stuff and quote what needs to be quoted.
26956 When IS-BODY is non-nil, assume that this is the body of an item, clean up
26957 whitespace, newlines, drawers, and timestamps, and cut it down to MAXLENGTH
26958 characters."
26959 (if (not s)
26961 (when is-body
26962 (let ((re (concat "\\(" org-drawer-regexp "\\)[^\000]*?:END:.*\n?"))
26963 (re2 (concat "^[ \t]*" org-keyword-time-regexp ".*\n?")))
26964 (while (string-match re s) (setq s (replace-match "" t t s)))
26965 (while (string-match re2 s) (setq s (replace-match "" t t s)))))
26966 (let ((start 0))
26967 (while (string-match "\\([,;\\]\\)" s start)
26968 (setq start (+ (match-beginning 0) 2)
26969 s (replace-match "\\\\\\1" nil nil s))))
26970 (when is-body
26971 (while (string-match "[ \t]*\n[ \t]*" s)
26972 (setq s (replace-match "\\n" t t s))))
26973 (setq s (org-trim s))
26974 (if is-body
26975 (if maxlength
26976 (if (and (numberp maxlength)
26977 (> (length s) maxlength))
26978 (setq s (substring s 0 maxlength)))))
26981 (defun org-get-entry ()
26982 "Clean-up description string."
26983 (save-excursion
26984 (org-back-to-heading t)
26985 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
26987 (defun org-start-icalendar-file (name)
26988 "Start an iCalendar file by inserting the header."
26989 (let ((user user-full-name)
26990 (name (or name "unknown"))
26991 (timezone (cadr (current-time-zone))))
26992 (princ
26993 (format "BEGIN:VCALENDAR
26994 VERSION:2.0
26995 X-WR-CALNAME:%s
26996 PRODID:-//%s//Emacs with Org-mode//EN
26997 X-WR-TIMEZONE:%s
26998 CALSCALE:GREGORIAN\n" name user timezone))))
27000 (defun org-finish-icalendar-file ()
27001 "Finish an iCalendar file by inserting the END statement."
27002 (princ "END:VCALENDAR\n"))
27004 (defun org-ical-ts-to-string (s keyword &optional inc)
27005 "Take a time string S and convert it to iCalendar format.
27006 KEYWORD is added in front, to make a complete line like DTSTART....
27007 When INC is non-nil, increase the hour by two (if time string contains
27008 a time), or the day by one (if it does not contain a time)."
27009 (let ((t1 (org-parse-time-string s 'nodefault))
27010 t2 fmt have-time time)
27011 (if (and (car t1) (nth 1 t1) (nth 2 t1))
27012 (setq t2 t1 have-time t)
27013 (setq t2 (org-parse-time-string s)))
27014 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
27015 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
27016 (when inc
27017 (if have-time
27018 (if org-agenda-default-appointment-duration
27019 (setq mi (+ org-agenda-default-appointment-duration mi))
27020 (setq h (+ 2 h)))
27021 (setq d (1+ d))))
27022 (setq time (encode-time s mi h d m y)))
27023 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
27024 (concat keyword (format-time-string fmt time))))
27026 ;;; XOXO export
27028 (defun org-export-as-xoxo-insert-into (buffer &rest output)
27029 (with-current-buffer buffer
27030 (apply 'insert output)))
27031 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
27033 (defun org-export-as-xoxo (&optional buffer)
27034 "Export the org buffer as XOXO.
27035 The XOXO buffer is named *xoxo-<source buffer name>*"
27036 (interactive (list (current-buffer)))
27037 ;; A quickie abstraction
27039 ;; Output everything as XOXO
27040 (with-current-buffer (get-buffer buffer)
27041 (let* ((pos (point))
27042 (opt-plist (org-combine-plists (org-default-export-plist)
27043 (org-infile-export-plist)))
27044 (filename (concat (file-name-as-directory
27045 (org-export-directory :xoxo opt-plist))
27046 (file-name-sans-extension
27047 (file-name-nondirectory buffer-file-name))
27048 ".html"))
27049 (out (find-file-noselect filename))
27050 (last-level 1)
27051 (hanging-li nil))
27052 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
27053 ;; Check the output buffer is empty.
27054 (with-current-buffer out (erase-buffer))
27055 ;; Kick off the output
27056 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
27057 (while (re-search-forward "^\\(\\*+\\)[ \t]+\\(.+\\)" (point-max) 't)
27058 (let* ((hd (match-string-no-properties 1))
27059 (level (length hd))
27060 (text (concat
27061 (match-string-no-properties 2)
27062 (save-excursion
27063 (goto-char (match-end 0))
27064 (let ((str ""))
27065 (catch 'loop
27066 (while 't
27067 (forward-line)
27068 (if (looking-at "^[ \t]\\(.*\\)")
27069 (setq str (concat str (match-string-no-properties 1)))
27070 (throw 'loop str)))))))))
27072 ;; Handle level rendering
27073 (cond
27074 ((> level last-level)
27075 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
27077 ((< level last-level)
27078 (dotimes (- (- last-level level) 1)
27079 (if hanging-li
27080 (org-export-as-xoxo-insert-into out "</li>\n"))
27081 (org-export-as-xoxo-insert-into out "</ol>\n"))
27082 (when hanging-li
27083 (org-export-as-xoxo-insert-into out "</li>\n")
27084 (setq hanging-li nil)))
27086 ((equal level last-level)
27087 (if hanging-li
27088 (org-export-as-xoxo-insert-into out "</li>\n")))
27091 (setq last-level level)
27093 ;; And output the new li
27094 (setq hanging-li 't)
27095 (if (equal ?+ (elt text 0))
27096 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
27097 (org-export-as-xoxo-insert-into out "<li>" text))))
27099 ;; Finally finish off the ol
27100 (dotimes (- last-level 1)
27101 (if hanging-li
27102 (org-export-as-xoxo-insert-into out "</li>\n"))
27103 (org-export-as-xoxo-insert-into out "</ol>\n"))
27105 (goto-char pos)
27106 ;; Finish the buffer off and clean it up.
27107 (switch-to-buffer-other-window out)
27108 (indent-region (point-min) (point-max) nil)
27109 (save-buffer)
27110 (goto-char (point-min))
27114 ;;;; Key bindings
27116 ;; Make `C-c C-x' a prefix key
27117 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
27119 ;; TAB key with modifiers
27120 (org-defkey org-mode-map "\C-i" 'org-cycle)
27121 (org-defkey org-mode-map [(tab)] 'org-cycle)
27122 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
27123 (org-defkey org-mode-map [(meta tab)] 'org-complete)
27124 (org-defkey org-mode-map "\M-\t" 'org-complete)
27125 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
27126 ;; The following line is necessary under Suse GNU/Linux
27127 (unless (featurep 'xemacs)
27128 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
27129 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
27130 (define-key org-mode-map [backtab] 'org-shifttab)
27132 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
27133 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
27134 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
27136 ;; Cursor keys with modifiers
27137 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
27138 (org-defkey org-mode-map [(meta right)] 'org-metaright)
27139 (org-defkey org-mode-map [(meta up)] 'org-metaup)
27140 (org-defkey org-mode-map [(meta down)] 'org-metadown)
27142 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
27143 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
27144 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
27145 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
27147 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
27148 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
27149 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
27150 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
27152 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
27153 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
27155 ;;; Extra keys for tty access.
27156 ;; We only set them when really needed because otherwise the
27157 ;; menus don't show the simple keys
27159 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
27160 (not window-system))
27161 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
27162 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
27163 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
27164 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
27165 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
27166 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
27167 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
27168 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
27169 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
27170 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
27171 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
27172 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
27173 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
27174 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
27175 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
27176 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
27177 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
27178 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
27179 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
27180 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
27181 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
27182 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
27184 ;; All the other keys
27186 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
27187 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
27188 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
27189 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
27190 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
27191 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
27192 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
27193 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
27194 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
27195 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
27196 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
27197 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
27198 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
27199 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
27200 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
27201 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
27202 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
27203 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
27204 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
27205 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
27206 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
27207 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
27208 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
27209 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
27210 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
27211 (org-defkey org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
27212 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
27213 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
27214 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
27215 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
27216 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
27217 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
27218 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
27219 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
27220 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
27221 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
27222 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
27223 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
27224 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
27225 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
27226 (org-defkey org-mode-map "\C-c^" 'org-sort)
27227 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
27228 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
27229 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
27230 (org-defkey org-mode-map "\C-m" 'org-return)
27231 (org-defkey org-mode-map "\C-j" 'org-return-indent)
27232 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
27233 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
27234 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
27235 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
27236 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
27237 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
27238 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
27239 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
27240 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
27241 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
27242 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
27243 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
27244 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
27245 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
27246 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
27248 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
27249 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
27250 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
27251 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
27253 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
27254 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
27255 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
27256 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
27257 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
27258 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
27259 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
27260 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
27261 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
27262 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
27263 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
27264 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
27266 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
27268 (when (featurep 'xemacs)
27269 (org-defkey org-mode-map 'button3 'popup-mode-menu))
27271 (defsubst org-table-p () (org-at-table-p))
27273 (defun org-self-insert-command (N)
27274 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
27275 If the cursor is in a table looking at whitespace, the whitespace is
27276 overwritten, and the table is not marked as requiring realignment."
27277 (interactive "p")
27278 (if (and (org-table-p)
27279 (progn
27280 ;; check if we blank the field, and if that triggers align
27281 (and org-table-auto-blank-field
27282 (member last-command
27283 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
27284 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
27285 ;; got extra space, this field does not determine column width
27286 (let (org-table-may-need-update) (org-table-blank-field))
27287 ;; no extra space, this field may determine column width
27288 (org-table-blank-field)))
27290 (eq N 1)
27291 (looking-at "[^|\n]* |"))
27292 (let (org-table-may-need-update)
27293 (goto-char (1- (match-end 0)))
27294 (delete-backward-char 1)
27295 (goto-char (match-beginning 0))
27296 (self-insert-command N))
27297 (setq org-table-may-need-update t)
27298 (self-insert-command N)
27299 (org-fix-tags-on-the-fly)))
27301 (defun org-fix-tags-on-the-fly ()
27302 (when (and (equal (char-after (point-at-bol)) ?*)
27303 (org-on-heading-p))
27304 (org-align-tags-here org-tags-column)))
27306 (defun org-delete-backward-char (N)
27307 "Like `delete-backward-char', insert whitespace at field end in tables.
27308 When deleting backwards, in tables this function will insert whitespace in
27309 front of the next \"|\" separator, to keep the table aligned. The table will
27310 still be marked for re-alignment if the field did fill the entire column,
27311 because, in this case the deletion might narrow the column."
27312 (interactive "p")
27313 (if (and (org-table-p)
27314 (eq N 1)
27315 (string-match "|" (buffer-substring (point-at-bol) (point)))
27316 (looking-at ".*?|"))
27317 (let ((pos (point))
27318 (noalign (looking-at "[^|\n\r]* |"))
27319 (c org-table-may-need-update))
27320 (backward-delete-char N)
27321 (skip-chars-forward "^|")
27322 (insert " ")
27323 (goto-char (1- pos))
27324 ;; noalign: if there were two spaces at the end, this field
27325 ;; does not determine the width of the column.
27326 (if noalign (setq org-table-may-need-update c)))
27327 (backward-delete-char N)
27328 (org-fix-tags-on-the-fly)))
27330 (defun org-delete-char (N)
27331 "Like `delete-char', but insert whitespace at field end in tables.
27332 When deleting characters, in tables this function will insert whitespace in
27333 front of the next \"|\" separator, to keep the table aligned. The table will
27334 still be marked for re-alignment if the field did fill the entire column,
27335 because, in this case the deletion might narrow the column."
27336 (interactive "p")
27337 (if (and (org-table-p)
27338 (not (bolp))
27339 (not (= (char-after) ?|))
27340 (eq N 1))
27341 (if (looking-at ".*?|")
27342 (let ((pos (point))
27343 (noalign (looking-at "[^|\n\r]* |"))
27344 (c org-table-may-need-update))
27345 (replace-match (concat
27346 (substring (match-string 0) 1 -1)
27347 " |"))
27348 (goto-char pos)
27349 ;; noalign: if there were two spaces at the end, this field
27350 ;; does not determine the width of the column.
27351 (if noalign (setq org-table-may-need-update c)))
27352 (delete-char N))
27353 (delete-char N)
27354 (org-fix-tags-on-the-fly)))
27356 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
27357 (put 'org-self-insert-command 'delete-selection t)
27358 (put 'orgtbl-self-insert-command 'delete-selection t)
27359 (put 'org-delete-char 'delete-selection 'supersede)
27360 (put 'org-delete-backward-char 'delete-selection 'supersede)
27362 ;; Make `flyspell-mode' delay after some commands
27363 (put 'org-self-insert-command 'flyspell-delayed t)
27364 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
27365 (put 'org-delete-char 'flyspell-delayed t)
27366 (put 'org-delete-backward-char 'flyspell-delayed t)
27368 ;; Make pabbrev-mode expand after org-mode commands
27369 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
27370 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
27372 ;; How to do this: Measure non-white length of current string
27373 ;; If equal to column width, we should realign.
27375 (defun org-remap (map &rest commands)
27376 "In MAP, remap the functions given in COMMANDS.
27377 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
27378 (let (new old)
27379 (while commands
27380 (setq old (pop commands) new (pop commands))
27381 (if (fboundp 'command-remapping)
27382 (org-defkey map (vector 'remap old) new)
27383 (substitute-key-definition old new map global-map)))))
27385 (when (eq org-enable-table-editor 'optimized)
27386 ;; If the user wants maximum table support, we need to hijack
27387 ;; some standard editing functions
27388 (org-remap org-mode-map
27389 'self-insert-command 'org-self-insert-command
27390 'delete-char 'org-delete-char
27391 'delete-backward-char 'org-delete-backward-char)
27392 (org-defkey org-mode-map "|" 'org-force-self-insert))
27394 (defun org-shiftcursor-error ()
27395 "Throw an error because Shift-Cursor command was applied in wrong context."
27396 (error "This command is active in special context like tables, headlines or timestamps"))
27398 (defun org-shifttab (&optional arg)
27399 "Global visibility cycling or move to previous table field.
27400 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
27401 on context.
27402 See the individual commands for more information."
27403 (interactive "P")
27404 (cond
27405 ((org-at-table-p) (call-interactively 'org-table-previous-field))
27406 (arg (message "Content view to level: ")
27407 (org-content (prefix-numeric-value arg))
27408 (setq org-cycle-global-status 'overview))
27409 (t (call-interactively 'org-global-cycle))))
27411 (defun org-shiftmetaleft ()
27412 "Promote subtree or delete table column.
27413 Calls `org-promote-subtree', `org-outdent-item',
27414 or `org-table-delete-column', depending on context.
27415 See the individual commands for more information."
27416 (interactive)
27417 (cond
27418 ((org-at-table-p) (call-interactively 'org-table-delete-column))
27419 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
27420 ((org-at-item-p) (call-interactively 'org-outdent-item))
27421 (t (org-shiftcursor-error))))
27423 (defun org-shiftmetaright ()
27424 "Demote subtree or insert table column.
27425 Calls `org-demote-subtree', `org-indent-item',
27426 or `org-table-insert-column', depending on context.
27427 See the individual commands for more information."
27428 (interactive)
27429 (cond
27430 ((org-at-table-p) (call-interactively 'org-table-insert-column))
27431 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
27432 ((org-at-item-p) (call-interactively 'org-indent-item))
27433 (t (org-shiftcursor-error))))
27435 (defun org-shiftmetaup (&optional arg)
27436 "Move subtree up or kill table row.
27437 Calls `org-move-subtree-up' or `org-table-kill-row' or
27438 `org-move-item-up' depending on context. See the individual commands
27439 for more information."
27440 (interactive "P")
27441 (cond
27442 ((org-at-table-p) (call-interactively 'org-table-kill-row))
27443 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27444 ((org-at-item-p) (call-interactively 'org-move-item-up))
27445 (t (org-shiftcursor-error))))
27446 (defun org-shiftmetadown (&optional arg)
27447 "Move subtree down or insert table row.
27448 Calls `org-move-subtree-down' or `org-table-insert-row' or
27449 `org-move-item-down', depending on context. See the individual
27450 commands for more information."
27451 (interactive "P")
27452 (cond
27453 ((org-at-table-p) (call-interactively 'org-table-insert-row))
27454 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27455 ((org-at-item-p) (call-interactively 'org-move-item-down))
27456 (t (org-shiftcursor-error))))
27458 (defun org-metaleft (&optional arg)
27459 "Promote heading or move table column to left.
27460 Calls `org-do-promote' or `org-table-move-column', depending on context.
27461 With no specific context, calls the Emacs default `backward-word'.
27462 See the individual commands for more information."
27463 (interactive "P")
27464 (cond
27465 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
27466 ((or (org-on-heading-p) (org-region-active-p))
27467 (call-interactively 'org-do-promote))
27468 ((org-at-item-p) (call-interactively 'org-outdent-item))
27469 (t (call-interactively 'backward-word))))
27471 (defun org-metaright (&optional arg)
27472 "Demote subtree or move table column to right.
27473 Calls `org-do-demote' or `org-table-move-column', depending on context.
27474 With no specific context, calls the Emacs default `forward-word'.
27475 See the individual commands for more information."
27476 (interactive "P")
27477 (cond
27478 ((org-at-table-p) (call-interactively 'org-table-move-column))
27479 ((or (org-on-heading-p) (org-region-active-p))
27480 (call-interactively 'org-do-demote))
27481 ((org-at-item-p) (call-interactively 'org-indent-item))
27482 (t (call-interactively 'forward-word))))
27484 (defun org-metaup (&optional arg)
27485 "Move subtree up or move table row up.
27486 Calls `org-move-subtree-up' or `org-table-move-row' or
27487 `org-move-item-up', depending on context. See the individual commands
27488 for more information."
27489 (interactive "P")
27490 (cond
27491 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
27492 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
27493 ((org-at-item-p) (call-interactively 'org-move-item-up))
27494 (t (transpose-lines 1) (beginning-of-line -1))))
27496 (defun org-metadown (&optional arg)
27497 "Move subtree down or move table row down.
27498 Calls `org-move-subtree-down' or `org-table-move-row' or
27499 `org-move-item-down', depending on context. See the individual
27500 commands for more information."
27501 (interactive "P")
27502 (cond
27503 ((org-at-table-p) (call-interactively 'org-table-move-row))
27504 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
27505 ((org-at-item-p) (call-interactively 'org-move-item-down))
27506 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
27508 (defun org-shiftup (&optional arg)
27509 "Increase item in timestamp or increase priority of current headline.
27510 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
27511 depending on context. See the individual commands for more information."
27512 (interactive "P")
27513 (cond
27514 ((org-at-timestamp-p t)
27515 (call-interactively (if org-edit-timestamp-down-means-later
27516 'org-timestamp-down 'org-timestamp-up)))
27517 ((org-on-heading-p) (call-interactively 'org-priority-up))
27518 ((org-at-item-p) (call-interactively 'org-previous-item))
27519 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
27521 (defun org-shiftdown (&optional arg)
27522 "Decrease item in timestamp or decrease priority of current headline.
27523 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
27524 depending on context. See the individual commands for more information."
27525 (interactive "P")
27526 (cond
27527 ((org-at-timestamp-p t)
27528 (call-interactively (if org-edit-timestamp-down-means-later
27529 'org-timestamp-up 'org-timestamp-down)))
27530 ((org-on-heading-p) (call-interactively 'org-priority-down))
27531 (t (call-interactively 'org-next-item))))
27533 (defun org-shiftright ()
27534 "Next TODO keyword or timestamp one day later, depending on context."
27535 (interactive)
27536 (cond
27537 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
27538 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
27539 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
27540 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
27541 (t (org-shiftcursor-error))))
27543 (defun org-shiftleft ()
27544 "Previous TODO keyword or timestamp one day earlier, depending on context."
27545 (interactive)
27546 (cond
27547 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
27548 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
27549 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
27550 ((org-at-property-p)
27551 (call-interactively 'org-property-previous-allowed-value))
27552 (t (org-shiftcursor-error))))
27554 (defun org-shiftcontrolright ()
27555 "Switch to next TODO set."
27556 (interactive)
27557 (cond
27558 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
27559 (t (org-shiftcursor-error))))
27561 (defun org-shiftcontrolleft ()
27562 "Switch to previous TODO set."
27563 (interactive)
27564 (cond
27565 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
27566 (t (org-shiftcursor-error))))
27568 (defun org-ctrl-c-ret ()
27569 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
27570 (interactive)
27571 (cond
27572 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
27573 (t (call-interactively 'org-insert-heading))))
27575 (defun org-copy-special ()
27576 "Copy region in table or copy current subtree.
27577 Calls `org-table-copy' or `org-copy-subtree', depending on context.
27578 See the individual commands for more information."
27579 (interactive)
27580 (call-interactively
27581 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
27583 (defun org-cut-special ()
27584 "Cut region in table or cut current subtree.
27585 Calls `org-table-copy' or `org-cut-subtree', depending on context.
27586 See the individual commands for more information."
27587 (interactive)
27588 (call-interactively
27589 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
27591 (defun org-paste-special (arg)
27592 "Paste rectangular region into table, or past subtree relative to level.
27593 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
27594 See the individual commands for more information."
27595 (interactive "P")
27596 (if (org-at-table-p)
27597 (org-table-paste-rectangle)
27598 (org-paste-subtree arg)))
27600 (defun org-ctrl-c-ctrl-c (&optional arg)
27601 "Set tags in headline, or update according to changed information at point.
27603 This command does many different things, depending on context:
27605 - If the cursor is in a headline, prompt for tags and insert them
27606 into the current line, aligned to `org-tags-column'. When called
27607 with prefix arg, realign all tags in the current buffer.
27609 - If the cursor is in one of the special #+KEYWORD lines, this
27610 triggers scanning the buffer for these lines and updating the
27611 information.
27613 - If the cursor is inside a table, realign the table. This command
27614 works even if the automatic table editor has been turned off.
27616 - If the cursor is on a #+TBLFM line, re-apply the formulas to
27617 the entire table.
27619 - If the cursor is a the beginning of a dynamic block, update it.
27621 - If the cursor is inside a table created by the table.el package,
27622 activate that table.
27624 - If the current buffer is a remember buffer, close note and file it.
27625 with a prefix argument, file it without further interaction to the default
27626 location.
27628 - If the cursor is on a <<<target>>>, update radio targets and corresponding
27629 links in this buffer.
27631 - If the cursor is on a numbered item in a plain list, renumber the
27632 ordered list.
27634 - If the cursor is on a checkbox, toggle it."
27635 (interactive "P")
27636 (let ((org-enable-table-editor t))
27637 (cond
27638 ((or org-clock-overlays
27639 org-occur-highlights
27640 org-latex-fragment-image-overlays)
27641 (org-remove-clock-overlays)
27642 (org-remove-occur-highlights)
27643 (org-remove-latex-fragment-image-overlays)
27644 (message "Temporary highlights/overlays removed from current buffer"))
27645 ((and (local-variable-p 'org-finish-function (current-buffer))
27646 (fboundp org-finish-function))
27647 (funcall org-finish-function))
27648 ((org-at-property-p)
27649 (call-interactively 'org-property-action))
27650 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
27651 ((org-on-heading-p) (call-interactively 'org-set-tags))
27652 ((org-at-table.el-p)
27653 (require 'table)
27654 (beginning-of-line 1)
27655 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
27656 (call-interactively 'table-recognize-table))
27657 ((org-at-table-p)
27658 (org-table-maybe-eval-formula)
27659 (if arg
27660 (call-interactively 'org-table-recalculate)
27661 (org-table-maybe-recalculate-line))
27662 (call-interactively 'org-table-align))
27663 ((org-at-item-checkbox-p)
27664 (call-interactively 'org-toggle-checkbox))
27665 ((org-at-item-p)
27666 (call-interactively 'org-maybe-renumber-ordered-list))
27667 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
27668 ;; Dynamic block
27669 (beginning-of-line 1)
27670 (org-update-dblock))
27671 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
27672 (cond
27673 ((equal (match-string 1) "TBLFM")
27674 ;; Recalculate the table before this line
27675 (save-excursion
27676 (beginning-of-line 1)
27677 (skip-chars-backward " \r\n\t")
27678 (if (org-at-table-p)
27679 (org-call-with-arg 'org-table-recalculate t))))
27681 (call-interactively 'org-mode-restart))))
27682 (t (error "C-c C-c can do nothing useful at this location.")))))
27684 (defun org-mode-restart ()
27685 "Restart Org-mode, to scan again for special lines.
27686 Also updates the keyword regular expressions."
27687 (interactive)
27688 (let ((org-inhibit-startup t)) (org-mode))
27689 (message "Org-mode restarted to refresh keyword and special line setup"))
27691 (defun org-kill-note-or-show-branches ()
27692 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
27693 (interactive)
27694 (if (not org-finish-function)
27695 (call-interactively 'show-branches)
27696 (let ((org-note-abort t))
27697 (funcall org-finish-function))))
27699 (defun org-return (&optional indent)
27700 "Goto next table row or insert a newline.
27701 Calls `org-table-next-row' or `newline', depending on context.
27702 See the individual commands for more information."
27703 (interactive)
27704 (cond
27705 ((bobp) (if indent (newline-and-indent) (newline)))
27706 ((and (org-at-heading-p)
27707 (looking-at
27708 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
27709 (org-show-entry)
27710 (end-of-line 1)
27711 (newline))
27712 ((org-at-table-p)
27713 (org-table-justify-field-maybe)
27714 (call-interactively 'org-table-next-row))
27715 (t (if indent (newline-and-indent) (newline)))))
27717 (defun org-return-indent ()
27718 "Goto next table row or insert a newline and indent.
27719 Calls `org-table-next-row' or `newline-and-indent', depending on
27720 context. See the individual commands for more information."
27721 (interactive)
27722 (org-return t))
27724 (defun org-ctrl-c-star ()
27725 "Compute table, or change heading status of lines.
27726 Calls `org-table-recalculate' or `org-toggle-region-headlines',
27727 depending on context. This will also turn a plain list item or a normal
27728 line into a subheading."
27729 (interactive)
27730 (cond
27731 ((org-at-table-p)
27732 (call-interactively 'org-table-recalculate))
27733 ((org-region-active-p)
27734 ;; Convert all lines in region to list items
27735 (call-interactively 'org-toggle-region-headings))
27736 ((org-on-heading-p)
27737 (org-toggle-region-headings (point-at-bol)
27738 (min (1+ (point-at-eol)) (point-max))))
27739 ((org-at-item-p)
27740 ;; Convert to heading
27741 ;; FIXME: not yet implemented
27743 (t (org-toggle-region-headings (point-at-bol)
27744 (min (1+ (point-at-eol)) (point-max))))))
27746 (defun org-ctrl-c-minus ()
27747 "Insert separator line in table or modify bullet status of line.
27748 Also turns a plain line or a region of lines into list items.
27749 Calls `org-table-insert-hline', `org-toggle-region-items', or
27750 `org-cycle-list-bullet', depending on context."
27751 (interactive)
27752 (cond
27753 ((org-at-table-p)
27754 (call-interactively 'org-table-insert-hline))
27755 ((org-on-heading-p)
27756 ;; Convert to item
27757 (save-excursion
27758 (beginning-of-line 1)
27759 (if (looking-at "\\*+ ")
27760 (replace-match (concat (make-string (- (match-end 0) (point)) ?\ ) "- ")))))
27761 ((org-region-active-p)
27762 ;; Convert all lines in region to list items
27763 (call-interactively 'org-toggle-region-items))
27764 ((org-in-item-p)
27765 (call-interactively 'org-cycle-list-bullet))
27766 (t (org-toggle-region-items (point-at-bol)
27767 (min (1+ (point-at-eol)) (point-max))))))
27769 (defun org-toggle-region-items (beg end)
27770 "Convert all lines in region to list items.
27771 If the first line is already an item, convert all list items in the region
27772 to normal lines."
27773 (interactive "r")
27774 (let (l2 l)
27775 (save-excursion
27776 (goto-char end)
27777 (setq l2 (org-current-line))
27778 (goto-char beg)
27779 (beginning-of-line 1)
27780 (setq l (1- (org-current-line)))
27781 (if (org-at-item-p)
27782 ;; We already have items, de-itemize
27783 (while (< (setq l (1+ l)) l2)
27784 (when (org-at-item-p)
27785 (goto-char (match-beginning 2))
27786 (delete-region (match-beginning 2) (match-end 2))
27787 (and (looking-at "[ \t]+") (replace-match "")))
27788 (beginning-of-line 2))
27789 (while (< (setq l (1+ l)) l2)
27790 (unless (org-at-item-p)
27791 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27792 (replace-match "\\1- \\2")))
27793 (beginning-of-line 2))))))
27795 (defun org-toggle-region-headings (beg end)
27796 "Convert all lines in region to list items.
27797 If the first line is already an item, convert all list items in the region
27798 to normal lines."
27799 (interactive "r")
27800 (let (l2 l)
27801 (save-excursion
27802 (goto-char end)
27803 (setq l2 (org-current-line))
27804 (goto-char beg)
27805 (beginning-of-line 1)
27806 (setq l (1- (org-current-line)))
27807 (if (org-on-heading-p)
27808 ;; We already have headlines, de-star them
27809 (while (< (setq l (1+ l)) l2)
27810 (when (org-on-heading-p t)
27811 (and (looking-at outline-regexp) (replace-match "")))
27812 (beginning-of-line 2))
27813 (let* ((stars (save-excursion
27814 (re-search-backward org-complex-heading-regexp nil t)
27815 (or (match-string 1) "*")))
27816 (add-stars (if org-odd-levels-only "**" "*"))
27817 (rpl (concat stars add-stars " \\2")))
27818 (while (< (setq l (1+ l)) l2)
27819 (unless (org-on-heading-p)
27820 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
27821 (replace-match rpl)))
27822 (beginning-of-line 2)))))))
27824 (defun org-meta-return (&optional arg)
27825 "Insert a new heading or wrap a region in a table.
27826 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
27827 See the individual commands for more information."
27828 (interactive "P")
27829 (cond
27830 ((org-at-table-p)
27831 (call-interactively 'org-table-wrap-region))
27832 (t (call-interactively 'org-insert-heading))))
27834 ;;; Menu entries
27836 ;; Define the Org-mode menus
27837 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
27838 '("Tbl"
27839 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
27840 ["Next Field" org-cycle (org-at-table-p)]
27841 ["Previous Field" org-shifttab (org-at-table-p)]
27842 ["Next Row" org-return (org-at-table-p)]
27843 "--"
27844 ["Blank Field" org-table-blank-field (org-at-table-p)]
27845 ["Edit Field" org-table-edit-field (org-at-table-p)]
27846 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
27847 "--"
27848 ("Column"
27849 ["Move Column Left" org-metaleft (org-at-table-p)]
27850 ["Move Column Right" org-metaright (org-at-table-p)]
27851 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
27852 ["Insert Column" org-shiftmetaright (org-at-table-p)])
27853 ("Row"
27854 ["Move Row Up" org-metaup (org-at-table-p)]
27855 ["Move Row Down" org-metadown (org-at-table-p)]
27856 ["Delete Row" org-shiftmetaup (org-at-table-p)]
27857 ["Insert Row" org-shiftmetadown (org-at-table-p)]
27858 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
27859 "--"
27860 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
27861 ("Rectangle"
27862 ["Copy Rectangle" org-copy-special (org-at-table-p)]
27863 ["Cut Rectangle" org-cut-special (org-at-table-p)]
27864 ["Paste Rectangle" org-paste-special (org-at-table-p)]
27865 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
27866 "--"
27867 ("Calculate"
27868 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
27869 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
27870 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
27871 "--"
27872 ["Recalculate line" org-table-recalculate (org-at-table-p)]
27873 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
27874 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
27875 "--"
27876 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
27877 "--"
27878 ["Sum Column/Rectangle" org-table-sum
27879 (or (org-at-table-p) (org-region-active-p))]
27880 ["Which Column?" org-table-current-column (org-at-table-p)])
27881 ["Debug Formulas"
27882 org-table-toggle-formula-debugger
27883 :style toggle :selected org-table-formula-debug]
27884 ["Show Col/Row Numbers"
27885 org-table-toggle-coordinate-overlays
27886 :style toggle :selected org-table-overlay-coordinates]
27887 "--"
27888 ["Create" org-table-create (and (not (org-at-table-p))
27889 org-enable-table-editor)]
27890 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
27891 ["Import from File" org-table-import (not (org-at-table-p))]
27892 ["Export to File" org-table-export (org-at-table-p)]
27893 "--"
27894 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
27896 (easy-menu-define org-org-menu org-mode-map "Org menu"
27897 '("Org"
27898 ("Show/Hide"
27899 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
27900 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
27901 ["Sparse Tree" org-occur t]
27902 ["Reveal Context" org-reveal t]
27903 ["Show All" show-all t]
27904 "--"
27905 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
27906 "--"
27907 ["New Heading" org-insert-heading t]
27908 ("Navigate Headings"
27909 ["Up" outline-up-heading t]
27910 ["Next" outline-next-visible-heading t]
27911 ["Previous" outline-previous-visible-heading t]
27912 ["Next Same Level" outline-forward-same-level t]
27913 ["Previous Same Level" outline-backward-same-level t]
27914 "--"
27915 ["Jump" org-goto t])
27916 ("Edit Structure"
27917 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
27918 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
27919 "--"
27920 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
27921 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
27922 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
27923 "--"
27924 ["Promote Heading" org-metaleft (not (org-at-table-p))]
27925 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
27926 ["Demote Heading" org-metaright (not (org-at-table-p))]
27927 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
27928 "--"
27929 ["Sort Region/Children" org-sort (not (org-at-table-p))]
27930 "--"
27931 ["Convert to odd levels" org-convert-to-odd-levels t]
27932 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
27933 ("Editing"
27934 ["Emphasis..." org-emphasize t])
27935 ("Archive"
27936 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
27937 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
27938 ; :active t :keys "C-u C-c C-x C-a"]
27939 ["Sparse trees open ARCHIVE trees"
27940 (setq org-sparse-tree-open-archived-trees
27941 (not org-sparse-tree-open-archived-trees))
27942 :style toggle :selected org-sparse-tree-open-archived-trees]
27943 ["Cycling opens ARCHIVE trees"
27944 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
27945 :style toggle :selected org-cycle-open-archived-trees]
27946 ["Agenda includes ARCHIVE trees"
27947 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
27948 :style toggle :selected (not org-agenda-skip-archived-trees)]
27949 "--"
27950 ["Move Subtree to Archive" org-advertized-archive-subtree t]
27951 ; ["Check and Move Children" (org-archive-subtree '(4))
27952 ; :active t :keys "C-u C-c C-x C-s"]
27954 "--"
27955 ("TODO Lists"
27956 ["TODO/DONE/-" org-todo t]
27957 ("Select keyword"
27958 ["Next keyword" org-shiftright (org-on-heading-p)]
27959 ["Previous keyword" org-shiftleft (org-on-heading-p)]
27960 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
27961 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
27962 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
27963 ["Show TODO Tree" org-show-todo-tree t]
27964 ["Global TODO list" org-todo-list t]
27965 "--"
27966 ["Set Priority" org-priority t]
27967 ["Priority Up" org-shiftup t]
27968 ["Priority Down" org-shiftdown t])
27969 ("TAGS and Properties"
27970 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
27971 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
27972 "--"
27973 ["Set property" 'org-set-property t]
27974 ["Column view of properties" org-columns t]
27975 ["Insert Column View DBlock" org-insert-columns-dblock t])
27976 ("Dates and Scheduling"
27977 ["Timestamp" org-time-stamp t]
27978 ["Timestamp (inactive)" org-time-stamp-inactive t]
27979 ("Change Date"
27980 ["1 Day Later" org-shiftright t]
27981 ["1 Day Earlier" org-shiftleft t]
27982 ["1 ... Later" org-shiftup t]
27983 ["1 ... Earlier" org-shiftdown t])
27984 ["Compute Time Range" org-evaluate-time-range t]
27985 ["Schedule Item" org-schedule t]
27986 ["Deadline" org-deadline t]
27987 "--"
27988 ["Custom time format" org-toggle-time-stamp-overlays
27989 :style radio :selected org-display-custom-times]
27990 "--"
27991 ["Goto Calendar" org-goto-calendar t]
27992 ["Date from Calendar" org-date-from-calendar t])
27993 ("Logging work"
27994 ["Clock in" org-clock-in t]
27995 ["Clock out" org-clock-out t]
27996 ["Clock cancel" org-clock-cancel t]
27997 ["Goto running clock" org-clock-goto t]
27998 ["Display times" org-clock-display t]
27999 ["Create clock table" org-clock-report t]
28000 "--"
28001 ["Record DONE time"
28002 (progn (setq org-log-done (not org-log-done))
28003 (message "Switching to %s will %s record a timestamp"
28004 (car org-done-keywords)
28005 (if org-log-done "automatically" "not")))
28006 :style toggle :selected org-log-done])
28007 "--"
28008 ["Agenda Command..." org-agenda t]
28009 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
28010 ("File List for Agenda")
28011 ("Special views current file"
28012 ["TODO Tree" org-show-todo-tree t]
28013 ["Check Deadlines" org-check-deadlines t]
28014 ["Timeline" org-timeline t]
28015 ["Tags Tree" org-tags-sparse-tree t])
28016 "--"
28017 ("Hyperlinks"
28018 ["Store Link (Global)" org-store-link t]
28019 ["Insert Link" org-insert-link t]
28020 ["Follow Link" org-open-at-point t]
28021 "--"
28022 ["Next link" org-next-link t]
28023 ["Previous link" org-previous-link t]
28024 "--"
28025 ["Descriptive Links"
28026 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
28027 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
28028 ["Literal Links"
28029 (progn
28030 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
28031 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))])
28032 "--"
28033 ["Export/Publish..." org-export t]
28034 ("LaTeX"
28035 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
28036 :selected org-cdlatex-mode]
28037 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
28038 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
28039 ["Modify math symbol" org-cdlatex-math-modify
28040 (org-inside-LaTeX-fragment-p)]
28041 ["Export LaTeX fragments as images"
28042 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
28043 :style toggle :selected org-export-with-LaTeX-fragments])
28044 "--"
28045 ("Documentation"
28046 ["Show Version" org-version t]
28047 ["Info Documentation" org-info t])
28048 ("Customize"
28049 ["Browse Org Group" org-customize t]
28050 "--"
28051 ["Expand This Menu" org-create-customize-menu
28052 (fboundp 'customize-menu-create)])
28053 "--"
28054 ["Refresh setup" org-mode-restart t]
28057 (defun org-info (&optional node)
28058 "Read documentation for Org-mode in the info system.
28059 With optional NODE, go directly to that node."
28060 (interactive)
28061 (info (format "(org)%s" (or node ""))))
28063 (defun org-install-agenda-files-menu ()
28064 (let ((bl (buffer-list)))
28065 (save-excursion
28066 (while bl
28067 (set-buffer (pop bl))
28068 (if (org-mode-p) (setq bl nil)))
28069 (when (org-mode-p)
28070 (easy-menu-change
28071 '("Org") "File List for Agenda"
28072 (append
28073 (list
28074 ["Edit File List" (org-edit-agenda-file-list) t]
28075 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
28076 ["Remove Current File from List" org-remove-file t]
28077 ["Cycle through agenda files" org-cycle-agenda-files t]
28078 ["Occur in all agenda files" org-occur-in-agenda-files t]
28079 "--")
28080 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
28082 ;;;; Documentation
28084 (defun org-customize ()
28085 "Call the customize function with org as argument."
28086 (interactive)
28087 (customize-browse 'org))
28089 (defun org-create-customize-menu ()
28090 "Create a full customization menu for Org-mode, insert it into the menu."
28091 (interactive)
28092 (if (fboundp 'customize-menu-create)
28093 (progn
28094 (easy-menu-change
28095 '("Org") "Customize"
28096 `(["Browse Org group" org-customize t]
28097 "--"
28098 ,(customize-menu-create 'org)
28099 ["Set" Custom-set t]
28100 ["Save" Custom-save t]
28101 ["Reset to Current" Custom-reset-current t]
28102 ["Reset to Saved" Custom-reset-saved t]
28103 ["Reset to Standard Settings" Custom-reset-standard t]))
28104 (message "\"Org\"-menu now contains full customization menu"))
28105 (error "Cannot expand menu (outdated version of cus-edit.el)")))
28107 ;;;; Miscellaneous stuff
28110 ;;; Generally useful functions
28112 (defun org-context ()
28113 "Return a list of contexts of the current cursor position.
28114 If several contexts apply, all are returned.
28115 Each context entry is a list with a symbol naming the context, and
28116 two positions indicating start and end of the context. Possible
28117 contexts are:
28119 :headline anywhere in a headline
28120 :headline-stars on the leading stars in a headline
28121 :todo-keyword on a TODO keyword (including DONE) in a headline
28122 :tags on the TAGS in a headline
28123 :priority on the priority cookie in a headline
28124 :item on the first line of a plain list item
28125 :item-bullet on the bullet/number of a plain list item
28126 :checkbox on the checkbox in a plain list item
28127 :table in an org-mode table
28128 :table-special on a special filed in a table
28129 :table-table in a table.el table
28130 :link on a hyperlink
28131 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
28132 :target on a <<target>>
28133 :radio-target on a <<<radio-target>>>
28134 :latex-fragment on a LaTeX fragment
28135 :latex-preview on a LaTeX fragment with overlayed preview image
28137 This function expects the position to be visible because it uses font-lock
28138 faces as a help to recognize the following contexts: :table-special, :link,
28139 and :keyword."
28140 (let* ((f (get-text-property (point) 'face))
28141 (faces (if (listp f) f (list f)))
28142 (p (point)) clist o)
28143 ;; First the large context
28144 (cond
28145 ((org-on-heading-p t)
28146 (push (list :headline (point-at-bol) (point-at-eol)) clist)
28147 (when (progn
28148 (beginning-of-line 1)
28149 (looking-at org-todo-line-tags-regexp))
28150 (push (org-point-in-group p 1 :headline-stars) clist)
28151 (push (org-point-in-group p 2 :todo-keyword) clist)
28152 (push (org-point-in-group p 4 :tags) clist))
28153 (goto-char p)
28154 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
28155 (if (looking-at "\\[#[A-Z0-9]\\]")
28156 (push (org-point-in-group p 0 :priority) clist)))
28158 ((org-at-item-p)
28159 (push (org-point-in-group p 2 :item-bullet) clist)
28160 (push (list :item (point-at-bol)
28161 (save-excursion (org-end-of-item) (point)))
28162 clist)
28163 (and (org-at-item-checkbox-p)
28164 (push (org-point-in-group p 0 :checkbox) clist)))
28166 ((org-at-table-p)
28167 (push (list :table (org-table-begin) (org-table-end)) clist)
28168 (if (memq 'org-formula faces)
28169 (push (list :table-special
28170 (previous-single-property-change p 'face)
28171 (next-single-property-change p 'face)) clist)))
28172 ((org-at-table-p 'any)
28173 (push (list :table-table) clist)))
28174 (goto-char p)
28176 ;; Now the small context
28177 (cond
28178 ((org-at-timestamp-p)
28179 (push (org-point-in-group p 0 :timestamp) clist))
28180 ((memq 'org-link faces)
28181 (push (list :link
28182 (previous-single-property-change p 'face)
28183 (next-single-property-change p 'face)) clist))
28184 ((memq 'org-special-keyword faces)
28185 (push (list :keyword
28186 (previous-single-property-change p 'face)
28187 (next-single-property-change p 'face)) clist))
28188 ((org-on-target-p)
28189 (push (org-point-in-group p 0 :target) clist)
28190 (goto-char (1- (match-beginning 0)))
28191 (if (looking-at org-radio-target-regexp)
28192 (push (org-point-in-group p 0 :radio-target) clist))
28193 (goto-char p))
28194 ((setq o (car (delq nil
28195 (mapcar
28196 (lambda (x)
28197 (if (memq x org-latex-fragment-image-overlays) x))
28198 (org-overlays-at (point))))))
28199 (push (list :latex-fragment
28200 (org-overlay-start o) (org-overlay-end o)) clist)
28201 (push (list :latex-preview
28202 (org-overlay-start o) (org-overlay-end o)) clist))
28203 ((org-inside-LaTeX-fragment-p)
28204 ;; FIXME: positions wrong.
28205 (push (list :latex-fragment (point) (point)) clist)))
28207 (setq clist (nreverse (delq nil clist)))
28208 clist))
28210 ;; FIXME: Compare with at-regexp-p Do we need both?
28211 (defun org-in-regexp (re &optional nlines visually)
28212 "Check if point is inside a match of regexp.
28213 Normally only the current line is checked, but you can include NLINES extra
28214 lines both before and after point into the search.
28215 If VISUALLY is set, require that the cursor is not after the match but
28216 really on, so that the block visually is on the match."
28217 (catch 'exit
28218 (let ((pos (point))
28219 (eol (point-at-eol (+ 1 (or nlines 0))))
28220 (inc (if visually 1 0)))
28221 (save-excursion
28222 (beginning-of-line (- 1 (or nlines 0)))
28223 (while (re-search-forward re eol t)
28224 (if (and (<= (match-beginning 0) pos)
28225 (>= (+ inc (match-end 0)) pos))
28226 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
28228 (defun org-at-regexp-p (regexp)
28229 "Is point inside a match of REGEXP in the current line?"
28230 (catch 'exit
28231 (save-excursion
28232 (let ((pos (point)) (end (point-at-eol)))
28233 (beginning-of-line 1)
28234 (while (re-search-forward regexp end t)
28235 (if (and (<= (match-beginning 0) pos)
28236 (>= (match-end 0) pos))
28237 (throw 'exit t)))
28238 nil))))
28240 (defun org-occur-in-agenda-files (regexp &optional nlines)
28241 "Call `multi-occur' with buffers for all agenda files."
28242 (interactive "sOrg-files matching: \np")
28243 (let* ((files (org-agenda-files))
28244 (tnames (mapcar 'file-truename files))
28245 (extra org-agenda-text-search-extra-files)
28247 (while (setq f (pop extra))
28248 (unless (member (file-truename f) tnames)
28249 (add-to-list 'files f 'append)
28250 (add-to-list 'tnames (file-truename f) 'append)))
28251 (multi-occur
28252 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
28253 regexp)))
28255 (if (boundp 'occur-mode-find-occurrence-hook)
28256 ;; Emacs 23
28257 (add-hook 'occur-mode-find-occurrence-hook
28258 (lambda ()
28259 (when (org-mode-p)
28260 (org-reveal))))
28261 ;; Emacs 22
28262 (defadvice occur-mode-goto-occurrence
28263 (after org-occur-reveal activate)
28264 (and (org-mode-p) (org-reveal)))
28265 (defadvice occur-mode-goto-occurrence-other-window
28266 (after org-occur-reveal activate)
28267 (and (org-mode-p) (org-reveal)))
28268 (defadvice occur-mode-display-occurrence
28269 (after org-occur-reveal activate)
28270 (when (org-mode-p)
28271 (let ((pos (occur-mode-find-occurrence)))
28272 (with-current-buffer (marker-buffer pos)
28273 (save-excursion
28274 (goto-char pos)
28275 (org-reveal)))))))
28277 (defun org-uniquify (list)
28278 "Remove duplicate elements from LIST."
28279 (let (res)
28280 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
28281 res))
28283 (defun org-delete-all (elts list)
28284 "Remove all elements in ELTS from LIST."
28285 (while elts
28286 (setq list (delete (pop elts) list)))
28287 list)
28289 (defun org-back-over-empty-lines ()
28290 "Move backwards over witespace, to the beginning of the first empty line.
28291 Returns the number o empty lines passed."
28292 (let ((pos (point)))
28293 (skip-chars-backward " \t\n\r")
28294 (beginning-of-line 2)
28295 (goto-char (min (point) pos))
28296 (count-lines (point) pos)))
28298 (defun org-skip-whitespace ()
28299 (skip-chars-forward " \t\n\r"))
28301 (defun org-point-in-group (point group &optional context)
28302 "Check if POINT is in match-group GROUP.
28303 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
28304 match. If the match group does ot exist or point is not inside it,
28305 return nil."
28306 (and (match-beginning group)
28307 (>= point (match-beginning group))
28308 (<= point (match-end group))
28309 (if context
28310 (list context (match-beginning group) (match-end group))
28311 t)))
28313 (defun org-switch-to-buffer-other-window (&rest args)
28314 "Switch to buffer in a second window on the current frame.
28315 In particular, do not allow pop-up frames."
28316 (let (pop-up-frames special-display-buffer-names special-display-regexps
28317 special-display-function)
28318 (apply 'switch-to-buffer-other-window args)))
28320 (defun org-combine-plists (&rest plists)
28321 "Create a single property list from all plists in PLISTS.
28322 The process starts by copying the first list, and then setting properties
28323 from the other lists. Settings in the last list are the most significant
28324 ones and overrule settings in the other lists."
28325 (let ((rtn (copy-sequence (pop plists)))
28326 p v ls)
28327 (while plists
28328 (setq ls (pop plists))
28329 (while ls
28330 (setq p (pop ls) v (pop ls))
28331 (setq rtn (plist-put rtn p v))))
28332 rtn))
28334 (defun org-move-line-down (arg)
28335 "Move the current line down. With prefix argument, move it past ARG lines."
28336 (interactive "p")
28337 (let ((col (current-column))
28338 beg end pos)
28339 (beginning-of-line 1) (setq beg (point))
28340 (beginning-of-line 2) (setq end (point))
28341 (beginning-of-line (+ 1 arg))
28342 (setq pos (move-marker (make-marker) (point)))
28343 (insert (delete-and-extract-region beg end))
28344 (goto-char pos)
28345 (move-to-column col)))
28347 (defun org-move-line-up (arg)
28348 "Move the current line up. With prefix argument, move it past ARG lines."
28349 (interactive "p")
28350 (let ((col (current-column))
28351 beg end pos)
28352 (beginning-of-line 1) (setq beg (point))
28353 (beginning-of-line 2) (setq end (point))
28354 (beginning-of-line (- arg))
28355 (setq pos (move-marker (make-marker) (point)))
28356 (insert (delete-and-extract-region beg end))
28357 (goto-char pos)
28358 (move-to-column col)))
28360 (defun org-replace-escapes (string table)
28361 "Replace %-escapes in STRING with values in TABLE.
28362 TABLE is an association list with keys like \"%a\" and string values.
28363 The sequences in STRING may contain normal field width and padding information,
28364 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
28365 so values can contain further %-escapes if they are define later in TABLE."
28366 (let ((case-fold-search nil)
28367 e re rpl)
28368 (while (setq e (pop table))
28369 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
28370 (while (string-match re string)
28371 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
28372 (cdr e)))
28373 (setq string (replace-match rpl t t string))))
28374 string))
28377 (defun org-sublist (list start end)
28378 "Return a section of LIST, from START to END.
28379 Counting starts at 1."
28380 (let (rtn (c start))
28381 (setq list (nthcdr (1- start) list))
28382 (while (and list (<= c end))
28383 (push (pop list) rtn)
28384 (setq c (1+ c)))
28385 (nreverse rtn)))
28387 (defun org-find-base-buffer-visiting (file)
28388 "Like `find-buffer-visiting' but alway return the base buffer and
28389 not an indirect buffer"
28390 (let ((buf (find-buffer-visiting file)))
28391 (if buf
28392 (or (buffer-base-buffer buf) buf)
28393 nil)))
28395 (defun org-image-file-name-regexp ()
28396 "Return regexp matching the file names of images."
28397 (if (fboundp 'image-file-name-regexp)
28398 (image-file-name-regexp)
28399 (let ((image-file-name-extensions
28400 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
28401 "xbm" "xpm" "pbm" "pgm" "ppm")))
28402 (concat "\\."
28403 (regexp-opt (nconc (mapcar 'upcase
28404 image-file-name-extensions)
28405 image-file-name-extensions)
28407 "\\'"))))
28409 (defun org-file-image-p (file)
28410 "Return non-nil if FILE is an image."
28411 (save-match-data
28412 (string-match (org-image-file-name-regexp) file)))
28414 ;;; Paragraph filling stuff.
28415 ;; We want this to be just right, so use the full arsenal.
28417 (defun org-indent-line-function ()
28418 "Indent line like previous, but further if previous was headline or item."
28419 (interactive)
28420 (let* ((pos (point))
28421 (itemp (org-at-item-p))
28422 column bpos bcol tpos tcol bullet btype bullet-type)
28423 ;; Find the previous relevant line
28424 (beginning-of-line 1)
28425 (cond
28426 ((looking-at "#") (setq column 0))
28427 ((looking-at "\\*+ ") (setq column 0))
28429 (beginning-of-line 0)
28430 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
28431 (beginning-of-line 0))
28432 (cond
28433 ((looking-at "\\*+[ \t]+")
28434 (goto-char (match-end 0))
28435 (setq column (current-column)))
28436 ((org-in-item-p)
28437 (org-beginning-of-item)
28438 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28439 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
28440 (setq bpos (match-beginning 1) tpos (match-end 0)
28441 bcol (progn (goto-char bpos) (current-column))
28442 tcol (progn (goto-char tpos) (current-column))
28443 bullet (match-string 1)
28444 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
28445 (if (not itemp)
28446 (setq column tcol)
28447 (goto-char pos)
28448 (beginning-of-line 1)
28449 (if (looking-at "\\S-")
28450 (progn
28451 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
28452 (setq bullet (match-string 1)
28453 btype (if (string-match "[0-9]" bullet) "n" bullet))
28454 (setq column (if (equal btype bullet-type) bcol tcol)))
28455 (setq column (org-get-indentation)))))
28456 (t (setq column (org-get-indentation))))))
28457 (goto-char pos)
28458 (if (<= (current-column) (current-indentation))
28459 (indent-line-to column)
28460 (save-excursion (indent-line-to column)))
28461 (setq column (current-column))
28462 (beginning-of-line 1)
28463 (if (looking-at
28464 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
28465 (replace-match (concat "\\1" (format org-property-format
28466 (match-string 2) (match-string 3)))
28467 t nil))
28468 (move-to-column column)))
28470 (defun org-set-autofill-regexps ()
28471 (interactive)
28472 ;; In the paragraph separator we include headlines, because filling
28473 ;; text in a line directly attached to a headline would otherwise
28474 ;; fill the headline as well.
28475 (org-set-local 'comment-start-skip "^#+[ \t]*")
28476 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
28477 ;; The paragraph starter includes hand-formatted lists.
28478 (org-set-local 'paragraph-start
28479 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
28480 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
28481 ;; But only if the user has not turned off tables or fixed-width regions
28482 (org-set-local
28483 'auto-fill-inhibit-regexp
28484 (concat "\\*+ \\|#\\+"
28485 "\\|[ \t]*" org-keyword-time-regexp
28486 (if (or org-enable-table-editor org-enable-fixed-width-editor)
28487 (concat
28488 "\\|[ \t]*["
28489 (if org-enable-table-editor "|" "")
28490 (if org-enable-fixed-width-editor ":" "")
28491 "]"))))
28492 ;; We use our own fill-paragraph function, to make sure that tables
28493 ;; and fixed-width regions are not wrapped. That function will pass
28494 ;; through to `fill-paragraph' when appropriate.
28495 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
28496 ; Adaptive filling: To get full control, first make sure that
28497 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
28498 (org-set-local 'adaptive-fill-regexp "\000")
28499 (org-set-local 'adaptive-fill-function
28500 'org-adaptive-fill-function)
28501 (org-set-local
28502 'align-mode-rules-list
28503 '((org-in-buffer-settings
28504 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
28505 (modes . '(org-mode))))))
28507 (defun org-fill-paragraph (&optional justify)
28508 "Re-align a table, pass through to fill-paragraph if no table."
28509 (let ((table-p (org-at-table-p))
28510 (table.el-p (org-at-table.el-p)))
28511 (cond ((and (equal (char-after (point-at-bol)) ?*)
28512 (save-excursion (goto-char (point-at-bol))
28513 (looking-at outline-regexp)))
28514 t) ; skip headlines
28515 (table.el-p t) ; skip table.el tables
28516 (table-p (org-table-align) t) ; align org-mode tables
28517 (t nil)))) ; call paragraph-fill
28519 ;; For reference, this is the default value of adaptive-fill-regexp
28520 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
28522 (defun org-adaptive-fill-function ()
28523 "Return a fill prefix for org-mode files.
28524 In particular, this makes sure hanging paragraphs for hand-formatted lists
28525 work correctly."
28526 (cond ((looking-at "#[ \t]+")
28527 (match-string 0))
28528 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
28529 (save-excursion
28530 (goto-char (match-end 0))
28531 (make-string (current-column) ?\ )))
28532 (t nil)))
28534 ;;;; Functions extending outline functionality
28537 (defun org-beginning-of-line (&optional arg)
28538 "Go to the beginning of the current line. If that is invisible, continue
28539 to a visible line beginning. This makes the function of C-a more intuitive.
28540 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28541 first attempt, and only move to after the tags when the cursor is already
28542 beyond the end of the headline."
28543 (interactive "P")
28544 (let ((pos (point)))
28545 (beginning-of-line 1)
28546 (if (bobp)
28548 (backward-char 1)
28549 (if (org-invisible-p)
28550 (while (and (not (bobp)) (org-invisible-p))
28551 (backward-char 1)
28552 (beginning-of-line 1))
28553 (forward-char 1)))
28554 (when org-special-ctrl-a/e
28555 (cond
28556 ((and (looking-at org-todo-line-regexp)
28557 (= (char-after (match-end 1)) ?\ ))
28558 (goto-char
28559 (if (eq org-special-ctrl-a/e t)
28560 (cond ((> pos (match-beginning 3)) (match-beginning 3))
28561 ((= pos (point)) (match-beginning 3))
28562 (t (point)))
28563 (cond ((> pos (point)) (point))
28564 ((not (eq last-command this-command)) (point))
28565 (t (match-beginning 3))))))
28566 ((org-at-item-p)
28567 (goto-char
28568 (if (eq org-special-ctrl-a/e t)
28569 (cond ((> pos (match-end 4)) (match-end 4))
28570 ((= pos (point)) (match-end 4))
28571 (t (point)))
28572 (cond ((> pos (point)) (point))
28573 ((not (eq last-command this-command)) (point))
28574 (t (match-end 4))))))))))
28576 (defun org-end-of-line (&optional arg)
28577 "Go to the end of the line.
28578 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
28579 first attempt, and only move to after the tags when the cursor is already
28580 beyond the end of the headline."
28581 (interactive "P")
28582 (if (or (not org-special-ctrl-a/e)
28583 (not (org-on-heading-p)))
28584 (end-of-line arg)
28585 (let ((pos (point)))
28586 (beginning-of-line 1)
28587 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
28588 (if (eq org-special-ctrl-a/e t)
28589 (if (or (< pos (match-beginning 1))
28590 (= pos (match-end 0)))
28591 (goto-char (match-beginning 1))
28592 (goto-char (match-end 0)))
28593 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
28594 (goto-char (match-end 0))
28595 (goto-char (match-beginning 1))))
28596 (end-of-line arg)))))
28598 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
28599 (define-key org-mode-map "\C-e" 'org-end-of-line)
28601 (defun org-kill-line (&optional arg)
28602 "Kill line, to tags or end of line."
28603 (interactive "P")
28604 (cond
28605 ((or (not org-special-ctrl-k)
28606 (bolp)
28607 (not (org-on-heading-p)))
28608 (call-interactively 'kill-line))
28609 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
28610 (kill-region (point) (match-beginning 1))
28611 (org-set-tags nil t))
28612 (t (kill-region (point) (point-at-eol)))))
28614 (define-key org-mode-map "\C-k" 'org-kill-line)
28616 (defun org-invisible-p ()
28617 "Check if point is at a character currently not visible."
28618 ;; Early versions of noutline don't have `outline-invisible-p'.
28619 (if (fboundp 'outline-invisible-p)
28620 (outline-invisible-p)
28621 (get-char-property (point) 'invisible)))
28623 (defun org-invisible-p2 ()
28624 "Check if point is at a character currently not visible."
28625 (save-excursion
28626 (if (and (eolp) (not (bobp))) (backward-char 1))
28627 ;; Early versions of noutline don't have `outline-invisible-p'.
28628 (if (fboundp 'outline-invisible-p)
28629 (outline-invisible-p)
28630 (get-char-property (point) 'invisible))))
28632 (defalias 'org-back-to-heading 'outline-back-to-heading)
28633 (defalias 'org-on-heading-p 'outline-on-heading-p)
28634 (defalias 'org-at-heading-p 'outline-on-heading-p)
28635 (defun org-at-heading-or-item-p ()
28636 (or (org-on-heading-p) (org-at-item-p)))
28638 (defun org-on-target-p ()
28639 (or (org-in-regexp org-radio-target-regexp)
28640 (org-in-regexp org-target-regexp)))
28642 (defun org-up-heading-all (arg)
28643 "Move to the heading line of which the present line is a subheading.
28644 This function considers both visible and invisible heading lines.
28645 With argument, move up ARG levels."
28646 (if (fboundp 'outline-up-heading-all)
28647 (outline-up-heading-all arg) ; emacs 21 version of outline.el
28648 (outline-up-heading arg t))) ; emacs 22 version of outline.el
28650 (defun org-up-heading-safe ()
28651 "Move to the heading line of which the present line is a subheading.
28652 This version will not throw an error. It will return the level of the
28653 headline found, or nil if no higher level is found."
28654 (let ((pos (point)) start-level level
28655 (re (concat "^" outline-regexp)))
28656 (catch 'exit
28657 (outline-back-to-heading t)
28658 (setq start-level (funcall outline-level))
28659 (if (equal start-level 1) (throw 'exit nil))
28660 (while (re-search-backward re nil t)
28661 (setq level (funcall outline-level))
28662 (if (< level start-level) (throw 'exit level)))
28663 nil)))
28665 (defun org-first-sibling-p ()
28666 "Is this heading the first child of its parents?"
28667 (interactive)
28668 (let ((re (concat "^" outline-regexp))
28669 level l)
28670 (unless (org-at-heading-p t)
28671 (error "Not at a heading"))
28672 (setq level (funcall outline-level))
28673 (save-excursion
28674 (if (not (re-search-backward re nil t))
28676 (setq l (funcall outline-level))
28677 (< l level)))))
28679 (defun org-goto-sibling (&optional previous)
28680 "Goto the next sibling, even if it is invisible.
28681 When PREVIOUS is set, go to the previous sibling instead. Returns t
28682 when a sibling was found. When none is found, return nil and don't
28683 move point."
28684 (let ((fun (if previous 're-search-backward 're-search-forward))
28685 (pos (point))
28686 (re (concat "^" outline-regexp))
28687 level l)
28688 (when (condition-case nil (org-back-to-heading t) (error nil))
28689 (setq level (funcall outline-level))
28690 (catch 'exit
28691 (or previous (forward-char 1))
28692 (while (funcall fun re nil t)
28693 (setq l (funcall outline-level))
28694 (when (< l level) (goto-char pos) (throw 'exit nil))
28695 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
28696 (goto-char pos)
28697 nil))))
28699 (defun org-show-siblings ()
28700 "Show all siblings of the current headline."
28701 (save-excursion
28702 (while (org-goto-sibling) (org-flag-heading nil)))
28703 (save-excursion
28704 (while (org-goto-sibling 'previous)
28705 (org-flag-heading nil))))
28707 (defun org-show-hidden-entry ()
28708 "Show an entry where even the heading is hidden."
28709 (save-excursion
28710 (org-show-entry)))
28712 (defun org-flag-heading (flag &optional entry)
28713 "Flag the current heading. FLAG non-nil means make invisible.
28714 When ENTRY is non-nil, show the entire entry."
28715 (save-excursion
28716 (org-back-to-heading t)
28717 ;; Check if we should show the entire entry
28718 (if entry
28719 (progn
28720 (org-show-entry)
28721 (save-excursion
28722 (and (outline-next-heading)
28723 (org-flag-heading nil))))
28724 (outline-flag-region (max (point-min) (1- (point)))
28725 (save-excursion (outline-end-of-heading) (point))
28726 flag))))
28728 (defun org-end-of-subtree (&optional invisible-OK to-heading)
28729 ;; This is an exact copy of the original function, but it uses
28730 ;; `org-back-to-heading', to make it work also in invisible
28731 ;; trees. And is uses an invisible-OK argument.
28732 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
28733 (org-back-to-heading invisible-OK)
28734 (let ((first t)
28735 (level (funcall outline-level)))
28736 (while (and (not (eobp))
28737 (or first (> (funcall outline-level) level)))
28738 (setq first nil)
28739 (outline-next-heading))
28740 (unless to-heading
28741 (if (memq (preceding-char) '(?\n ?\^M))
28742 (progn
28743 ;; Go to end of line before heading
28744 (forward-char -1)
28745 (if (memq (preceding-char) '(?\n ?\^M))
28746 ;; leave blank line before heading
28747 (forward-char -1))))))
28748 (point))
28750 (defun org-show-subtree ()
28751 "Show everything after this heading at deeper levels."
28752 (outline-flag-region
28753 (point)
28754 (save-excursion
28755 (outline-end-of-subtree) (outline-next-heading) (point))
28756 nil))
28758 (defun org-show-entry ()
28759 "Show the body directly following this heading.
28760 Show the heading too, if it is currently invisible."
28761 (interactive)
28762 (save-excursion
28763 (condition-case nil
28764 (progn
28765 (org-back-to-heading t)
28766 (outline-flag-region
28767 (max (point-min) (1- (point)))
28768 (save-excursion
28769 (re-search-forward
28770 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
28771 (or (match-beginning 1) (point-max)))
28772 nil))
28773 (error nil))))
28775 (defun org-make-options-regexp (kwds)
28776 "Make a regular expression for keyword lines."
28777 (concat
28779 "#?[ \t]*\\+\\("
28780 (mapconcat 'regexp-quote kwds "\\|")
28781 "\\):[ \t]*"
28782 "\\(.+\\)"))
28784 ;; Make isearch reveal the necessary context
28785 (defun org-isearch-end ()
28786 "Reveal context after isearch exits."
28787 (when isearch-success ; only if search was successful
28788 (if (featurep 'xemacs)
28789 ;; Under XEmacs, the hook is run in the correct place,
28790 ;; we directly show the context.
28791 (org-show-context 'isearch)
28792 ;; In Emacs the hook runs *before* restoring the overlays.
28793 ;; So we have to use a one-time post-command-hook to do this.
28794 ;; (Emacs 22 has a special variable, see function `org-mode')
28795 (unless (and (boundp 'isearch-mode-end-hook-quit)
28796 isearch-mode-end-hook-quit)
28797 ;; Only when the isearch was not quitted.
28798 (org-add-hook 'post-command-hook 'org-isearch-post-command
28799 'append 'local)))))
28801 (defun org-isearch-post-command ()
28802 "Remove self from hook, and show context."
28803 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
28804 (org-show-context 'isearch))
28807 ;;;; Integration with and fixes for other packages
28809 ;;; Imenu support
28811 (defvar org-imenu-markers nil
28812 "All markers currently used by Imenu.")
28813 (make-variable-buffer-local 'org-imenu-markers)
28815 (defun org-imenu-new-marker (&optional pos)
28816 "Return a new marker for use by Imenu, and remember the marker."
28817 (let ((m (make-marker)))
28818 (move-marker m (or pos (point)))
28819 (push m org-imenu-markers)
28822 (defun org-imenu-get-tree ()
28823 "Produce the index for Imenu."
28824 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
28825 (setq org-imenu-markers nil)
28826 (let* ((n org-imenu-depth)
28827 (re (concat "^" outline-regexp))
28828 (subs (make-vector (1+ n) nil))
28829 (last-level 0)
28830 m tree level head)
28831 (save-excursion
28832 (save-restriction
28833 (widen)
28834 (goto-char (point-max))
28835 (while (re-search-backward re nil t)
28836 (setq level (org-reduced-level (funcall outline-level)))
28837 (when (<= level n)
28838 (looking-at org-complex-heading-regexp)
28839 (setq head (org-match-string-no-properties 4)
28840 m (org-imenu-new-marker))
28841 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
28842 (if (>= level last-level)
28843 (push (cons head m) (aref subs level))
28844 (push (cons head (aref subs (1+ level))) (aref subs level))
28845 (loop for i from (1+ level) to n do (aset subs i nil)))
28846 (setq last-level level)))))
28847 (aref subs 1)))
28849 (eval-after-load "imenu"
28850 '(progn
28851 (add-hook 'imenu-after-jump-hook
28852 (lambda () (org-show-context 'org-goto)))))
28854 ;; Speedbar support
28856 (defun org-speedbar-set-agenda-restriction ()
28857 "Restrict future agenda commands to the location at point in speedbar.
28858 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
28859 (interactive)
28860 (let (p m tp np dir txt w)
28861 (cond
28862 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28863 'org-imenu t))
28864 (setq m (get-text-property p 'org-imenu-marker))
28865 (save-excursion
28866 (save-restriction
28867 (set-buffer (marker-buffer m))
28868 (goto-char m)
28869 (org-agenda-set-restriction-lock 'subtree))))
28870 ((setq p (text-property-any (point-at-bol) (point-at-eol)
28871 'speedbar-function 'speedbar-find-file))
28872 (setq tp (previous-single-property-change
28873 (1+ p) 'speedbar-function)
28874 np (next-single-property-change
28875 tp 'speedbar-function)
28876 dir (speedbar-line-directory)
28877 txt (buffer-substring-no-properties (or tp (point-min))
28878 (or np (point-max))))
28879 (save-excursion
28880 (save-restriction
28881 (set-buffer (find-file-noselect
28882 (let ((default-directory dir))
28883 (expand-file-name txt))))
28884 (unless (org-mode-p)
28885 (error "Cannot restrict to non-Org-mode file"))
28886 (org-agenda-set-restriction-lock 'file))))
28887 (t (error "Don't know how to restrict Org-mode's agenda")))
28888 (org-move-overlay org-speedbar-restriction-lock-overlay
28889 (point-at-bol) (point-at-eol))
28890 (setq current-prefix-arg nil)
28891 (org-agenda-maybe-redo)))
28893 (eval-after-load "speedbar"
28894 '(progn
28895 (speedbar-add-supported-extension ".org")
28896 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
28897 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
28898 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
28899 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
28900 (add-hook 'speedbar-visiting-tag-hook
28901 (lambda () (org-show-context 'org-goto)))))
28904 ;;; Fixes and Hacks
28906 ;; Make flyspell not check words in links, to not mess up our keymap
28907 (defun org-mode-flyspell-verify ()
28908 "Don't let flyspell put overlays at active buttons."
28909 (not (get-text-property (point) 'keymap)))
28911 ;; Make `bookmark-jump' show the jump location if it was hidden.
28912 (eval-after-load "bookmark"
28913 '(if (boundp 'bookmark-after-jump-hook)
28914 ;; We can use the hook
28915 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
28916 ;; Hook not available, use advice
28917 (defadvice bookmark-jump (after org-make-visible activate)
28918 "Make the position visible."
28919 (org-bookmark-jump-unhide))))
28921 (defun org-bookmark-jump-unhide ()
28922 "Unhide the current position, to show the bookmark location."
28923 (and (org-mode-p)
28924 (or (org-invisible-p)
28925 (save-excursion (goto-char (max (point-min) (1- (point))))
28926 (org-invisible-p)))
28927 (org-show-context 'bookmark-jump)))
28929 ;; Make session.el ignore our circular variable
28930 (eval-after-load "session"
28931 '(add-to-list 'session-globals-exclude 'org-mark-ring))
28933 ;;;; Experimental code
28935 (defun org-closed-in-range ()
28936 "Sparse tree of items closed in a certain time range.
28937 Still experimental, may disappear in the future."
28938 (interactive)
28939 ;; Get the time interval from the user.
28940 (let* ((time1 (time-to-seconds
28941 (org-read-date nil 'to-time nil "Starting date: ")))
28942 (time2 (time-to-seconds
28943 (org-read-date nil 'to-time nil "End date:")))
28944 ;; callback function
28945 (callback (lambda ()
28946 (let ((time
28947 (time-to-seconds
28948 (apply 'encode-time
28949 (org-parse-time-string
28950 (match-string 1))))))
28951 ;; check if time in interval
28952 (and (>= time time1) (<= time time2))))))
28953 ;; make tree, check each match with the callback
28954 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
28957 ;;;; Finish up
28959 (provide 'org)
28961 (run-hooks 'org-load-hook)
28963 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
28964 ;;; org.el ends here